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/g2901_3000/s2926_maximum_balanced_subsequence_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2926_maximum_balanced_subsequence_sum // #Hard #Array #Dynamic_Programming #Binary_Search #Segment_Tree #Binary_Indexed_Tree // #2024_01_16_Time_636_ms_(100.00%)_Space_66.4_MB_(66.67%) import kotlin.math.max @Suppress("NAME_SHADOWING") class Solution { fun maxBalancedSubsequenceSum(nums: IntArray): Long { val n = nums.size var m = 0 val arr = IntArray(n) var max = Int.MIN_VALUE for (i in 0 until n) { val x = nums[i] if (x > 0) { arr[m++] = x - i } else if (x > max) { max = x } } if (m == 0) { return max.toLong() } arr.sort() val map: MutableMap<Int, Int> = HashMap(m shl 1) var pre = Int.MIN_VALUE var index = 1 for (x in arr) { if (x == pre) { continue } map[x] = index++ pre = x } val bit = BIT(index) var ans: Long = 0 for (i in 0 until n) { if (nums[i] <= 0) { continue } index = map[nums[i] - i]!! val cur = bit.query(index) + nums[i] bit.update(index, cur) ans = max(ans, cur) } return ans } private class BIT(var n: Int) { var tree: LongArray = LongArray(n + 1) fun lowbit(index: Int): Int { return index and (-index) } fun update(index: Int, v: Long) { var index = index while (index <= n && tree[index] < v) { tree[index] = v index += lowbit(index) } } fun query(index: Int): Long { var index = index var result: Long = 0 while (index > 0) { result = max(tree[index].toDouble(), result.toDouble()).toLong() index -= lowbit(index) } return result } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,035
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/leonra/adventofcode/advent2023/day02/Day2.kt
LeonRa
726,688,446
false
{"Kotlin": 30456}
package com.leonra.adventofcode.advent2023.day02 import com.leonra.adventofcode.shared.readResource import kotlin.math.max /** https://adventofcode.com/2023/day/2 */ private object Day2 { fun partOne(): Int { val redMax = 12 val greenMax = 13 val blueMax = 14 var sum = 0 readResource("/2023/day02/part1.txt") { line -> var isGameValid = true val pulls = line.split(DELIMITER) for (pull in pulls) { val redCount = pull.ballCount(RED_BALLS) val greenCount = pull.ballCount(GREEN_BALLS) val blueCount = pull.ballCount(BLUE_BALLS) if (redCount > redMax || greenCount > greenMax || blueCount > blueMax) { isGameValid = false break } } if (isGameValid) { GAME_ID.find(line)?.let { sum += it.groups[1]?.value?.toInt() ?: 0 } } } return sum } fun partTwo(): Int { var sum = 0 readResource("/2023/day02/part1.txt") { line -> var minRed = 0 var minBlue = 0 var minGreen = 0 val pulls = line.split(DELIMITER) for (pull in pulls) { val redCount = pull.ballCount(RED_BALLS) val greenCount = pull.ballCount(GREEN_BALLS) val blueCount = pull.ballCount(BLUE_BALLS) minRed = max(minRed, redCount) minGreen = max(minGreen, greenCount) minBlue = max(minBlue, blueCount) } sum += (minRed * minBlue * minGreen) } return sum } private val GAME_ID = Regex("Game (\\d+):") private val DELIMITER = Regex("[:;]") private val RED_BALLS = Regex("(\\d+) red") private val GREEN_BALLS = Regex("(\\d+) green") private val BLUE_BALLS = Regex("(\\d+) blue") private fun String.ballCount(ballRegex: Regex): Int = ballRegex.find(this)?.let { it.groups[1]?.value?.toInt() } ?: 0 } private fun main() { println("Part 1 sum: ${Day2.partOne()}") println("Part 2 sum: ${Day2.partTwo()}") }
0
Kotlin
0
0
46bdb5d54abf834b244ba9657d0d4c81a2d92487
2,194
AdventOfCode
Apache License 2.0
app/src/main/java/online/vapcom/codewars/strings/MostFrequentlyUsedWords.kt
vapcomm
503,057,535
false
{"Kotlin": 142486}
package online.vapcom.codewars.strings /** * #24 Most frequently used words in a text - 4 kyu * * https://www.codewars.com/kata/51e056fe544cf36c410000fb/train/kotlin */ fun top3(str: String): List<String> { fun plusOne(map: HashMap<String, Int>, word: String) { map.merge(word, 1) { old, value -> old + value } } println("\n== str: '$str'") val counters = hashMapOf<String, Int>() val sb = StringBuilder() var state = Top3State.SPACE str.forEach { c -> when (state) { Top3State.SPACE -> { if (c.isLetter()) { sb.append(c) state = Top3State.WORD } else if (c == '\'') { sb.append(c) state = Top3State.APOSTROPHE } } Top3State.WORD -> { if (c.isLetter() || c == '\'') sb.append(c) else { plusOne(counters, sb.toString().lowercase()) sb.clear() state = Top3State.SPACE } } Top3State.APOSTROPHE -> { if (c.isLetter()) { sb.append(c) state = Top3State.WORD } else { sb.clear() state = Top3State.SPACE } } } } if (sb.isNotEmpty()) // last word plusOne(counters, sb.toString().lowercase()) println("\n-- counters: $counters") if (counters.isEmpty()) return emptyList() // find top3 words val maxes = Array(3) { "" } var m0 = 0 var m1 = 0 var m2 = 0 counters.forEach { entry -> if (entry.value > m0) { m2 = m1; m1 = m0 m0 = entry.value maxes[2] = maxes[1] maxes[1] = maxes[0] maxes[0] = entry.key } else if (entry.value > m1) { m2 = m1 m1 = entry.value maxes[2] = maxes[1] maxes[1] = entry.key } else if (entry.value > m2) { m2 = entry.value maxes[2] = entry.key } } val result = maxes.filter { it.isNotEmpty() } println("-- MAX: maxes: ${maxes.joinToString()}, result: $result") return result } private enum class Top3State { SPACE, WORD, APOSTROPHE }
0
Kotlin
0
0
97b50e8e25211f43ccd49bcee2395c4bc942a37a
2,430
codewars
MIT License
src/Day01.kt
ked4ma
573,017,240
false
{"Kotlin": 51348}
/** * [Day01](https://adventofcode.com/2022/day/1) */ fun main() { fun convInput(input: List<String>): List<Int> = buildList { var list = ArrayList<Int>() for (s in input) { if (s.isEmpty()) { if (list.size > 0) { add(list) list = ArrayList() } } else { list.add(s.toInt()) } } if (list.isNotEmpty()) { add(list) } }.map(ArrayList<Int>::sum) fun part1(input: List<String>): Int { val conv = convInput(input) return conv.max() } fun part2(input: List<String>): Int { val conv = convInput(input) return conv.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
1
Kotlin
0
0
6d4794d75b33c4ca7e83e45a85823e828c833c62
1,022
aoc-in-kotlin-2022
Apache License 2.0
src/pl/shockah/aoc/y2021/Day4.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2021 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.unikorn.collection.Array2D class Day4: AdventTask<Day4.Input, Int, Int>(2021, 4) { data class Input( val rng: List<Int>, val boards: List<Array2D<Int>> ) override fun parseInput(rawInput: String): Input { var lines = rawInput.trim().lines().toMutableList() val rng = lines.removeFirst().split(',').map { it.toInt() } val boards = mutableListOf<Array2D<Int>>() while (lines.isNotEmpty()) { if (lines.first().isEmpty()) { lines.removeFirst() continue } val boardLines = lines .takeWhile { it.isNotEmpty() } .map { it.trim().split(Regex("\\D+")).map { it.toInt() } } require(boardLines.map { it.size }.toSet().size == 1) require(boardLines.size == boardLines.first().size) lines = lines.drop(boardLines.size).toMutableList() boards += Array2D(boardLines.first().size, boardLines.size) { x, y -> boardLines[y][x] } } return Input(rng, boards) } private fun Array2D<Int?>.isWinningBoard(): Boolean { (0 until width).forEach { if (getColumn(it).all { it == null }) return true if (getRow(it).all { it == null }) return true } // diagonals // if ((0 until width).all { this[it, it] == null }) // return true // if ((0 until width).all { this[width - it - 1, it] == null }) // return true return false } override fun part1(input: Input): Int { var boards = input.boards.map { Array2D<Int?>(it.width, it.height) { x, y -> it[x, y] } } input.rng.forEach { rng -> boards = boards.map { board -> board.map { it -> it.takeUnless { it == rng } } } boards.forEach { if (it.isWinningBoard()) return it.toList().filterNotNull().sum() * rng } } throw IllegalStateException("No winning board, no more random numbers.") } override fun part2(input: Input): Int { var boards = input.boards.map { Array2D<Int?>(it.width, it.height) { x, y -> it[x, y] } } input.rng.forEach { rng -> boards = boards.map { board -> board.map { it -> it.takeUnless { it == rng } } } val winningBoards = boards.filter { it.isWinningBoard() } if (boards.size - winningBoards.size == 0) { val board = winningBoards.first() return board.toList().filterNotNull().sum() * rng } boards -= winningBoards } throw IllegalStateException("No winning board, no more random numbers.") } class Tests { private val task = Day4() private val rawInput = """ 7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 22 13 17 11 0 8 2 23 4 24 21 9 14 16 7 6 10 3 18 5 1 12 20 15 19 3 15 0 2 22 9 18 13 17 5 19 8 7 25 23 20 11 10 24 4 14 21 16 12 6 14 21 17 24 4 10 16 15 9 19 18 8 23 26 20 22 11 13 6 5 2 0 12 3 7 """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(4512, task.part1(input)) } @Test fun part2() { val input = task.parseInput(rawInput) Assertions.assertEquals(1924, task.part2(input)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
3,139
Advent-of-Code
Apache License 2.0
Kotlin/search/TernarySearch.kt
HarshCasper
274,711,817
false
{"C++": 1488046, "Java": 948670, "Python": 703942, "C": 615475, "JavaScript": 228879, "Go": 166382, "Dart": 107821, "Julia": 82766, "C#": 76519, "Kotlin": 40240, "PHP": 5465}
//Kotlin program to implement ternary search using recursive approach import java.util.* // A function to declare ternary search fun ternarySearch(left:Int, right:Int, key:Int, array: ArrayList<Int>): Int{ if (right >= left) { // Finding the midterms val mid1 = left + (right - left) / 3 val mid2 = right - (right - left) / 3 // Check if the value is present in the first mid term if (array[mid1] == key) { return mid1 } // Check if the value is present in the second mid term if (array[mid2] == key) { return mid2 } // If the element is not present in the mid positions, the following cases can be a possibility. // Checking if the value is less than mid1 element if (key < array[mid1]) { return ternarySearch(left, mid1 - 1, key, array) } // Checking if the value is greater than mid2 element else if (key > array[mid2]) { return ternarySearch(mid2 + 1, right, key, array) } // The last possibility is that, the element may be present between the mid1 and mid2 else { return ternarySearch(mid1 + 1, mid2 - 1, key, array) } } // If all the possibilities fail, the element is not present inside the array return -1 } //Testing code fun main(){ val input = Scanner(System.`in`) println("Enter the length of the array") val arrayLength = input.nextInt() val arrayOfElements = arrayListOf<Int>() println("Enter the elements of the array in ascending order") for(index in 0 until arrayLength) { val element = input.nextInt() arrayOfElements.add(element) } print("Enter the number you want to search for :") val number = input.nextInt() input.close() val left:Int = -1 val right:Int = arrayLength - 1 // Search the number using ternarySearch val position = ternarySearch(left, right, number, arrayOfElements) + 1 if(position == 0) println("Key: $number is not present in the array") else println("Key: $number is present in the array at position $position") } /* Sample Test Cases:- Test Case 1:- Enter the length of the array 5 Enter the elements of the array in ascending order 1 2 3 4 5 Enter the number you want to search for :5 Key: 5 is present in the array at position 5 Test Case 2:- Enter the length of the array 5 Enter the elements of the array in ascending order 10 20 30 40 50 Enter the number you want to search for :60 Key: 60 is not present in the array Time Complexity:- The time complexity of this algorithm is O(log3n), where n is the size of the array Space cComplexity:- The space complexity of this algorithm is O(1), which is constant, irrespective of any case. */
2
C++
1,086
877
4f1e5bdd6d9d899fa354de94740e0aecf5ecd2be
2,901
NeoAlgo
MIT License
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day24.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day24 : Day<Int> { private enum class Color { WHITE, BLACK } private fun Color.flip(): Color = when (this) { Color.WHITE -> Color.BLACK Color.BLACK -> Color.WHITE } private enum class Direction { EAST, SOUTHEAST, SOUTHWEST, WEST, NORTHWEST, NORTHEAST } private data class Vector(val x: Int, val y: Int) private operator fun Vector.plus(vector: Vector) = Vector( x = x + vector.x, y = y + vector.y ) private data class Tile(val color: Color = Color.WHITE) private tailrec fun readDirections(rest: String, acc: List<Direction> = emptyList()): List<Direction> { if (rest.isEmpty()) return acc val dir = when (rest.take(2)) { "se" -> Direction.SOUTHEAST "sw" -> Direction.SOUTHWEST "ne" -> Direction.NORTHEAST "nw" -> Direction.NORTHWEST else -> when (rest.take(1)) { "e" -> Direction.EAST "w" -> Direction.WEST else -> throw IllegalArgumentException(rest) } } return readDirections( rest = rest.drop(if (dir in listOf(Direction.EAST, Direction.WEST)) 1 else 2), acc = acc + dir ) } private val tilesToFlipOver: List<List<Direction>> = readDayInput() .lines() .map(::readDirections) private val Direction.asVector: Vector get() = when (this) { Direction.EAST -> Vector(x = 1, y = 0) Direction.WEST -> Vector(x = -1, y = 0) Direction.SOUTHEAST -> Vector(x = 1, y = -1) Direction.SOUTHWEST -> Vector(x = 0, y = -1) Direction.NORTHWEST -> Vector(x = -1, y = 1) Direction.NORTHEAST -> Vector(x = 0, y = 1) } private data class State( val tiles: Map<Vector, Tile> = emptyMap(), val xRange: IntRange = IntRange.EMPTY, val yRange: IntRange = IntRange.EMPTY ) private fun State.addPath(path: List<Direction>): State { val tilePosition: Vector = path.fold(Vector(0, 0)) { acc, direction -> acc + direction.asVector } val flippedTile = tiles.getOrElse(tilePosition) { Tile() }.let { tile -> tile.copy(color = tile.color.flip()) } return copy(tiles = tiles + (tilePosition to flippedTile)) } private val Vector.adjacent: List<Vector> get() = Direction.values().map { direction -> this + direction.asVector } private fun State.countAdjacentBlackTiles(vector: Vector): Int { return vector.adjacent.count { adjacent -> tiles.getOrElse(adjacent) { Tile() }.color == Color.BLACK } } private fun State.nextDay(): State { return copy( tiles = yRange.flatMap { y -> xRange.map { x -> val pos = Vector(x, y) val tile = tiles.getOrElse(pos) { Tile() } pos to tile.copy( color = when (tile.color) { Color.BLACK -> when (countAdjacentBlackTiles(pos)) { 1, 2 -> tile.color else -> tile.color.flip() } Color.WHITE -> when (countAdjacentBlackTiles(pos)) { 2 -> tile.color.flip() else -> tile.color } } ) } }.toMap(), xRange = (xRange.first - 1)..(xRange.last + 1), yRange = (yRange.first - 1)..(yRange.last + 1) ) } private fun State.nthIteration(n: Int): State { return (0 until n).fold(this) { state, _ -> state.nextDay() } } private fun State.countBlackTiles(): Int = tiles.count { (_, tile) -> tile.color == Color.BLACK } private fun State.withComputedRanges(): State { return copy( xRange = (tiles.keys.minOf { pos -> pos.x } - 1)..(tiles.keys.maxOf { pos -> pos.x } + 1), yRange = (tiles.keys.minOf { pos -> pos.y } - 1)..(tiles.keys.maxOf { pos -> pos.y } + 1) ) } override fun step1(): Int { return tilesToFlipOver .fold(State()) { acc, path -> acc.addPath(path) } .countBlackTiles() } override fun step2(): Int { return tilesToFlipOver .fold(State()) { acc, path -> acc.addPath(path) } .withComputedRanges() .nthIteration(100) .countBlackTiles() } override val expectedStep1: Int = 488 override val expectedStep2: Int = 4118 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
5,043
adventofcode
Apache License 2.0
2019/day6/orbits.kt
sergeknystautas
226,467,020
false
null
package aoc2019.day6; import java.io.File; fun LoadOrbits(filename: String) : List<String> { return File(filename).readLines(); } fun MapOrbits(lines: List<String>): Map<String, String> { var orbits = lines.associateBy ( { it.split(")")[1]}, { it.split(")")[0]} ); return orbits; } fun CountOrbit(orbitsCount: MutableMap<String, Int>, orbitsMap: Map<String, String>, body: String): Int { if (body.equals("COM")) { return 0; } if (orbitsCount.containsKey(body)) { return orbitsCount.getValue(body); } else { var around: String = orbitsMap.getValue(body); var count = CountOrbit(orbitsCount, orbitsMap, around) + 1; orbitsCount.put(body, count); return count; } } fun StepsToCom(orbitsMap: Map<String, String>, body: String): List<String> { var steps = mutableListOf<String>(); if (!body.equals("COM")) { steps.addAll(StepsToCom(orbitsMap, orbitsMap.getValue(body))); } steps.add(body); return steps; } fun main(args: Array<String>) { if (args.size == 1) { var orbitsLines = LoadOrbits(args[0]); var orbitsMap = MapOrbits(orbitsLines); var orbitsCount = mutableMapOf<String, Int>(); println(orbitsMap); for (orbit in orbitsMap) { var count = CountOrbit(orbitsCount, orbitsMap, orbit.key); println("${orbit.key} to ${orbit.value} with count ${count}"); } var sum = orbitsCount.values.sumBy{ it }; println(sum); var you = StepsToCom(orbitsMap, "YOU"); var san = StepsToCom(orbitsMap, "SAN"); var position = 0; // Shouldn't hit an exception because you'll reach YOU or SAN as the end state while (you[position].equals(san[position])) { position++; } var youToSanta = orbitsCount.getValue("YOU") + orbitsCount.getValue("SAN") - position * 2; println(you); println(san); println(position); println(youToSanta); } else { println("Ya done messed up a-a-ron!"); } }
0
Kotlin
0
0
38966bc742f70122681a8885e986ed69dd505243
2,104
adventofkotlin2019
Apache License 2.0
year2020/day03/trees/src/main/kotlin/com/curtislb/adventofcode/year2020/day03/trees/TreeField.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2020.day03.trees import com.curtislb.adventofcode.common.grid.Grid import com.curtislb.adventofcode.common.geometry.Point import com.curtislb.adventofcode.common.geometry.Ray import com.curtislb.adventofcode.common.grid.toGrid import com.curtislb.adventofcode.common.number.Fraction /** * A collection of trees arranged in a 2D grid, consisting of a base pattern repeated infinitely to * the right. * * @param treePattern A string representing the base pattern for this tree field. Each line should * contain a row of characters, with each representing an empty grid space (`.`) or a tree (`#`). */ class TreeField(treePattern: String) { /** * A boolean grid representing the base pattern for this tree field. Contains `true` at each * tree position. */ private val patternGrid: Grid<Boolean> = treePattern.trim().lines().map { line -> line.trim().map { char -> char == '#' } }.toGrid() /** * Returns the number of trees intersected by a line with the given [slope], starting from the * top-left position. * * A [slope] of `null` corresponds to a vertical line (i.e. one with infinite slope). * * @throws IllegalArgumentException If [slope] is not negative or `null`. */ fun countTreesAlongSlope(slope: Fraction?): Int { // Convert slope to a ray originating from the top-left corner require(slope == null || slope.numerator < 0L) { "Slope must be negative or null: $slope" } val ray = Ray(source = Point.ORIGIN, slope = slope, isPositive = slope != null) // Count trees at each point intersected by the ray var count = 0 for (point in ray.points()) { // Stop after reaching the bottom of the pattern if (-point.y >= patternGrid.height) { break } // Check for a tree at the current point if (isTreeAt(point)) { count++ } } return count } /** * Returns `true` if there is a tree at the given [position] in the grid. */ private fun isTreeAt(position: Point): Boolean = patternGrid[position.matrixRow, position.matrixCol % patternGrid.width] }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,268
AdventOfCode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/PartitionString.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 /** * 2405. Optimal Partition of String * @see <a href="https://leetcode.com/problems/optimal-partition-of-string/">Source</a> */ fun interface PartitionString { operator fun invoke(s: String): Int } class PartitionStringBit : PartitionString { override operator fun invoke(s: String): Int { var vis = 0 var res = 1 for (c in s) { vis = if (vis shr c.code - 'a'.code and 1 == 1) { // if bit is on res++ // create new substring 1 shl c.code - 'a'.code // reset vis and mark current bit on } else { vis or (1 shl c.code - 'a'.code) // mark the current bit on } } return res } } class PartitionStringSet : PartitionString { override operator fun invoke(s: String): Int { var ans = 1 val st = HashSet<Char>() for (i in s.indices) { // insert till we find duplicate element. if (!st.contains(s[i])) { st.add(s[i]) } else { // if we found duplicate char then increment count and clear set and start with new set. ans++ st.clear() st.add(s[i]) } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,916
kotlab
Apache License 2.0
src/main/kotlin/day08/Code.kt
fcolasuonno
317,324,330
false
null
package day08 import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/main/kotlin/$dir/$name").readLines() val parsed = parse(input) part1(parsed) part2(parsed) } private val lineStructure = """(...) ([+-]\d+)""".toRegex() data class Regs(var acc: Int = 0, var ip: Int = 0) interface Op { fun execute(regs: Regs): Regs } data class Nop(val value: Int) : Op { override fun execute(regs: Regs) = regs.copy(ip = regs.ip + 1) } data class Jmp(val value: Int) : Op { override fun execute(regs: Regs) = regs.copy(ip = regs.ip + value) } data class Acc(val value: Int) : Op { override fun execute(regs: Regs) = regs.copy(ip = regs.ip + 1, acc = regs.acc + value) } val opcodeMap = mapOf<String, (Int) -> Op>("nop" to { x -> Nop(x) }, "jmp" to { x -> Jmp(x) }, "acc" to { x -> Acc(x) }) fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (opcode, op) = it.toList() opcodeMap.getValue(opcode)(op.toInt()) } }.requireNoNulls() fun part1(input: List<Op>) { val seen = mutableSetOf<Int>() val cpu = generateSequence(Regs()) { regs -> seen.add(regs.ip) val op = input.getOrNull(regs.ip) op?.execute(regs) } val last = cpu.takeWhile { regs -> regs.ip !in seen }.last() val res = last.acc println("Part 1 = $res") } fun part2(input: List<Op>) { val changeOp = input.withIndex().filter { it.value is Jmp || it.value is Nop }.map { it.index } val res = changeOp.map { change -> input.mapIndexed { index, op -> when { index != change -> op op is Jmp -> Nop(op.value) op is Nop -> Jmp(op.value) else -> op } } }.map { execute(it) }.single { it.ip >= input.size }.acc println("Part 2 = $res") } fun execute(input: List<Op>): Regs { val seen = mutableSetOf<Int>() return generateSequence(Regs()) { regs -> seen.add(regs.ip) input.getOrNull(regs.ip)?.execute(regs) }.takeWhile { regs -> regs.ip !in seen }.last() }
0
Kotlin
0
0
e7408e9d513315ea3b48dbcd31209d3dc068462d
2,272
AOC2020
MIT License
src/main/kotlin/com/jaspervanmerle/aoc2020/day/Day18.kt
jmerle
317,518,472
false
null
package com.jaspervanmerle.aoc2020.day class Day18 : Day("654686398176", "8952864356993") { private val parensRegex = "\\(([^()]*)\\)".toRegex() private val addRegex = "(\\d+) \\+ (\\d+)".toRegex() private val multiplyRegex = "(\\d+) \\* (\\d+)".toRegex() override fun solvePartOne(): Any { return calculateOutput(this::calculateSimpleMath) } override fun solvePartTwo(): Any { return calculateOutput(this::calculateAdvancedMath) } private fun calculateOutput(calculator: (String) -> Long): Long { return getInput() .lines() .map { expression -> val simplifiedExpression = replaceAll(expression, parensRegex) { calculator(it.groups[1]!!.value).toString() } calculator(simplifiedExpression) } .sum() } private fun calculateSimpleMath(expression: String): Long { val parts = expression.split(" ") var value = parts[0].toLong() for (i in 2 until parts.size step 2) { when (parts[i - 1]) { "*" -> value *= parts[i].toLong() "+" -> value += parts[i].toLong() } } return value } private fun calculateAdvancedMath(expression: String): Long { val addParsed = replaceAll(expression, addRegex) { (it.groups[1]!!.value.toLong() + it.groups[2]!!.value.toLong()).toString() } val multiplyParsed = replaceAll(addParsed, multiplyRegex) { (it.groups[1]!!.value.toLong() * it.groups[2]!!.value.toLong()).toString() } return multiplyParsed.toLong() } private fun replaceAll(original: String, regex: Regex, replacer: (MatchResult) -> String): String { var current = original while (true) { val oldCurrent = current current = current.replace(regex, replacer) if (current == oldCurrent) { return current } } } }
0
Kotlin
0
0
81765a46df89533842162f3bfc90f25511b4913e
2,055
advent-of-code-2020
MIT License
src/main/kotlin/cloud/dqn/leetcode/PalindromeLinkedListKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/palindrome-linked-list/description/ * Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time and O(1) space? */ class PalindromeLinkedListKt { class ListNode(var `val`: Int = 0) { var next: ListNode? = null } /** Algo0: Assuption that negative values for a node cannot ever be a palindrome ASSUMPTION IS WRONG: if values are == then it is a palindrome Assumption that 1 is not the reverse of 100 as a node value Warning: Not a true O(n) solution as the // once for center element if it exists intIsAPalindrome(x:Int) is O(log(10)x) So runTime: O(n + log(10)(MiddleNode value if it exists)) For all other elements a check must be made for if (x:Int).equals(Reverse(x:Int)) O(n * ReversalTime(n/2)) WARNING INCORRECT BASED UPON FIXED ASSUMPTION Runtime: O(n) Find length of list O(n) find halfway point make stack of list up to halfway point with the list the remainder if (length == odd) { newList = newList.next } while (stack.isNotEmpty()) { if (! pop() isPalendrom(newList.`val`) ){ return false } } return true */ class Solution { private fun powerOfTen(exponent: Int): Long { var power: Long = 1 var index = 0 while (index < exponent) { index++ power *= 10 } return power } private fun digitAt(place: Int, x: Int): Long { return (x / powerOfTen(place)) % 10L } private fun getMostSignificantPlace(x: Int): Int { // place => 3210 // x => abcd if (x < 10) { return 0 } else { var p = 0 while (powerOfTen(p) <= x) { p++ } return --p } } private fun intIsAPalindrome(x: Int): Boolean { if (x < 0) { return false } var mostSignificantPlace = getMostSignificantPlace(x) var leastSignificantPlace = 0 while (mostSignificantPlace > leastSignificantPlace) { if (digitAt(mostSignificantPlace, x) != digitAt(leastSignificantPlace, x)) { return false } mostSignificantPlace-- leastSignificantPlace++ } return true } private fun getListSize(head: ListNode?): Int { var headCopy: ListNode? = head // head is immutable var s = 0 // 0 while (headCopy != null) { headCopy = headCopy.next s++ } return s } /* Assumes: that neg values are never the reverse values > 10 && the tens place is a 0 can never be reversed */ private fun isIntTheReverse(x: Int, y: Int): Boolean { if (x < 0 || y < 0) { return false } else if (x < 10) { return x == y } else if ( (x >= 10 || y >= 10) && ( (x % 10 == 0) || (y % 10 == 0) ) ) { return false } var mostSignificantPlaceX = getMostSignificantPlace(x) // make sure they are the same length if (mostSignificantPlaceX != getMostSignificantPlace(y)) { return false } var leastSignificantPlaceY = 0 while (mostSignificantPlaceX >= 0) { if (digitAt(mostSignificantPlaceX, x) != digitAt(leastSignificantPlaceY, y)) { return false } mostSignificantPlaceX-- leastSignificantPlaceY++ } return true } fun isPalindrome(head: ListNode?): Boolean { var headCopy = head // head is immutable val size = getListSize(headCopy) if (size <= 1) { return true } var halfway = size / 2 var stackTop: ListNode? = null while (halfway > 0) { headCopy?.let { val tempNext = it.next it.next = null if (stackTop == null) { stackTop = it } else { val temp = stackTop stackTop = it it.next = temp } headCopy = tempNext } halfway-- } // check that the middle element is a palindrome if ((1 and size) == 1) { // it's odd headCopy?.let { if (!intIsAPalindrome(it.`val`)) { return false } headCopy = it.next } } // pop stack and iterate headCopy while (stackTop != null && headCopy != null) { stackTop?.`val`?.let { stackValue -> headCopy?.`val`?.let { headValue -> if (stackValue != headValue) { return false } /* // use this algorithm is the values are // required to be reversed and non-negative // and one of the values cannot end in zero if (!isIntTheReverse(stackValue, headValue)) { return false } */ } } stackTop = stackTop?.next headCopy = headCopy?.next } return true } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
6,305
cloud-dqn-leetcode
No Limit Public License
src/sort/HeapSort.kt
daolq3012
143,137,563
false
null
package sort import extention.swap import java.io.IOException /** * * Heap Sort Algorithm. * * @see: http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap07.htm */ class HeapSort : SortAlgorithms<ArrayList<Int>> { override fun sort(arr: ArrayList<Int>) { val count = arr.size // check if there is only 1 element return if (count == 1) { return } //first place arr in max-heap order buildMaxHeap(arr, count) var endIndex = count - 1 while (endIndex > 0) { //swap the root(maximum value) of the heap with the last element of the heap arr.swap(0, endIndex) //put the heap back in max-heap order siftDown(arr, 0, endIndex - 1) //decrement the size of the heap so that the previous //max value will stay in its proper place endIndex-- } return } private fun buildMaxHeap(arr: ArrayList<Int>, count: Int) { //start is assigned the index in a of the last parent node var start = (count - 2) / 2 //binary heap while (start >= 0) { //sift down the node at index start to the proper place //such that all nodes below the start index are in heap //order siftDown(arr, start, count - 1) start-- } //after sifting down the root all nodes/elements are in heap order } private fun siftDown(arr: ArrayList<Int>, start: Int, end: Int) { //end represents the limit of how far down the heap to sift var root = start while (root * 2 + 1 <= end) { //While the root has at least one child var child = root * 2 + 1 //root*2+1 points to the left child //if the child has a sibling and the child's value is less than its sibling's... if (child + 1 <= end && arr[child] < arr[child + 1]) { child = root * 2 + 2 //... then point to the right child instead } if (arr[root] < arr[child]) { //out of max-heap order arr.swap(root, child) root = child //repeat to continue sifting down the child now } else { break } } } object Run { @Throws(IOException::class) @JvmStatic fun main(args: Array<String>) { val input = arrayListOf(6, 5, 3, 1, 8, 7, 2, 4) val sortAlgorithms: SortAlgorithms<ArrayList<Int>> = HeapSort() sortAlgorithms.sort(input) System.out.print("---------Result---------\n$input ") } } }
1
Kotlin
11
74
40e00d0d3f1c7cbb93ad28f4197e7ffa5ea36ef9
2,706
Kotlin-Algorithms
Apache License 2.0
src/main/kotlin/kr/co/programmers/P60059.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://school.programmers.co.kr/learn/courses/30/lessons/60059 class P60059 { fun solution(k: Array<IntArray>, lock: Array<IntArray>): Boolean { var key = k repeat(4) { // 키를 4번 회전면서 체크한다. if (check(key, lock)) { return true } // 키를 오른쪽으로 90도 회전 key = turn(key) } return false } private fun check(key: Array<IntArray>, lock: Array<IntArray>): Boolean { val n = lock.size val m = key.size val len = (n + m - 1) val loop = len * len var i = 0 while (i < loop) { val x = (i % len) + n - m + 1 val y = (i / len) + n - m + 1 if (verify(key, lock, y, x)) { return true } i++ } return false } /** * 자물쇠([lock])와 열쇠([key])에서 겹쳐지는 부분 계산 */ private fun verify(key: Array<IntArray>, lock: Array<IntArray>, y: Int, x: Int): Boolean { val m = key.size val n = lock.size val copiedLock = lock.map { it.copyOf() } for (i in y until y + m) { for (j in x until x + m) { // 자물쇠에 해당하는 부분만 계산 if (i in n until n + n && j in n until n + n) { copiedLock[i - n][j - n] += key[i - y][j - x] } } } // 자물쇠의 모든 칸이 1이면 OK return copiedLock.all { it.all { v -> v == 1 } } } /** 키를 오른쪽으로 90도 회전 */ private fun turn(key: Array<IntArray>): Array<IntArray> { val n = key.size val turned = Array(n) { IntArray(n) } for (r in 0 until n) { for (c in 0 until n) { turned[c][n - r - 1] = key[r][c] } } return turned } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,971
algorithm
MIT License
src/adventofcode/Day15.kt
Timo-Noordzee
573,147,284
false
{"Kotlin": 80936}
package adventofcode import org.openjdk.jmh.annotations.* import java.util.concurrent.TimeUnit import kotlin.math.abs import kotlin.math.absoluteValue private operator fun List<MatchResult>.component1() = this[0].groupValues[1].toInt() private operator fun List<MatchResult>.component2() = this[1].groupValues[2].toInt() private operator fun List<MatchResult>.component3() = this[2].groupValues[1].toInt() private operator fun List<MatchResult>.component4() = this[3].groupValues[2].toInt() data class Sensor( val x: Int, val y: Int, val beacon: Point ) { private val range = (x - beacon.x).absoluteValue + (y - beacon.y).absoluteValue val yRange = (this.y - range)..(this.y + range) fun xRangeAt(y: Int): IntRange { val yDelta = abs(this.y - y) return if (yDelta > range) 0..0 else { val halfWidth = range - yDelta (this.x - halfWidth)..(this.x + halfWidth) } } } @State(Scope.Benchmark) @Fork(1) @Warmup(iterations = 0) @Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS) class Day15 { var targetY: Int = 2_000_000 var max: Int = 40_000_000 var input: List<String> = emptyList() @Setup fun setup() { input = readInput("Day15") targetY = 2_000_000 max = 4_000_000 } fun parseSensors(): List<Sensor> { val regex = Regex("""x=(-?\d+)|y=(-?\d+)""") return input.map { line -> val (sensorX, sensorY, beaconX, beaconY) = regex.findAll(line).toList() Sensor(sensorX, sensorY, Point(beaconX, beaconY)) } } @Benchmark fun part1(): Int { val sensors = parseSensors() val numOfBeaconsAtTargetY = sensors.map { it.beacon }.toSet().count { it.y == targetY } val impossiblePositions = sensors .filter { targetY in it.yRange } .map { it.xRangeAt(targetY) } .merge() .sumOf { it.size } return impossiblePositions - numOfBeaconsAtTargetY } @Benchmark fun part2(): Long { val sensors = parseSensors() for (y in 0..max) { val mergedRanges = sensors.filter { y in it.yRange }.map { it.xRangeAt(y) }.merge() if (mergedRanges.size > 1) { return (mergedRanges.first().last + 1) * 4_000_000L + y } } error("check input") } } fun main() { val day15 = Day15() // test if implementation meets criteria from the description, like: day15.input = readInput("Day15_test") day15.targetY = 10 day15.max = 20 check(day15.part1() == 26) check(day15.part2() == 56000011L) day15.input = readInput("Day15") day15.targetY = 2_000_000 day15.max = 4_000_000 println(day15.part1()) println(day15.part2()) }
0
Kotlin
0
2
10c3ab966f9520a2c453a2160b143e50c4c4581f
2,817
advent-of-code-2022-kotlin
Apache License 2.0
src/Day25.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
import java.util.* import kotlin.math.abs fun main() { val cost = mapOf( '2' to 2, '1' to 1, '0' to 0, '-' to -1, '=' to -2 ) fun String.snafuToLong(): Long { var n = 0L var k = 1L for (c in reversed()) { n += k * cost[c]!! k *= 5L } return n } fun max(len: Int): Long { if (len == 0) return 0 var k = 1L var sum = 2L repeat(len - 1) { k *= 5 sum += k * 2 } return sum } fun part1(input: List<String>): Any { val sum = input.sumOf { it.snafuToLong() } var len = 1 var k = 1L while (max(len) < sum) { len++ k *= 5 } var rem = sum var res = "" repeat(len) { done -> var fixed = false for (d in 2 downTo -2) { val willRemain = rem - d * k val ok = abs(willRemain) <= max(len - done - 1) if (!ok) continue rem -= d * k res += cost.entries.first { it.value == d }.key fixed = true break } require(fixed) k /= 5 } return res } fun part2(input: List<String>): Any { return Unit } @Suppress("DuplicatedCode") run { val day = String.format("%02d", 25) val testInput = readInput("Day${day}_test") val input = readInput("Day$day") println("Part 1 test - " + part1(testInput)) println("Part 1 real - " + part1(input)) println("---") println("Part 2 test - " + part2(testInput)) println("Part 2 real - " + part2(input)) } }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
1,798
advent-of-code-2022
Apache License 2.0
src/aoc22/Day12.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc2022.day12 import lib.Grid import lib.Point import lib.Solution enum class PlotType { START, END, MIDDLE } data class Plot(val plotType: PlotType, val height: Int) { infix fun canStepTo(other: Plot): Boolean = other.height <= height + 1 companion object { fun parse(ch: Char): Plot = when (ch) { 'S' -> Plot(PlotType.START, 0) 'E' -> Plot(PlotType.END, 25) else -> Plot(PlotType.MIDDLE, ch - 'a') } } } typealias Input = Grid<Plot> typealias Output = Int private val solution = object : Solution<Input, Output>(2022, "Day12") { override fun parse(input: String): Input = Grid.parse(input).map(Plot.Companion::parse) override fun format(output: Output): String = "$output" override fun solve(part: Part, input: Input): Output = when (part) { Part.PART1 -> input.shortedDistance { it.plotType == PlotType.START } Part.PART2 -> input.shortedDistance { it.height == 0 } } fun Grid<Plot>.shortedDistance(start: (Plot) -> Boolean): Int { val distance = mutableMapOf<Point, Int>() val queue = ArrayDeque<Point>() fun Point.isNotVisited(): Boolean = this !in distance fun canStepFrom(points: Pair<Point, Point>): Boolean = this[points.first] canStepTo this[points.second] fun stepFrom(points: Pair<Point, Point>) { distance[points.second] = distance[points.first]!! + 1 queue.add(points.second) } indicesOf(start).forEach { distance[it] = 0 queue.add(it) } while (queue.isNotEmpty()) { val currPoint = queue.removeFirst() adjacents(currPoint) .filter { nextPoint -> nextPoint.isNotVisited() } .filter { nextPoint -> canStepFrom(currPoint to nextPoint) } .forEach { nextPoint -> stepFrom(currPoint to nextPoint) if (this[nextPoint].plotType == PlotType.END) { return distance[nextPoint]!! } } } error("Did not reach END.") } } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
2,043
aoc-kotlin
Apache License 2.0
year2022/src/cz/veleto/aoc/year2022/Day20.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay class Day20(config: Config) : AocDay(config) { override fun part1(): String { val list = parseList().toList() val mixedList = mix(list, rounds = 1) return getGroveCoors(mixedList).toString() } override fun part2(): String { val list = parseList() val decryptedList = list.map { it * 811_589_153 }.toList() val mixedList = mix(decryptedList, rounds = 10) return getGroveCoors(mixedList).toString() } private fun parseList(): Sequence<Long> = input.map { it.toLong() } private fun mix(originalList: List<Long>, rounds: Int): List<Long> { val nodes: MutableList<Node> = Node.listFromLongs(originalList).toMutableList() val firstNode = nodes.first() val size = nodes.size val cycleSize = size - 1 for (round in 1..rounds) { var node = firstNode while (node.mixedCount < round) { val index = nodes.indexOf(node) val newPosMaybeNegative = (index + node.value).rem(cycleSize).toInt() val newPos = (newPosMaybeNegative + cycleSize).rem(cycleSize) when { newPos < index -> { nodes.removeAt(index) nodes.add(newPos, node) } newPos > index -> { nodes.add(newPos + 1, node) nodes.removeAt(index) } else -> Unit } node.mixedCount++ node = node.nextNode } } return nodes.map { it.value } } private fun getGroveCoors(list: List<Long>): Long { val zeroIndex = list.indexOf(0) return listOf(1000, 2000, 3000).sumOf { list[(zeroIndex + it).rem(list.size)] } } private class Node private constructor( val value: Long, var mixedCount: Int, private var _nextNode: Node? = null, ) { companion object { fun listFromLongs(list: List<Long>): List<Node> { val nodes = list.map { Node( value = it, mixedCount = 0, ) } nodes.forEachIndexed { index, node -> node._nextNode = nodes[(index + 1).rem(nodes.size)] } return nodes } } val nextNode: Node get() = _nextNode!! override fun toString(): String = "Node(value=$value, mixedCount=$mixedCount, nextNodeValue=${nextNode.value})" } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
2,738
advent-of-pavel
Apache License 2.0
src/Day03.kt
er453r
572,440,270
false
{"Kotlin": 69456}
fun main() { val lowerScoreOffset = 'a'.code - 1 val upperScoreOffset = 'A'.code - 1 - 26 fun Char.priority(): Int = this.code - (if (this.code > lowerScoreOffset) lowerScoreOffset else upperScoreOffset) fun part1(input: List<String>): Int = input.sumOf { items -> items.chunked(items.length / 2) .map { it.toSet() } .reduce { a, b -> a.intersect(b) } .first() .priority() } fun part2(input: List<String>): Int = input.chunked(3).sumOf { group -> group.map { it.toSet() } .reduce { a, b -> a.intersect(b) } .first() .priority() } test( day = 3, testTarget1 = 157, testTarget2 = 70, part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
800
aoc2022
Apache License 2.0
logicsolver/src/main/kotlin/nl/hiddewieringa/logicsolver/Solver.kt
hiddewie
147,922,971
false
null
package nl.hiddewieringa.logicsolver interface LogicPuzzleSolver<IN, OUT> { fun solve(input: IN): OneOf<OUT, List<LogicSolveError>> } /** * Solving data structure for sudokus. * * Contains its location, its value, and any values that are not allowed. */ class SudokuSolveData(val coordinate: Coordinate, val value: Int?, val notAllowed: List<Int>) { fun hasValue(): Boolean { return value != null } fun isEmpty(): Boolean { return !hasValue() } fun isNotAllowed(value: Int): Boolean { return !isAllowed(value) } fun isAllowed(value: Int): Boolean { return !notAllowed.contains(value) } override fun toString(): String { return "SSD($coordinate, $value, $notAllowed)" } } /** * Solves sudoku input of different forms */ class SudokuSolver : LogicPuzzleSolver<SudokuInput, SudokuOutput> { private val groupStrategy = GroupStrategy() private val overlappingGroupsStrategy = OverlappingGroupsStrategy() /** * Migrates input groups to Group objects */ private fun toGroups(groups: List<Set<Coordinate>>): Set<SudokuGroup> { return groups.map { coordinates: Set<Coordinate> -> { v: Map<Coordinate, SudokuSolveData> -> coordinates.map { v[it] }.filterNotNull().toSet() } }.toSet() } /** * Builds solving data from input */ private fun buildSolvingData(coordinates: List<Coordinate>, input: Map<Coordinate, Int>): MutableMap<Coordinate, SudokuSolveData> { return coordinates.map { coordinate -> coordinate to SudokuSolveData(coordinate, input[coordinate], listOf()) }.toMap(mutableMapOf()) } /** * Gathers conclusions from each group */ private fun gatherConclusions(groups: Set<SudokuGroup>, data: MutableMap<Coordinate, SudokuSolveData>, puzzleValues: Set<Int>): Set<Conclusion> { return groups.flatMap { strategy -> groupStrategy(Pair(strategy(data), puzzleValues)) }.toSet() + overlappingGroupsStrategy(Triple(groups, data, puzzleValues)) } /** * Processes the conclusions from each group */ private fun processConclusion(data: MutableMap<Coordinate, SudokuSolveData>, conclusion: Conclusion) { conclusion.match({ value -> if (data[value.coordinate]!!.value != null) { throw Exception("Value at ${data[value.coordinate]!!.coordinate} is ${data[value.coordinate]!!.value} but replacing with ${value.value}") } data[value.coordinate] = SudokuSolveData(value.coordinate, value.value, data[value.coordinate]!!.notAllowed) }, { notAllowed -> data[notAllowed.coordinate] = SudokuSolveData(notAllowed.coordinate, data[notAllowed.coordinate]!!.value, data[notAllowed.coordinate]!!.notAllowed + listOf(notAllowed.value)) }) } /** * Solves the input by finding conclusions until no more conclusions can be found. * Then, either the puzzle has been solved or an error is returned. */ override fun solve(input: SudokuInput): OneOf<SudokuOutput, List<LogicSolveError>> { val groups = toGroups(input.groups) val data = buildSolvingData(input.coordinates, input.values) if (isSolved(data)) { return toOutput(input.coordinates, data) } do { val conclusions = gatherConclusions(groups, data, input.puzzleValues) conclusions.forEach { processConclusion(data, it) } if (!isValid(groups, data, input.puzzleValues)) { throw Exception("The puzzle is not valid: current state: ${toOutput(input.coordinates, data)}") } } while (!conclusions.isEmpty()) return if (isSolved(data)) { toOutput(input.coordinates, data) } else { OneOf.right(listOf(LogicSolveError("No more conclusions, cannot solve"))) } } /** * Checks if the puzzle has been solved */ private fun isSolved(data: MutableMap<Coordinate, SudokuSolveData>): Boolean { return !data.values.any { it.value == null } } /** * Checks if the puzzle is valid */ private fun isValid(groups: Set<SudokuGroup>, data: MutableMap<Coordinate, SudokuSolveData>, puzzleValues: Set<Int>): Boolean { return groups.all { group -> val groupData = group(data) puzzleValues.all { i -> groupData.asSequence().filter { it.hasValue() }.count { it.value == i } <= 1 } } } /** * Generates the output given solving data */ private fun toOutput(coordinates: List<Coordinate>, data: MutableMap<Coordinate, SudokuSolveData>): OneOf<SudokuOutput, List<LogicSolveError>> { val valueMap = data .filterValues { it.value != null } .mapValues { it.value.value!! } return OneOf.left(SudokuOutput(coordinates, valueMap)) } }
0
Kotlin
0
0
bcf12c102f4ab77c5aa380dbf7c98a1cc3e585c0
5,247
LogicSolver
MIT License
src/Day02.kt
hiteshchalise
572,795,242
false
{"Kotlin": 10694}
fun main() { fun part1(input: List<String>): Int { val score = input.fold(0) { acc, round -> val (opponentMove, yourMove) = round.split(" ") val score: Int = when(opponentMove) { "A" -> { when (yourMove) { "X" -> 1 + 3 "Y" -> 2 + 6 else -> 3 + 0 } } "B" -> { when (yourMove) { "X" -> 1 + 0 "Y" -> 2 + 3 else -> 3 + 6 } } "C" -> { when (yourMove) { "X" -> 1 + 6 "Y" -> 2 + 0 else -> 3 + 3 } } else -> { throw(Error("Illegal State Exception")) } } (acc + score) } return score } fun part2(input: List<String>): Int { val score = input.fold(0) { acc, round -> val (opponentMove, target) = round.split(" ") val score: Int = when(opponentMove) { "A" -> { when (target) { "X" -> 3 + 0 "Y" -> 1 + 3 else -> 2 + 6 } } "B" -> { when (target) { "X" -> 1 + 0 "Y" -> 2 + 3 else -> 3 + 6 } } "C" -> { when (target) { "X" -> 2 + 0 "Y" -> 3 + 3 else -> 1 + 6 } } else -> { throw(Error("Illegal State Exception")) } } (acc + score) } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e4d66d8d1f686570355b63fce29c0ecae7a3e915
2,338
aoc-2022-kotlin
Apache License 2.0
codeforces/vk2022/round1/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.vk2022.round1 import kotlin.math.roundToLong import kotlin.math.sqrt private fun solve() { readln() val a = readInts() var ans = 1 val toTest = mutableSetOf<Long>() for (i in a.indices) for (j in 0 until i) { val ba = a[i] - a[j] for (d in 1..ba) { if (d * d > ba) break if (ba % d != 0) continue val e = ba / d if (((d xor e) and 1) != 0) continue val q = (d + e) / 2 val x = q.toLong() * q - a[i] if (x >= 0) toTest.add(x) } } for (x in toTest) { val current = a.count { b -> val y = b + x val z = sqrt(y.toDouble()).roundToLong() y == z * z } ans = ans.coerceAtLeast(current) } println(ans) } fun main() = repeat(readInt()) { solve() } private fun readInt() = readln().toInt() private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
860
competitions
The Unlicense
jvm/src/main/kotlin/io/prfxn/aoc2021/day19.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Beacon Scanner (https://adventofcode.com/2021/day/19) package io.prfxn.aoc2021 import kotlin.math.abs private typealias CT = Triple<Int, Int, Int> fun main() { val orientationMappers = // region sequenceOf.. sequenceOf( { t: CT -> t.let { (x, y, z) -> Triple(x, y, z) } }, // (default) { t: CT -> t.let { (x, y, z) -> Triple(-x, y, -z) } }, // z -> -z (via x) { t: CT -> t.let { (x, y, z) -> Triple(z, y, -x) } }, // z -> x { t: CT -> t.let { (x, y, z) -> Triple(-z, y, x) } }, // z -> -x { t: CT -> t.let { (x, y, z) -> Triple(x, z, -y) } }, // z -> y { t: CT -> t.let { (x, y, z) -> Triple(x, -z, y) } } // z -> -y ) .flatMap { fn -> sequenceOf( { t: CT -> fn(t).let { (x, y, z) -> Triple(x, y, z) } }, // 0 (default) { t: CT -> fn(t).let { (x, y, z) -> Triple(y, -x, z) } }, // 90 { t: CT -> fn(t).let { (x, y, z) -> Triple(-x, -y, z) } }, // 180 { t: CT -> fn(t).let { (x, y, z) -> Triple(-y, x, z) } } // 270 ) } // endregion fun findOriginAndOrientationMapper(wrtS: Set<CT>, ofS: Set<CT>) = orientationMappers .flatMap { orient -> wrtS.flatMap { (x1, y1, z1) -> ofS.map { val (x2, y2, z2) = orient(it) Triple(x1 - x2, y1 - y2, z1 - z2) to orient } } } .find { (s2o, orient) -> val (x2o, y2o, z2o) = s2o ofS.map(orient) .filter { (x2, y2, z2) -> Triple(x2 + x2o, y2 + y2o, z2 + z2o) in wrtS } .take(12) .count() == 12 } val scanners: MutableList<MutableSet<CT>> = textResourceReader("input/19.txt").useLines { lines -> mutableListOf<MutableSet<CT>>().apply { lines.filter(String::isNotBlank).forEach { line -> if (line.startsWith("--- scanner")) add(mutableSetOf()) else last().add(line.split(",").map(String::toInt).let { (a, b, c) -> Triple(a, b, c) }) } } } val scannerOrigins = mutableMapOf<Int, MutableList<Pair<Int, CT>>>() val unmergedScannerIndices = scanners.indices.toMutableSet() while (unmergedScannerIndices.size > 1) { for (s2i in (scanners.size - 1 downTo 1).filter(unmergedScannerIndices::contains)) { ((s2i - 1 downTo 0).filter(unmergedScannerIndices::contains)) .find { s1i -> val s1 = scanners[s1i] val s2 = scanners[s2i] findOriginAndOrientationMapper(s1, s2) ?.let { (s2o, orient) -> val (x2o, y2o, z2o) = s2o scannerOrigins.getOrPut(s1i) { mutableListOf(s1i to Triple(0, 0, 0)) } .apply { add(s2i to s2o) scannerOrigins[s2i] ?.map { (s3i, s3o) -> val (x3o, y3o, z3o) = orient(s3o) s3i to Triple(x3o + x2o, y3o + y2o, z3o + z2o) } ?.let { addAll(it) scannerOrigins.remove(s2i) } } s2.forEach { val (x2, y2, z2) = orient(it) s1.add(Triple(x2 + x2o, y2 + y2o, z2 + z2o)) } unmergedScannerIndices.remove(s2i) println("scanner $s2i -> scanner $s1i") true } ?: false } } } println(scanners.first().size) // answer 1 fun manhattanDistance(ct1: CT, ct2: CT) = ct1.let { (x1, y1, z1) -> ct2.let { (x2, y2, z2) -> abs(x1 - x2) + abs(y1 - y2) + abs(z1 - z2) } } val scannerOrigins0 = scannerOrigins[0]!!.map { it.second } (0 until scannerOrigins0.size - 1) .flatMap { i1 -> (i1 + 1 until scannerOrigins0.size) .map { i2 -> manhattanDistance(scannerOrigins0[i1], scannerOrigins0[i2]) } } .maxOf { it } .let(::println) // answer 2 }
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
4,812
aoc2021
MIT License
src/main/kotlin/days/Day02.kt
TheMrMilchmann
571,779,671
false
{"Kotlin": 56525}
/* * Copyright (c) 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* fun main() { val data = readInput().map { val (a, b) = it.split(" ") a to b } fun String.toMove() = when (this) { "A", "X" -> Move.Rock "B", "Y" -> Move.Paper "C", "Z" -> Move.Scissor else -> error("Unknown move: $this") } fun part1(): Int { val rounds = data.map { (a, b) -> a.toMove() to b.toMove() } return rounds.sumOf { (opponent, reaction) -> val result = Result.values().find { reaction == opponent.getReactionFor(it) }!! reaction.points + result.points } } fun part2(): Int { val rounds = data.map { (a, b) -> val result = when (b) { "X" -> Result.Defeat "Y" -> Result.Draw "Z" -> Result.Victory else -> error("Unknown result: $b") } a.toMove() to result } return rounds.sumOf { (opponent, result) -> result.points + opponent.getReactionFor(result).points } } println("Part 1: ${part1()} ") println("Part 2: ${part2()} ") } private enum class Move(val points: Int) { Rock(1), Paper(2), Scissor(3); fun getReactionFor(result: Result): Move = result.selectReaction(this) companion object { val cachedValues = values() } } private enum class Result(val points: Int, val selectReaction: (Move) -> Move) { Defeat(0, { Move.cachedValues[(it.ordinal + 2) % 3] }), Draw(3, { it }), Victory(6, { Move.cachedValues[(it.ordinal + 1) % 3] }) }
0
Kotlin
0
1
2e01ab62e44d965a626198127699720563ed934b
2,729
AdventOfCode2022
MIT License
src/Day11.kt
rromanowski-figure
573,003,468
false
{"Kotlin": 35951}
object Day11 : Runner<Long, Long>(11, 10605L, 2713310158L) { private fun String.toItems(): List<Item> = split(",").map { Item(it.trim().toLong()) } object Regex { val monkey = """Monkey (\d+):""".toRegex() val itemList = """\s+Starting items: (.*)""".toRegex() val operation = """\s+Operation: new = (.*)""".toRegex() val divisibleTest = """\s+Test: divisible by (\d+)""".toRegex() val ifTrue = """\s+If true: throw to monkey (\d+)""".toRegex() val ifFalse = """\s+If false: throw to monkey (\d+)""".toRegex() } private fun monkeyMap(input: List<String>, factor: Long = 3): MutableMap<Int, Monkey> { val monkeyMap = mutableMapOf<Int, Monkey>() var currentMonkey = monkey { worryDecreaseFactor { factor } } input.forEach { if (it.trim().isBlank()) { val monkey = currentMonkey.finalize() monkeyMap[monkey.id] = monkey currentMonkey = monkey { worryDecreaseFactor { factor } } } Regex.monkey.find(it)?.destructured?.also { currentMonkey.apply { id { it.component1().toInt() } } } Regex.itemList.find(it)?.destructured?.also { currentMonkey.apply { items { it.component1().toItems() } } } Regex.operation.find(it)?.destructured?.also { currentMonkey.apply { operation { Operation.of(it.component1()).transform } } } Regex.divisibleTest.find(it)?.destructured?.also { currentMonkey.apply { divisibleBy { it.component1().toLong() } } } Regex.ifTrue.find(it)?.destructured?.also { currentMonkey.apply { onTrueTarget { it.component1().toInt() } } } Regex.ifFalse.find(it)?.destructured?.also { currentMonkey.apply { onFalseTarget { it.component1().toInt() } } } } val monkey = currentMonkey.finalize() monkeyMap[monkey.id] = monkey println(monkeyMap.values.joinToString("\n") { "${it.id} ${it.items}" }) return monkeyMap } private fun MutableMap<Int, Monkey>.inspect(rounds: Int = 20) { val supermodulo = this.values.fold(1L) { a, m -> a * m.divisibleBy } repeat(rounds) { r -> this.entries.sortedBy { it.key }.forEach { (_, monkey) -> while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() monkey.throwItem(item, this[monkey.inspect(item, supermodulo)]!!) } } val round = r + 1 if (rounds > 20 && (round == 1 || round == 20 || round % 1000 == 0)) { println("\n== After round $round ==") this.values.forEach { monkey -> println("Monkey ${monkey.id} inspected items ${monkey.numberOfInspections} times.") } } } this.values.forEach { println("Monkey ${it.id} inspected items ${it.numberOfInspections} times.") } } private fun Map<Int, Monkey>.monkeyBusiness(): Long { return this.values .sortedByDescending { it.numberOfInspections } .take(2) .fold(1) { a, m -> a * m.numberOfInspections } } override fun part1(input: List<String>): Long { val monkeyMap = monkeyMap(input) monkeyMap.inspect() return monkeyMap.monkeyBusiness() } override fun part2(input: List<String>): Long { val monkeyMap = monkeyMap(input, 1) monkeyMap.inspect(10000) return monkeyMap.monkeyBusiness() } data class Item(var worryLevel: Long) { override fun toString(): String { return worryLevel.toString() } } data class Monkey( val id: Int, val items: MutableList<Item>, val operation: Long.() -> Long, val worryDecreaseFactor: Long, val divisibleBy: Long, val onTrueTarget: Int, val onFalseTarget: Int, var numberOfInspections: Long = 0L, ) { fun inspect(item: Item, modulo: Long): Int { numberOfInspections++ item.worryLevel = item.worryLevel.operation() % modulo item.worryLevel /= worryDecreaseFactor return if (item.worryLevel % divisibleBy == 0L) onTrueTarget else onFalseTarget } fun throwItem(item: Item, monkey: Monkey) { monkey.items.add(item) } } class MonkeyBuilder( private var id: Int = -1, private var items: MutableList<Item> = mutableListOf(), private var operation: Long.() -> Long = { this }, private var worryDecreaseFactor: Long = 3, private var divisibleBy: Long = 0, private var onTrueTarget: Int = -1, private var onFalseTarget: Int = -1, ) { fun id(lambda: () -> Int) { this.id = lambda() } fun worryDecreaseFactor(lambda: () -> Long) { this.worryDecreaseFactor = lambda() } fun items(lambda: () -> List<Item>) { this.items = lambda().toMutableList() } fun operation(lambda: () -> Long.() -> Long) { this.operation = lambda() } fun divisibleBy(lambda: () -> Long) { this.divisibleBy = lambda() } fun onTrueTarget(lambda: () -> Int) { this.onTrueTarget = lambda() } fun onFalseTarget(lambda: () -> Int) { this.onFalseTarget = lambda() } fun finalize() = Monkey( id = id, items = items, operation = operation, worryDecreaseFactor = worryDecreaseFactor, divisibleBy = divisibleBy, onTrueTarget = onTrueTarget, onFalseTarget = onFalseTarget ) } private fun monkey(lambda: MonkeyBuilder.() -> Unit): MonkeyBuilder { return MonkeyBuilder().apply(lambda) } data class Operation(val transform: Long.() -> Long) { companion object { fun of(s: String): Operation { val regex = """(\w+)\s+([+*])\s+(\w+)""".toRegex() val (op1, op, op2) = regex.find(s.trim())!!.destructured return when (op) { "+" -> when { op1 != "old" -> Operation { this + op1.toInt() } op2 != "old" -> Operation { this + op2.toInt() } else -> Operation { this + this } } "*" -> when { op1 != "old" -> Operation { this * op1.toInt() } op2 != "old" -> Operation { this * op2.toInt() } else -> Operation { this * this } } else -> error("Unsupported operator: $op") } } } } }
0
Kotlin
0
0
6ca5f70872f1185429c04dcb8bc3f3651e3c2a84
7,002
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/g0701_0800/s0786_k_th_smallest_prime_fraction/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0701_0800.s0786_k_th_smallest_prime_fraction // #Medium #Array #Binary_Search #Heap_Priority_Queue // #2023_03_13_Time_165_ms_(100.00%)_Space_35.8_MB_(100.00%) class Solution { fun kthSmallestPrimeFraction(arr: IntArray, k: Int): IntArray { val n = arr.size var low = 0.0 var high = 1.0 while (low < high) { val mid = (low + high) / 2 val res = getFractionsLessThanMid(arr, n, mid) if (res[0] == k) { return intArrayOf(arr[res[1]], arr[res[2]]) } else if (res[0] > k) { high = mid } else { low = mid } } return intArrayOf() } private fun getFractionsLessThanMid(arr: IntArray, n: Int, mid: Double): IntArray { var maxLessThanMid = 0.0 // stores indices of max fraction less than mid; var x = 0 var y = 0 // for storing fractions less than mid var total = 0 var j = 1 for (i in 0 until n - 1) { // while fraction is greater than mid increment j while (j < n && arr[i] > arr[j] * mid) { j++ } if (j == n) { break } // j fractions greater than mid, n-j fractions smaller than mid, add fractions smaller // than mid to total total += n - j val fraction = arr[i].toDouble() / arr[j] if (fraction > maxLessThanMid) { maxLessThanMid = fraction x = i y = j } } return intArrayOf(total, x, y) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,676
LeetCode-in-Kotlin
MIT License
src/main/kotlin/lesson3/FrogJmp.kt
iafsilva
633,017,063
false
null
package lesson3 /** * A small frog wants to get to the other side of the road. * * The frog is currently located at position X and wants to get to a position greater than or equal to Y. * * The small frog always jumps a fixed distance, D. * * Count the minimal number of jumps that the small frog must perform to reach its target. * * Write a function: * * fun solution(X: Int, Y: Int, D: Int): Int * * that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y. * * For example, given: * ``` * X = 10 * Y = 85 * D = 30 * ``` * the function should return 3, because the frog will be positioned as follows: * ``` * after the first jump, at position 10 + 30 = 40 * after the second jump, at position 10 + 30 + 30 = 70 * after the third jump, at position 10 + 30 + 30 + 30 = 100 * ``` * Write an efficient algorithm for the following assumptions: * * - X, Y and D are integers within the range [1..1,000,000,000]; * - X ≤ Y. */ class FrogJmp { fun solution(x: Int, y: Int, d: Int): Int { val distance = y - x val jumps = distance / d // If the jumps are 1.1, that means 2 jumps. return if (distance % d == 0) jumps else jumps + 1 } }
0
Kotlin
0
0
5d86aefe70e9401d160c3d87c09a9bf98f6d7ab9
1,291
codility-lessons
Apache License 2.0
src/Day06.kt
BionicCa
574,904,899
false
{"Kotlin": 20039}
fun main() { fun part1(input: List<String>): Int { val dataStream = input.first().toCharArray() val checkCharacters = 4 for (i in dataStream.indices) { if (i + checkCharacters - 1 >= dataStream.size) break val slice = dataStream.slice(i until i + checkCharacters) val noDuplicates = slice.distinct().size == slice.size if (noDuplicates) { return i + checkCharacters } } return -1 } fun part2(input: List<String>): Int { val dataStream = input.first().toCharArray() val checkCharacters = 14 for (i in dataStream.indices) { if (i + checkCharacters - 1 >= dataStream.size) break val slice = dataStream.slice(i until i + checkCharacters) val noDuplicates = slice.distinct().size == slice.size if (noDuplicates) { return i + checkCharacters } } return -1 } // val testInput = readInput("Day06_test") // println(part1(testInput)) // println(part2(testInput)) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ed8bda8067386b6cd86ad9704bda5eac81bf0163
1,202
AdventOfCode2022
Apache License 2.0
src/main/kotlin/aoc04/solution.kt
dnene
317,653,484
false
null
package aoc04 import aoc04.Field.Companion.fieldMap import java.io.File enum class Field( val str: String, val validator: ((String) -> Boolean)? = null ) { BirthYear("byr", { it.length == 4 && it.all { it.isDigit() } && it.toInt() in (1920..2002) }), IssueYear("iyr", { it.length == 4 && it.all { it.isDigit() } && it.toInt() in (2010..2020) }), ExpirationYear("eyr", { it.length == 4 && it.all { it.isDigit() } && it.toInt() in (2020..2030) }), Height("hgt", { when (it.takeLast(2).toString()) { "cm" -> { it.substring(0, it.length - 2).run { toInt() in (150..193) } } "in" -> { it.substring(0, it.length - 2).run { toInt() in (59..76) } } else -> false } }), HairColour("hcl", { it.length == 7 && it[0] == '#' && it.substring(1).all { it.isDigit() || it in ('a'..'f') } }), EyeColour("ecl", { it in allowedEyeColours }), PassportId("pid", { it.length == 9 && it.all { it.isDigit() } }), CountryId("cid"); fun isValid(value: String): Boolean = validator?.let { it(value) } ?: true companion object { val mandatoryKeys = values().filter { it.validator != null }.map { it.str }.toSet() val allowedEyeColours = setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") val fieldMap = values().map { it.str to it }.toMap() } } val breakOnEmptyLine: (Pair<List<String>?, List<List<String>>>, String) -> Pair<List<String>?, List<List<String>>> = { acc, elem -> if (elem.isEmpty()) { (null as List<String>? to (acc.first?.let { acc.second + listOf(it) } ?: acc.second)) } else { (acc.first ?: mutableListOf<String>()) + elem to acc.second } } fun main(args: Array<String>) { File("data/inputs/aoc04.txt") .readLines() .flatMap { it.trim().split(" ") } .fold(null as List<String>? to listOf(), breakOnEmptyLine) .let { breakOnEmptyLine(it, "").second } .map { it.map { it.split(":").let { it[0] to it[1] } } } .run { filter { (Field.mandatoryKeys subtract it.map { it.first }.toSet()).isEmpty() } .size .let { println(it) } filter { keyValueList -> (Field.mandatoryKeys subtract keyValueList.map { it.first }.toSet()).isEmpty() && keyValueList.all { (key, value) -> fieldMap[key]?.isValid(value) ?: false } } .size .let { println(it) } } }
0
Kotlin
0
0
db0a2f8b484575fc3f02dc9617a433b1d3e900f1
2,634
aoc2020
MIT License
src/main/kotlin/com/kishor/kotlin/algo/dp/GlobMatching.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.dp fun isMatch(fileName: String, pattern: String): Boolean { val sLen = fileName.length val pLen = pattern.length // base cases if (pattern == fileName || pattern == "*") return true if (pattern.isEmpty() || fileName.isEmpty()) return false // init all matrix except [0][0] element as False val d = Array(pLen + 1) { BooleanArray(sLen + 1) } d[0][0] = true // DP compute for (pIdx in 1 until pLen + 1) { // the current character in the pattern is '*' if (pattern[pIdx - 1] == '*') { var sIdx = 1 // d[p_idx - 1][s_idx - 1] is a string-pattern match // on the previous step, i.e. one character before. // Find the first idx in string with the previous math. while (!d[pIdx - 1][sIdx - 1] && sIdx < sLen + 1) sIdx++ // If (string) matches (pattern), // when (string) matches (pattern)* as well d[pIdx][sIdx - 1] = d[pIdx - 1][sIdx - 1] // If (string) matches (pattern), // when (string)(whatever_characters) matches (pattern)* as well while (sIdx < sLen + 1) d[pIdx][sIdx++] = true } else if (pattern[pIdx - 1] == '?') { for (sIdx in 1 until sLen + 1) d[pIdx][sIdx] = d[pIdx - 1][sIdx - 1] } else { for (sIdx in 1 until sLen + 1) { // Match is possible if there is a previous match // and current characters are the same d[pIdx][sIdx] = d[pIdx - 1][sIdx - 1] && pattern[pIdx - 1] == fileName[sIdx - 1] } } } return d[pLen][sLen] }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,693
DS_Algo_Kotlin
MIT License
meistercharts-commons/src/commonMain/kotlin/it/neckar/open/kotlin/lang/RandomExt.kt
Neckar-IT
599,079,962
false
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
package it.neckar.open.kotlin.lang import kotlin.math.PI import kotlin.math.cos import kotlin.math.pow import kotlin.math.sqrt import kotlin.random.Random /** * Code adopted from KDS (License: Apache or MIT) */ fun Random.ints(): Sequence<Int> = sequence { while (true) yield(nextInt()) } fun Random.ints(from: Int, until: Int): Sequence<Int> = sequence { while (true) yield(nextInt(from, until)) } fun Random.ints(range: IntRange): Sequence<Int> = ints(range.start, range.endInclusive + 1) fun Random.doubles(): Sequence<Double> = sequence { while (true) yield(nextDouble()) } fun Random.floats(): Sequence<Float> = sequence { while (true) yield(nextFloat()) } fun <T> List<T>.random(random: Random = Random): T { if (this.isEmpty()) throw IllegalArgumentException("Empty list") return this[random.nextInt(this.size)] } fun <T> List<T>.randomWithWeights(weights: List<Double>, random: Random = Random): T = random.weighted(this.zip(weights).toMap()) operator fun Random.get(min: Double, max: Double): Double = min + nextDouble() * (max - min) operator fun Random.get(min: Float, max: Float): Float = min + nextFloat() * (max - min) operator fun Random.get(min: Int, max: Int): Int = min + nextInt(max - min) operator fun Random.get(range: IntRange): Int = range.start + this.nextInt(range.endInclusive - range.start + 1) operator fun Random.get(range: LongRange): Long = range.start + this.nextLong() % (range.endInclusive - range.start + 1) operator fun <T> Random.get(list: List<T>): T = list[this[list.indices]] fun <T> Random.weighted(weights: Map<T, Double>): T = shuffledWeighted(weights).first() fun <T> Random.weighted(weights: RandomWeights<T>): T = shuffledWeighted(weights).first() fun <T> Random.shuffledWeighted(weights: Map<T, Double>): List<T> = shuffledWeighted(RandomWeights(weights)) fun <T> Random.shuffledWeighted(values: List<T>, weights: List<Double>): List<T> = shuffledWeighted(RandomWeights(values, weights)) fun <T> Random.shuffledWeighted(weights: RandomWeights<T>): List<T> { val randoms = (weights.items.indices).map { -(nextDouble().pow(1.0 / weights.normalizedWeights[it])) } val sortedIndices = (weights.items.indices).sortedWith { a, b -> randoms[a].compareTo(randoms[b]) } return sortedIndices.map { weights.items[it] } } data class RandomWeights<T>(val weightsMap: Map<T, Double>) { constructor(vararg pairs: Pair<T, Double>) : this(mapOf(*pairs)) constructor(values: List<T>, weights: List<Double>) : this(values.zip(weights).toMap()) val items: List<T> = weightsMap.keys.toList() val weights: List<Double> = weightsMap.values.toList() val normalizedWeights: List<Double> = normalizeWeights(weights) companion object { private fun normalizeWeights(weights: List<Double>): List<Double> { val min = weights.minOrNull() ?: 0.0 return weights.map { (it + min) + 1 } } } } /** * Normal distribution. * Returns a value around the given center with the given sigma * * Returns random values around [center]. 95% of these values are within the range of 4 sigma (-2/+2) around the center */ fun randomNormal(center: Double, sigma: Double): Double { return center + (sigma * sqrt(-2.0 * kotlin.math.log(random.nextDouble(), 10.0)) * cos(2.0 * PI * random.nextDouble())) }
3
Kotlin
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
3,265
meistercharts
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2020/d20/Day20.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2020.d20 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.sqrt import kotlin.io.path.div import kotlin.io.path.useLines typealias Tile = List<String> /** * Returns all edges of this tile, read both clockwise (cw) * and counterclockwise (ccw). The order is: * cw top, cw right, cw bottom, cw left, * ccw top, ccw right, ccw bottom, ccw left */ fun Tile.edges(): List<String> = listOf( this.first(), String(this.map { it.last() }.toCharArray()), this.last().reversed(), String(this.reversed().map { it.first() }.toCharArray()), ).let { edges -> edges + edges.map { it.reversed() } } fun rotate(puzzle: List<String>): List<String> = puzzle[0].indices.map { x -> puzzle.indices.reversed().map { y -> puzzle[y][x] }.toCharArray() .let(::String) } fun flip(puzzle: List<String>): List<String> = puzzle.map { it.reversed() } /** * Order matters. Here, we optionally flip across the vertical axis, then rotate * some number of times clockwise. */ data class TileOrientation(val num: Int, val flip: Boolean, val rotate: Int) class Solver(private val tilesMap: Map<Int, Tile>) { // the tiles will assemble into a square image, so there are a // square number of them private val numTilesPerSide = com.groundsfam.advent.sqrt(tilesMap.size) private val tileSideLen = tilesMap.values.first().size // a table on which to lay down tiles to solve the puzzle. it // is just big enough to store the solved puzzle, so table[0][0] // must be a corner piece in correct orientation private val table = Array(numTilesPerSide) { Array<TileOrientation?>(numTilesPerSide) { null } } val cornerTiles: List<Int> private val puzzleEdges: Set<String> private val tilesByEdge: Map<String, Set<Int>> init { // map from an edge to all tiles having it as an edge, possibly flipped val tileEdges = mutableMapOf<String, MutableSet<Int>>() tilesMap.forEach { (num, tile) -> tile.edges().forEach { edge -> (tileEdges[edge] ?: mutableSetOf<Int>().also { tileEdges[edge] = it }) .add(num) } } tilesByEdge = tileEdges cornerTiles = tileEdges .filterValues { it.size == 1 } .also { puzzleEdges = it.keys }.values .map { it.first() } .groupBy { it } .mapValues { (_, v) -> v.size }.entries // edge tiles appear twice here, and corners appear four times .filter { (_, count) -> count == 4 } .let { cornerTiles -> cornerTiles.map { it.key } } } /** * Returns all edges of this tile, post transformation, read * both clockwise (cw) and counterclockwise (ccw). The order is: * cw top, cw right, cw bottom, cw left, * ccw top, ccw right, ccw bottom, ccw left */ fun TileOrientation.edges(): List<String> = tilesMap[num]!!.edges().take(4).let { unflippedEdges -> if (flip) { unflippedEdges // cw edges become ccw edges .map { it.reversed() } // the order changes to what was originally top, left, bottom, right .let { reversedEdges -> (0 until 4).map { reversedEdges[(4 - it) % 4] } } } else { unflippedEdges } }.let { unrotatedEdges -> // perform rotation (0 until 4).map { unrotatedEdges[(it + 4 - rotate) % 4] } }.let { edges -> edges + edges.map { it.reversed() } } fun TileOrientation.transformed(): Tile { val rowsFirst = rotate % 2 == 0 val reverseRows = if (flip) { rotate in setOf(0, 1) } else { rotate in setOf(2, 3) } val reverseCols = rotate in setOf(1, 2) val original = tilesMap[num]!! return if (rowsFirst) { (0 until tileSideLen) .let { if (reverseCols) it.reversed() else it } .map { j -> original[j].let { if (reverseRows) it.reversed() else it } } } else { (0 until tileSideLen) .let { if (reverseRows) it.reversed() else it } .map { i -> (0 until tileSideLen) .let { if (reverseCols) it.reversed() else it } .map { j -> original[j][i] } .toCharArray() .let(::String) } } } fun solvePuzzle(): List<String> { val firstCorner = cornerTiles[0] tilesMap[firstCorner]!!.edges() .take(4) .map { it in puzzleEdges } .let { (t, r, b, l) -> val firstCornerTurns = when { l && t -> 0 t && r -> 3 r && b -> 2 b && l -> 1 else -> throw RuntimeException("First corner $firstCorner has unexpected puzzle edge overlap") } table[0][0] = TileOrientation(firstCorner, false, firstCornerTurns) } (0 until numTilesPerSide).forEach { i -> if (i != 0) { // place tile based on the one above this spot val tileAbove = table[i-1][0] ?: throw RuntimeException("Tile not placed at (${i-1}, 0)!") val bottomEdge = tileAbove.edges()[2] val nextTile = tilesByEdge[bottomEdge]!! .filterNot { it == tileAbove.num } .first() table[i][0] = tilesMap[nextTile]!! .edges() .indexOf(bottomEdge) .let { matchingEdgeIdx -> // if tileAbove's CW bottom edge matches one of our CW edges, then a flip is required if (matchingEdgeIdx < 4) TileOrientation(nextTile, true, matchingEdgeIdx) // if tileAbove's CW bottom edge matches one of our CCW edges, then no flip is required else TileOrientation(nextTile, false, (8 - matchingEdgeIdx) % 4) } } (1 until numTilesPerSide).forEach { j -> // place tile based on the one to the left of this spot val tileLeft = table[i][j-1] ?: throw RuntimeException("Tile not placed at ($i, ${j-1})!") val rightEdge = tileLeft.edges()[1] val nextTile = tilesByEdge[rightEdge]!! .filterNot { it == tileLeft.num } .first() table[i][j] = tilesMap[nextTile]!! .edges() .indexOf(rightEdge) .let { matchingEdgeIdx -> // if tileAbove's CW right edge matches one of our CW edges, then a flip is required if (matchingEdgeIdx < 4) TileOrientation(nextTile, true, (matchingEdgeIdx + 3) % 4) // if tileAbove's CW bottom edge matches one of our CCW edges, then no flip is required else TileOrientation(nextTile, false, (7 - matchingEdgeIdx) % 4) } } } val ret = Array(numTilesPerSide * (tileSideLen - 2)) { "" } table.forEachIndexed { i, row -> val strings = row.map { if (it == null) throw RuntimeException("Table not filled out!") it.transformed() }.map { tile -> tile.map { // remove first and last character - they're part of the tile's border it.substring(1, it.length - 1) } }.reduce { tileA, tileB -> tileA.indices.map { tileA[it] + tileB[it] } } // don't include first or last row, they're part of the tiles' borders (1 until strings.size - 1).forEach { j -> ret[(tileSideLen - 2) * i + j - 1] = strings[j] } } return ret.toList() } } // sea monsters look like this // # // # ## ## ### // # # # # # # // size: 20x3 fun findSeaMonsters(puzzle: List<String>): Int { var orientedPuzzle = puzzle val seaMonster = listOf(18 to 0) + listOf(0, 5, 6, 11, 12, 17, 18, 19).map { it to 1 } + listOf(1, 4, 7, 10, 13, 16).map { it to 2 } repeat(8) { time -> val seaMonserPoints = mutableSetOf<Pair<Int, Int>>() (0..orientedPuzzle.size - 3).forEach { y -> (0..orientedPuzzle[y].length - 20).forEach { x -> if (seaMonster.all { (i, j) -> orientedPuzzle[y+j][x+i] == '#' }) { seaMonserPoints.addAll(seaMonster.map { (i, j) -> (x+i) to (y+j) }) } } } if (seaMonserPoints.isNotEmpty()) { return puzzle.sumOf { row -> row.count { it == '#' } } - seaMonserPoints.size } orientedPuzzle = if (time == 3) flip(orientedPuzzle) else rotate(orientedPuzzle) } return 0 } fun main() { val solver = (DATAPATH / "2020/day20.txt").useLines { lines -> val map = mutableMapOf<Int, Tile>() lines.chunked(12).forEach { chunk -> map[chunk.first().substring(5, 9).toInt()] = chunk.subList(1, 11) } Solver(map) } solver.cornerTiles .map { it.toLong() } .reduce { a, b -> a * b } .also { println("Part one: $it") } solver.solvePuzzle() .let(::findSeaMonsters) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
9,997
advent-of-code
MIT License
src/main/kotlin/org/vitrivr/cottontail/utilities/name/Name.kt
frankier
278,349,990
true
{"Kotlin": 1020644, "Dockerfile": 280}
package org.vitrivr.cottontail.utilities.name /** * A [Name] that identifies a DBO used within Cottontail DB. * * @author <NAME> * @version 1.0 */ class Name(name: String) { companion object { /** The separator between Cottontail DB name components. */ const val COTTONTAIL_NAME_COMPONENT_SEPARATOR = '.' /** The separator between Cottontail DB name components. */ const val COTTONTAIL_NAME_COMPONENT_ROOT = "warren" /** [Regex] to match [NameType.SIMPLE]*/ val SIMPLE_NAME_REGEX = Regex("^([a-zA-Z0-9\\-_()]+)$") /** [Regex] to match [NameType.FQN]*/ val FQN_NAME_REGEX = Regex("^([a-zA-Z0-9\\-_]+)(\\.[a-zA-Z0-9\\-_()]+){0,3}$") /** [Regex] to match [NameType.FQN_WILDCARD]*/ val FQN_WILDCARD_NAME_REGEX = Regex("^([a-zA-Z0-9\\-_]+){1}(\\.([a-zA-Z0-9\\-_()]+|\\*)){0,3}\$") /** [Regex] to match [NameType.FQN_WILDCARD]*/ val WILDCARD_NAME_REGEX = Regex("^\\*\$") /** The separator between Cottontail DB name components. */ val COTTONTAIL_ROOT_NAME = Name("warren") /** * Finds the longest, common prefix the [Name]s in the given collection share. * * @param names Collection of [Name]s * @return Longest, common prefix as [Name] */ fun findLongestCommonPrefix(names: Collection<Name>): Name { val prefix = Array<String?>(3) { null } for (i in 0 until 3) { val d = names.mapNotNull { val split = it.name.split('.') if (i < split.size) { split[i] } else { null } }.distinct() if (d.size == 1) { prefix[i] = d.first() } else { break } } return Name(prefix.filterNotNull().joinToString(separator = ".")) } } /** Cottontail DB [Name]s are always lower-case values. */ val name = name.toLowerCase() /** The [NameType] of this [Name]. */ val type: NameType = when { this.name.matches(SIMPLE_NAME_REGEX) -> NameType.SIMPLE this.name.matches(FQN_NAME_REGEX) -> NameType.FQN this.name.matches(FQN_WILDCARD_NAME_REGEX) -> NameType.FQN_WILDCARD this.name.matches(WILDCARD_NAME_REGEX) -> NameType.WILDCARD else -> throw IllegalArgumentException("The provided name $name does not match any of the supported name types.") } /** * Appends the other [Name] to this [Name]. * * @param other The other [Name]. * @return The concatenated [Name]. */ fun append(other: Name): Name = Name("$this$COTTONTAIL_NAME_COMPONENT_SEPARATOR${other.name}") /** * Appends the other name component to this [Name]. * * @param other The other name component. * @return The concatenated [Name]. */ fun append(other: String): Name = Name("$this$COTTONTAIL_NAME_COMPONENT_SEPARATOR$other") /** * Returns the first [Name] component of this [Name], which is a [Name] again. If this is of [NameType.SIMPLE], * then the same [Name] is returned. * * @return Last [Name] component of this [Name] */ fun first(): Name = Name(this.name.split(COTTONTAIL_NAME_COMPONENT_SEPARATOR).first()) /** * Returns the last [Name] component of this [Name], which is a [Name] again. If this is of [NameType.SIMPLE], * then the same [Name] is returned. * * @return Last [Name] component of this [Name] */ fun last(): Name = Name(this.name.split(COTTONTAIL_NAME_COMPONENT_SEPARATOR).last()) /** * Returns true, if this [Name] is a root name (i.e. equals to the [COTTONTAIL_ROOT_NAME]). * * @return True if this [Name] is a root name. */ fun isRoot(): Boolean = this.name == COTTONTAIL_NAME_COMPONENT_ROOT /** * Checks if this [Name] is a prefix of the provided [Name]. * * @param that The [Name] to check. */ fun isPrefixOf(that: Name): Boolean { val o = that.name.split(COTTONTAIL_NAME_COMPONENT_SEPARATOR) val t = this.name.split(COTTONTAIL_NAME_COMPONENT_SEPARATOR) return if (o.size > t.size) false else o.mapIndexed { i, s -> s == t[i] }.all { it } } /** * Returns the [Match] between two [Name]. The rules of matching are as follows: * * - Two [Name]s match as [Match.EQUAL] if they are exactly equal. * - A [NameType.SIMPLE] and a [NameType.FQN] match as [Match.EQUIVALENT], if their last component is equal. * - A [NameType.FQN_WILDCARD] matches [NameType.SIMPLE] and [NameType.FQN] as [Match.INCLUDES], if they share a common prefix. * - A [NameType.WILDCARD] matches all [NameType.SIMPLE] and [NameType.FQN] as [Match.INCLUDES] * * If none of the above is true, two [Name]s don't match at all (i.e. [Match.NO_MATCH]). */ fun match(that: Name): Match = when (this.type) { NameType.FQN -> when (that.type) { NameType.FQN -> if (this.name == that.name) Match.EQUAL else Match.NO_MATCH NameType.SIMPLE -> if (this.last().name == that.name) Match.EQUIVALENT else Match.NO_MATCH NameType.FQN_WILDCARD -> if (this.name.startsWith(that.name.subSequence(0..that.name.length - 3))) Match.INCLUDES else Match.NO_MATCH NameType.WILDCARD -> Match.INCLUDES } NameType.SIMPLE -> when (that.type) { NameType.FQN -> if (this.name == that.last().name) Match.EQUIVALENT else Match.NO_MATCH NameType.SIMPLE -> if (this.name == that.name) Match.EQUAL else Match.NO_MATCH NameType.FQN_WILDCARD -> Match.NO_MATCH NameType.WILDCARD -> Match.INCLUDES } NameType.FQN_WILDCARD -> when (that.type) { NameType.FQN -> if (that.name.startsWith(this.name.substring(0..this.name.length - 3))) Match.INCLUDES else Match.NO_MATCH NameType.SIMPLE -> Match.NO_MATCH NameType.FQN_WILDCARD -> if (this.name == that.name) Match.EQUAL else Match.NO_MATCH NameType.WILDCARD -> Match.NO_MATCH } NameType.WILDCARD -> when (that.type) { NameType.FQN -> Match.INCLUDES NameType.SIMPLE -> Match.INCLUDES NameType.FQN_WILDCARD -> Match.NO_MATCH NameType.WILDCARD -> Match.EQUAL } } /** * Normalizes this [Name] by removing the provided prefix. If this [Name] does not start with the given prefix, then the [Name] will not be changed. * * @param prefix The prefix [Name] relative to which the name should be normalized. */ fun normalize(prefix: Name): Name = if (this.name.startsWith(prefix.name)) { Name(this.name.substring(prefix.name.length + 1 until this.name.length)) } else { this } /** * Returns a [String] representation of this [Name]. * * @return [String] for this [Name]. */ override fun toString(): String = this.name /** * */ override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + type.hashCode() return result } /** * */ override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is Name) return false return other.name == this.name && other.type == this.type } }
0
Kotlin
0
0
e4ec66eaf014bb8ea4399cc7ea54062f16cf0c60
7,544
cottontaildb
MIT License
src/main/kotlin/g1101_1200/s1191_k_concatenation_maximum_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1101_1200.s1191_k_concatenation_maximum_sum // #Medium #Array #Dynamic_Programming #2023_05_25_Time_389_ms_(100.00%)_Space_77.8_MB_(100.00%) class Solution { private var mod = (1e9 + 7).toInt() fun kConcatenationMaxSum(arr: IntArray, k: Int): Int { var sum: Long = 0 for (i in arr.indices) { sum += arr[i].toLong() } return if (sum <= 0 || k == 1) { var cb: Long = 0 var ob: Long = 0 for (i in arr.indices) { cb = if (arr[i] + cb > arr[i]) { arr[i] + cb } else { arr[i].toLong() } if (ob < cb) { ob = cb } } if (k == 1) { return (ob % mod).toInt() } for (i in arr.indices) { cb = if (arr[i] + cb > arr[i]) { arr[i] + cb } else { arr[i].toLong() } if (ob < cb) { ob = cb } } (ob % mod).toInt() } else { var max1: Long = 0 var smax: Long = 0 for (i in arr.indices.reversed()) { smax += arr[i].toLong() if (smax > max1) { max1 = smax } } max1 %= mod.toLong() var max2: Long = 0 smax = 0 for (i in arr.indices) { smax += arr[i].toLong() if (smax > max2) { max2 = smax } } max2 %= mod.toLong() val ans = max1 + (k - 2) * sum + max2 (ans % mod).toInt() } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,821
LeetCode-in-Kotlin
MIT License
src/year2015/day22/Day22.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day22 import readInput import kotlin.math.max fun main() { // test if implementation meets criteria from the description, like: val input = readInput("2015", "Day22") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = winWithLeastManaSpent(toGame(input)) ?: error("Unable to win") private fun part2(input: List<String>) = winWithLeastManaSpent( game = toGame(input), playerHpDrain = 1, ) ?: error("Unable to win") private fun toGame(input: List<String>): Game { val (bossInitialHP, bossDmg) = input.map { it.split(' ').last().toInt() } return Game( bossHP = bossInitialHP, bossDmg = bossDmg, ) } private fun winWithLeastManaSpent( game: Game, playerHpDrain: Int = 0, cache: MutableMap<Game, Int?> = hashMapOf() ): Int? { return cache.getOrPut(game) { var nextGame = game.tickEffects() if (nextGame.bossHP <= 0) { return@getOrPut nextGame.manaSpent } nextGame = nextGame.copy(playerHP = nextGame.playerHP - playerHpDrain) if (nextGame.playerHP <= 0) { return@getOrPut null } val availableSpells = Spell.values().filter { val canReapplyEffect = when (it) { Spell.Shield -> nextGame.effects.shieldTimer == 0 Spell.Poison -> nextGame.effects.poisonTimer == 0 Spell.Recharge -> nextGame.effects.rechargeTimer == 0 else -> true } canReapplyEffect && it.cost <= nextGame.playerMana } val gameOnStartOfRound = nextGame return@getOrPut availableSpells.mapNotNull { nextGame = gameOnStartOfRound nextGame = nextGame.playerTurn(it) if (nextGame.bossHP <= 0) { return@mapNotNull nextGame.manaSpent } nextGame = nextGame.tickEffects() if (nextGame.bossHP <= 0) { return@mapNotNull nextGame.manaSpent } nextGame = nextGame.bossTurn() if (nextGame.playerHP <= 0) { return@mapNotNull null } winWithLeastManaSpent(nextGame, playerHpDrain, cache) }.minOrNull() } } private data class Game( val bossHP: Int, val bossDmg: Int, val playerHP: Int = 50, val playerMana: Int = 500, val manaSpent: Int = 0, val effects: Effects = Effects(), ) { fun tickEffects() = Game( bossHP = bossHP - if (effects.poisonTimer > 0) 3 else 0, bossDmg = bossDmg, playerHP = playerHP, playerMana = playerMana + if (effects.rechargeTimer > 0) 101 else 0, manaSpent = manaSpent, effects = effects.tick(), ) fun bossTurn() = Game( bossHP = bossHP, bossDmg = bossDmg, playerHP = playerHP - (bossDmg - if (effects.shieldTimer > 0) 7 else 0), playerMana = playerMana, manaSpent = manaSpent, effects = effects, ) fun playerTurn(spell: Spell) = Game( bossHP = bossHP - spell.dmg, bossDmg = bossDmg, playerHP = playerHP + spell.heal, playerMana = playerMana - spell.cost, manaSpent = manaSpent + spell.cost, effects = effects.cast(spell), ) } private enum class Spell( val cost: Int, val dmg: Int, val heal: Int, ) { MagicMissile(53, 4, 0), Drain(73, 2, 2), Shield(113, 0, 0), Poison(173, 0, 0), Recharge(229, 0, 0), } private data class Effects( val poisonTimer: Int = 0, val shieldTimer: Int = 0, val rechargeTimer: Int = 0, ) { fun tick() = Effects( poisonTimer = max(poisonTimer - 1, 0), shieldTimer = max(shieldTimer - 1, 0), rechargeTimer = max(rechargeTimer - 1, 0), ) fun cast(spell: Spell) = Effects( poisonTimer = if (spell == Spell.Poison) 6 else poisonTimer, shieldTimer = if (spell == Spell.Shield) 6 else shieldTimer, rechargeTimer = if (spell == Spell.Recharge) 5 else rechargeTimer, ) }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
4,080
AdventOfCode
Apache License 2.0
kotlin/src/main/kotlin/com/pbh/soft/day7/Day7Solver.kt
phansen314
579,463,173
false
{"Kotlin": 105902}
package com.pbh.soft.day7 import cc.ekblad.konbini.* import com.pbh.soft.common.Solver import com.pbh.soft.common.parsing.ParsingUtils.newlineP import com.pbh.soft.common.parsing.ParsingUtils.onSuccess import com.pbh.soft.common.parsing.ParsingUtils.parseMap import com.pbh.soft.day7.Card._J import com.pbh.soft.day7.HandType.* import com.pbh.soft.day7.Parsing.problemP import mu.KLogging object Day7Solver : Solver, KLogging() { override fun solveP1(text: String): String = problemP.parse(text).onSuccess { problem -> problem .map { ClassifiedHandXBid(it.hand, it.bid, StandardClassifier(it.hand)) } .sortedWith(StandardComparator) .mapIndexed { i, chb -> (i + 1) * chb.bid } .sum() .toString() } override fun solveP2(text: String): String = problemP.parse(text).onSuccess { problem -> problem .map { ClassifiedHandXBid(it.hand, it.bid, WithJokersClassifier(it.hand)) } .sortedWith(WithJokerRuleComparator) .mapIndexed { i, chb -> (i + 1) * chb.bid } .sum() .toString() } } typealias Hand = List<Card> data class HandXBid(val hand: Hand, val bid: Long) data class ClassifiedHandXBid( val hand: Hand, val bid: Long, val type: HandType ) enum class Card(val chr: Char) { _2('2'), _3('3'), _4('4'), _5('5'), _6('6'), _7('7'), _8('8'), _9('9'), _T('T'), _J('J'), _Q('Q'), _K('K'), _A('A'); companion object { val charToCard = entries.associateBy { it.chr } } } enum class HandType { HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, FULL_HOUSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND } interface Classifier : (Hand) -> HandType object StandardClassifier : Classifier { override fun invoke(hand: Hand): HandType { val cmap = hand.groupingBy { it }.eachCount() return if (cmap.size == 1) FIVE_OF_A_KIND else if (cmap.size == 2) { val x = cmap.values.first() if (x == 1 || x == 4) FOUR_OF_A_KIND else FULL_HOUSE } else if (cmap.size == 3) { if (cmap.values.any { it == 3 }) THREE_OF_A_KIND else TWO_PAIR } else if (cmap.size == 5) HIGH_CARD else ONE_PAIR } } object WithJokersClassifier : Classifier { override fun invoke(hand: Hand): HandType { val cmap = hand.groupingBy { it }.eachCount() return when (cmap[_J]) { null -> StandardClassifier(hand) 1 -> when (cmap.size) { 2 -> FIVE_OF_A_KIND 3 -> if (cmap.values.any { it == 2 }) FULL_HOUSE else FOUR_OF_A_KIND 4 -> THREE_OF_A_KIND else -> ONE_PAIR } 2 -> when (cmap.size) { 2 -> FIVE_OF_A_KIND 3 -> FOUR_OF_A_KIND else -> THREE_OF_A_KIND } 3 -> if (cmap.size == 2) FIVE_OF_A_KIND else FOUR_OF_A_KIND 4 -> FIVE_OF_A_KIND else -> FIVE_OF_A_KIND } } } object WithJokerRuleComparator : Comparator<ClassifiedHandXBid> { val cardComparator: Comparator<Card> = Comparator { c1, c2 -> if (c1 == c2) 0 else if (c1 == _J) -1 else if (c2 == _J) 1 else if (c1 < c2) -1 else 1 } override fun compare(o1: ClassifiedHandXBid, o2: ClassifiedHandXBid): Int { return if (o1.type < o2.type) -1 else if (o1.type > o2.type) 1 else { for (i in o1.hand.indices) { val comp = cardComparator.compare(o1.hand[i], o2.hand[i]) if (comp < 0) return -1 if (comp > 0) return 1 } 0 } } } object StandardComparator : Comparator<ClassifiedHandXBid> { override fun compare(o1: ClassifiedHandXBid, o2: ClassifiedHandXBid): Int { return if (o1.type < o2.type) -1 else if (o1.type > o2.type) 1 else { for (i in o1.hand.indices) { if (o1.hand[i] < o2.hand[i]) return -1 if (o1.hand[i] > o2.hand[i]) return 1 } 0 } } } object Parsing { val handXbidP = parser { val hand = many1(parseMap(Card.charToCard)); whitespace1(); val bid = integer() HandXBid(hand, bid) } val problemP = chain(handXbidP, newlineP).map { it.terms } }
0
Kotlin
0
0
7fcc18f453145d10aa2603c64ace18df25e0bb1a
4,004
advent-of-code
MIT License
src/Day06.kt
Yasenia
575,276,480
false
{"Kotlin": 15232}
fun main() { fun getStartOfMessage(message: String, markerSize: Int): Int { val data = message.toCharArray() var startPosition = markerSize while (data.slice(startPosition - markerSize until startPosition).distinct().count() < markerSize) startPosition++ return startPosition } fun part1(input: List<String>): Int = getStartOfMessage(input[0], 4) fun part2(input: List<String>): Int = getStartOfMessage(input[0], 14) val testInput1 = readInput("Day06_test_1") check(part1(testInput1) == 7) check(part2(testInput1) == 19) val testInput2 = readInput("Day06_test_2") check(part1(testInput2) == 5) check(part2(testInput2) == 23) val testInput3 = readInput("Day06_test_3") check(part1(testInput3) == 6) check(part2(testInput3) == 23) val testInput4 = readInput("Day06_test_4") check(part1(testInput4) == 10) check(part2(testInput4) == 29) val testInput5 = readInput("Day06_test_5") check(part1(testInput5) == 11) check(part2(testInput5) == 26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9300236fa8697530a3c234e9cb39acfb81f913ba
1,145
advent-of-code-kotlin-2022
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/RankTeamsByVotes.kt
faniabdullah
382,893,751
false
null
//In a special ranking system, each voter gives a rank from highest to lowest //to all teams participated in the competition. // // The ordering of teams is decided by who received the most position-one votes. // If two or more teams tie in the first position, we consider the second //position to resolve the conflict, if they tie again, we continue this process until the //ties are resolved. If two or more teams are still tied after considering all //positions, we rank them alphabetically based on their team letter. // // Given an array of strings votes which is the votes of all voters in the //ranking systems. Sort all teams according to the ranking system described above. // // Return a string of all teams sorted by the ranking system. // // // Example 1: // // //Input: votes = ["ABC","ACB","ABC","ACB","ACB"] //Output: "ACB" //Explanation: Team A was ranked first place by 5 voters. No other team was //voted as first place so team A is the first team. //Team B was ranked second by 2 voters and was ranked third by 3 voters. //Team C was ranked second by 3 voters and was ranked third by 2 voters. //As most of the voters ranked C second, team C is the second team and team B //is the third. // // // Example 2: // // //Input: votes = ["WXYZ","XYZW"] //Output: "XWYZ" //Explanation: X is the winner due to tie-breaking rule. X has same votes as W //for the first position but X has one vote as second position while W doesn't //have any votes as second position. // // // Example 3: // // //Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"] //Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK" //Explanation: Only one voter so his votes are used for the ranking. // // // Example 4: // // //Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"] //Output: "ABC" //Explanation: //Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters. // //Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters. // //Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters. // //There is a tie and we rank teams ascending by their IDs. // // // Example 5: // // //Input: votes = ["M","M","M","M"] //Output: "M" //Explanation: Only team M in the competition so it has the first rank. // // // // Constraints: // // // 1 <= votes.length <= 1000 // 1 <= votes[i].length <= 26 // votes[i].length == votes[j].length for 0 <= i, j < votes.length. // votes[i][j] is an English upper-case letter. // All characters of votes[i] are unique. // All the characters that occur in votes[0] also occur in votes[j] where 1 <= //j < votes.length. // // Related Topics Array Hash Table String Sorting Counting 👍 616 👎 65 package leetcodeProblem.leetcode.editor.en class RankTeamsByVotes { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun rankTeams(votes: Array<String>): String { val matrix = Array(26) { IntArray(27) } for (i in matrix.indices) { matrix[i][26] = ('A' + i).toInt() } for (str in votes) { for (i in str.indices) { matrix[str[i] - 'A'][i]++ } } matrix.sortWith(Comparator { a, b -> var start = 0 while (start < 27 && a[start] == b[start]) { start++ } if (start == 26) { a[start] - b[start] } else { b[start] - a[start] } }) val res = StringBuilder() for (i in matrix) { if (votes[0].contains(i[26].toChar())) { res.append(i[26].toChar()) } } return res.toString() } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { val result = RankTeamsByVotes.Solution().rankTeams( arrayOf<String>( "FVSHJIEMNGYPTQOURLWCZKAX", "AITFQORCEHPVJMXGKSLNZWUY", "OTERVXFZUMHNIYSCQAWGPKJL", "VMSERIJYLZNWCPQTOKFUHAXG", "VNHOZWKQCEFYPSGLAMXJIUTR", "ANPHQIJMXCWOSKTYGULFVERZ", "RFYUXJEWCKQOMGATHZVILNSP", "SCPYUMQJTVEXKRNLIOWGHAFZ", "VIKTSJCEYQGLOMPZWAHFXURN", "SVJICLXKHQZTFWNPYRGMEUAO", "JRCTHYKIGSXPOZLUQAVNEWFM", "NGMSWJITREHFZVQCUKXYAPOL", "WUXJOQKGNSYLHEZAFIPMRCVT", "PKYQIOLXFCRGHZNAMJVUTWES", "FERSGNMJVZXWAYLIKCPUQHTO", "HPLRIUQMTSGYJVAXWNOCZEKF", "JUVWPTEGCOFYSKXNRMHQALIZ", "MWPIAZCNSLEYRTHFKQXUOVGJ", "EZXLUNFVCMORSIWKTYHJAQPG", "HRQNLTKJFIEGMCSXAZPYOVUW", "LOHXVYGWRIJMCPSQENUAKTZF", "XKUTWPRGHOAQFLVYMJSNEIZC", "WTCRQMVKPHOSLGAXZUEFYNJI" ) ) println(result) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
5,070
dsa-kotlin
MIT License
java/com/google/android/libraries/pcc/chronicle/analysis/Utils.kt
google
564,990,777
false
{"Kotlin": 1440335, "Starlark": 162149, "Java": 10061, "AIDL": 5852, "Python": 4367, "Dockerfile": 2035, "Shell": 1301}
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.analysis import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy import com.google.android.libraries.pcc.chronicle.api.StorageMedia import com.google.android.libraries.pcc.chronicle.api.policy.PolicyTarget import com.google.android.libraries.pcc.chronicle.api.policy.StorageMedium import java.time.Duration /** Finds the most restrained [ManagementStrategy] from the receiving list. */ fun List<ManagementStrategy>.mostRestrained(): ManagementStrategy { // Use minOfWith, because comparators order in ascending order, and our comparator gives // more-restrained strategies a negative value (placing them towards the front of the order). return minOfWith(ManagementStrategyComparator) { it } } /** * Analysis-specific comparator for [ManagementStrategies][ManagementStrategy]. * * Applies a lexicographic ordering to the components of a [ManagementStrategy], implying that more * restrained strategies come before more liberal strategies. From most significant to least * significant, the components are: * * 1. [StorageMedia], as characterized by that media's [danger][StorageMedia.danger] level. * 1. Whether or not the storage will be [encrypted]. * 1. The [time to live][StorageMedia.ttl]. * * **Note:** [PassThru][ManagementStrategy.PassThru] strategies are considered the most restrained * of all, and are interpreted as being zero danger storage (because nothing is stored). */ object ManagementStrategyComparator : Comparator<ManagementStrategy?> { override fun compare(a: ManagementStrategy?, b: ManagementStrategy?): Int { if (a == b) return 0 if (a == null) return 1 if (b == null) return -1 if (a is ManagementStrategy.PassThru) return -1 if (b is ManagementStrategy.PassThru) return 1 a as ManagementStrategy.Stored b as ManagementStrategy.Stored if (a.media != b.media) return a.media.danger - b.media.danger if (a.encrypted != b.encrypted) { if (a.encrypted) return -1 return 1 } return (a.ttl ?: Duration.ZERO).compareTo(b.ttl ?: Duration.ZERO) } } /** * Converts a [PolicyTarget's][PolicyTarget] retentions and max age into a list of * [ManagementStrategies][ManagementStrategy]. */ fun PolicyTarget.retentionsAsManagementStrategies(): List<ManagementStrategy> { if (maxAgeMs == 0L) return listOf(ManagementStrategy.PassThru) return retentions.map { ManagementStrategy.Stored( it.encryptionRequired, when (it.medium) { StorageMedium.RAM -> StorageMedia.MEMORY StorageMedium.DISK -> StorageMedia.LOCAL_DISK }, Duration.ofMillis(maxAgeMs) ) } }
0
Kotlin
8
27
cc72138bf0d0d77aedbc05dd4d3d9e4bb7e28f17
3,267
private-compute-libraries
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day23.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year18 import com.grappenmaker.aoc.* fun PuzzleSet.day23() = puzzle(day = 23) { data class Bot(val pos: Point3D, val r: Int) val bots = inputLines.map { l -> val (x, y, z, r) = l.splitInts() Bot(Point3D(x, y, z), r) } fun Point3D.inRange(bot: Bot) = this manhattanDistanceTo bot.pos <= bot.r val target = bots.maxBy { it.r } partOne = bots.count { it.pos.inRange(target) }.s() // You will have to know, above this single line of code were about 80 lines of ideas written out // to solve the problem. Initial idea was to... do a bunch of spatial math to hope to decrease the search area // to a reasonable size, then bruteforce... // Yeah this problem was really fucking hard to me fun Bot.potential(other: Bot) = pos manhattanDistanceTo other.pos <= r + other.r // Set because we do `in` checks later val graph = bots.associateWith { b -> (bots - b).filter { b.potential(it) }.toSet() } // // Idea: recursive algorithm to do it // // For each point, connect it to another, recursive down the chain // // Then each iteration, if there is no connection, discard it // fun recurse(curr: Set<Bot>): Set<Bot> { // if (curr.size > 2 && curr.any { p -> (curr - p).any { o -> o !in graph.getValue(p) } }) return curr // return curr.flatMap { p -> graph.getValue(p).filter { it !in curr }.map { o -> recurse(curr + o) } }.maxByOrNull { it.size } ?: curr // } // // That did not work, now we can be a little bit smarter about it. // // We can keep track of all visitable points in this iteration // // We can always look at the node with the most neighbours, that makes intuitive sense // // We can also immediately discard stuff that isn't neighbour with the next added node! // // That way we don't have to check anything else if that makes sense // fun recurse(todo: Set<Bot> = bots.toSet(), soFar: Set<Bot> = emptySet()): Set<Bot> { // if (todo.isEmpty()) return soFar // // return todo.map { n -> // val neigh = graph.getValue(n) // recurse(todo.filterTo(hashSetOf()) { it in neigh }, soFar + n) // }.maxByOrNull { it.size } ?: soFar // } // That did not work either, guess I am not smart enough // Wikipedia with the rescue, teaching me about cliques /* algorithm BronKerbosch2(R, P, X) is if P and X are both empty then report R as a maximal clique choose a pivot vertex u in P ⋃ X for each vertex v in P \ N(u) do BronKerbosch2(R ⋃ {v}, P ⋂ N(v), X ⋂ N(v)) P := P \ {v} X := X ⋃ {v} */ fun algo(r: Set<Bot> = emptySet(), p: Set<Bot> = bots.toSet(), x: Set<Bot> = emptySet()): Set<Bot> { if (p.isEmpty() && x.isEmpty()) return r // How to choose? Well, we know that we end when we find the best solution // We find that solution the quickest if u has the highest potential, which is of course ITS neighbour count // This apparently makes a huge difference, I tried the plain algorithm first which did not yield a // solution in a reasonable amount of time. val u = (p + x).maxBy { graph.getValue(it).size } return (p - graph.getValue(u)).map { v -> // return p.asSequence().map { v -> val neighs = graph.getValue(v) algo(r + v, p.intersect(neighs), x.intersect(neighs)) }.maxBy { it.size } } // Now at the set of points of most overlap, we know that, since manhattan distance, the answer is equal to // the distance function (distance to center - radius, as for all circles) since any rotation to that is just // the same if that makes sense (it does not) // Check for max because farthest away on circle distance is closest // (counterintuitive, did this wrong the first time, math is hard) partTwo = algo().maxOf { it.pos.manhattanDistance - it.r }.s() // Hard puzzle, part one was really easy though... how would you come up with this algorithm yourself? // It makes sense where it comes from but I would have never thought of doing that... }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
4,218
advent-of-code
The Unlicense
src/main/kotlin/fijb/leetcode/algorithms/A4MedianOfTwoSortedArrays.kt
fi-jb
552,324,917
false
{"Kotlin": 22836}
package fijb.leetcode.algorithms //https://leetcode.com/problems/median-of-two-sorted-arrays/ object A4MedianOfTwoSortedArrays { fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val nums = arrayListOf<Int>() var i1 = 0 var i2 = 0 val s = (nums1.size + nums2.size) while (i1 < nums1.size && i2 < nums2.size) { if (i1 + i2 > s) break if (nums1[i1] < nums2[i2]) nums.add( nums1[i1 ++] ) else nums.add( nums2[i2 ++] ) } val h = s / 2 val h1 = minOf(nums1.size, h + 1) val h2 = minOf(nums2.size, h + 1) while (i1 < h1) nums.add( nums1[i1 ++] ) while (i2 < h2) nums.add( nums2[i2 ++] ) return if (s % 2 == 0) 0.5 * (nums[h - 1] + nums[h]) else nums[h].toDouble() } }
0
Kotlin
0
0
f0d59da5bcffaa7a008fe6b83853306d40ac4b90
828
leetcode
MIT License
src/Day09.kt
mihansweatpants
573,733,975
false
{"Kotlin": 31704}
import java.lang.IllegalArgumentException import kotlin.math.abs fun main() { fun part1(moves: List<RopeMove>): Int { val visitedPositions = mutableSetOf<KnotPosition>() var headKnotPosition = KnotPosition(0, 0) var tailKnotPosition = KnotPosition(0, 0) visitedPositions.add(tailKnotPosition) for ((direction, steps) in moves) { repeat(steps) { headKnotPosition = headKnotPosition.move(direction) tailKnotPosition = tailKnotPosition.catchUp(headKnotPosition) visitedPositions.add(tailKnotPosition) } } return visitedPositions.size } fun part2(moves: List<RopeMove>): Int { val visitedPositions = mutableSetOf<KnotPosition>() val rope = Array(10) { KnotPosition(0, 0) } visitedPositions.add(rope.last()) for ((direction, steps) in moves) { repeat(steps) { rope[0] = rope[0].move(direction) for (i in 1..rope.lastIndex) { rope[i] = rope[i].catchUp(rope[i - 1]) } visitedPositions.add(rope.last()) } } return visitedPositions.size } val input = readInput("Day09") .lines() .map { it.split(" ") } .map { (direction, steps) -> RopeMove(direction, steps.toInt()) } println(part1(input)) println(part2(input)) } private data class RopeMove( val direction: String, val steps: Int ) private data class KnotPosition( val x: Int, val y: Int ) { fun move(direction: String, steps: Int = 1): KnotPosition { return when (direction) { "U" -> this.copy(y = y + steps) "D" -> this.copy(y = y - steps) "L" -> this.copy(x = x - steps) "R" -> this.copy(x = x + steps) else -> throw IllegalArgumentException("Unknown direction $direction") } } fun catchUp(other: KnotPosition): KnotPosition { val xDiff = abs(this.x - other.x) val yDiff = abs(this.y - other.y) val moves = if (xDiff == 0 && yDiff >= 2) { listOf(this.catchUpVertically(other)) } else if (xDiff >= 2 && yDiff == 0) { listOf(this.catchUpHorizontally(other)) } else if (xDiff >= 2 || yDiff >= 2) { catchUpDiagonally(other) } else { emptyList() } var newPosition = this for ((direction, steps) in moves) { newPosition = newPosition.move(direction, steps) } return newPosition } fun catchUpDiagonally(other: KnotPosition): List<RopeMove> { var toX = catchUpHorizontally(other) var toY = catchUpVertically(other) if (toX.steps < toY.steps) { toX = toX.copy(steps = toX.steps + 1) } else if (toX.steps > toY.steps) { toY = toY.copy(steps = toY.steps + 1) } return listOf(toX, toY) } fun catchUpHorizontally(other: KnotPosition): RopeMove { val direction = if (other.x > this.x) "R" else "L" var distance = abs(this.x - other.x) if (distance > 0) distance -= 1 return RopeMove(direction, distance) } fun catchUpVertically(other: KnotPosition): RopeMove { val direction = if (other.y > this.y) "U" else "D" var distance = abs(this.y - other.y) if (distance > 0) distance -= 1 return RopeMove(direction, distance) } }
0
Kotlin
0
0
0de332053f6c8f44e94f857ba7fe2d7c5d0aae91
3,529
aoc-2022
Apache License 2.0
melif/src/main/kotlin/ru/ifmo/ctddev/isaev/datasetFilter.kt
siviae
53,358,845
false
{"Kotlin": 152748, "Java": 152582}
package ru.ifmo.ctddev.isaev import org.slf4j.Logger import org.slf4j.LoggerFactory import ru.ifmo.ctddev.isaev.point.Point import java.util.* /** * @author iisaev */ enum class NormalizationMode { NONE, VALUE_BASED, MEASURE_BASED } fun DoubleArray.normalize(min: Double, max: Double) { this.forEachIndexed { i, value -> this[i] = (value - min) / (max - min) } } class DataSetEvaluator(private val normMode: NormalizationMode) { constructor() : this(NormalizationMode.VALUE_BASED) private fun evaluateMeasuresHelper(original: FeatureDataSet, measures: Array<out RelevanceMeasure>): List<DoubleArray> { return measures.map { m -> val evaluated = m.evaluate(original) when (normMode) { NormalizationMode.NONE -> Unit NormalizationMode.VALUE_BASED -> evaluated.normalize(evaluated.min()!!, evaluated.max()!!) NormalizationMode.MEASURE_BASED -> evaluated.normalize(m.minValue, m.maxValue) } return@map evaluated } } private fun evaluateMeasures(original: FeatureDataSet, measureCosts: Point, vararg measures: RelevanceMeasure): List<EvaluatedFeature> { if (measureCosts.coordinates.size != measures.size) { throw IllegalArgumentException("Number of given measures mismatch with measureCosts dimension") } val features = original.features val valuesForEachMeasure = evaluateMeasuresHelper(original, measures) val ensembleMeasures = 0.until(features.size) .map { i -> measureCosts.coordinates.zip(valuesForEachMeasure.map { it[i] }) } .map { it.sumByDouble { (measureCost, measureValue) -> measureCost * measureValue } } return features.zip(ensembleMeasures) .map { (f, m) -> EvaluatedFeature(f, m) } } fun evaluateFeatures(original: FeatureDataSet, measureCosts: Point, measures: Array<out RelevanceMeasure> ): Sequence<EvaluatedFeature> { return evaluateMeasures(original, measureCosts, *measures) .sortedBy { it.measure } .asSequence() } fun evaluateMeasures(dataSet: FeatureDataSet, measures: Array<out RelevanceMeasure>): List<DoubleArray> { return evaluateMeasuresHelper(dataSet, measures) } } sealed class DataSetFilter { protected val logger: Logger = LoggerFactory.getLogger(this.javaClass) abstract fun filterDataSet(original: FeatureDataSet, measureCosts: Point, measures: Array<out RelevanceMeasure>): FeatureDataSet } class PercentFilter(private val percents: Int) : DataSetFilter() { override fun filterDataSet(original: FeatureDataSet, measureCosts: Point, measures: Array<out RelevanceMeasure>): FeatureDataSet { val evaluatedFeatures = DataSetEvaluator().evaluateFeatures(original, measureCosts, measures).toList() val featureToSelect = (evaluatedFeatures.size.toDouble() * percents / 100).toInt() val filteredFeatures = ArrayList<Feature>(evaluatedFeatures.subList(0, featureToSelect)) return FeatureDataSet(filteredFeatures, original.classes, original.name) } } class PreferredSizeFilter(val preferredSize: Int) : DataSetFilter() { init { logger.info("Initialized dataset filter with preferred size {}", preferredSize) } override fun filterDataSet(original: FeatureDataSet, measureCosts: Point, measures: Array<out RelevanceMeasure>): FeatureDataSet { val filteredFeatures = DataSetEvaluator().evaluateFeatures(original, measureCosts, measures) .take(preferredSize) return FeatureDataSet(filteredFeatures.toList(), original.classes, original.name) } } class WyrdCuttingRuleFilter : DataSetFilter() { override fun filterDataSet(original: FeatureDataSet, measureCosts: Point, measures: Array<out RelevanceMeasure>): FeatureDataSet { val filteredFeatures = DataSetEvaluator().evaluateFeatures(original, measureCosts, measures) val mean = filteredFeatures .map({ it.measure }) .average() val std = Math.sqrt( filteredFeatures .map({ it.measure }) .map { x -> Math.pow(x - mean, 2.0) } .average() ) val inRange = filteredFeatures .filter { f -> isInRange(f, mean, std) } .count() val result = filteredFeatures.toList().subList(0, inRange) return FeatureDataSet(result, original.classes, original.name) } private fun isInRange(feature: EvaluatedFeature, mean: Double, std: Double): Boolean { return feature.measure > mean - std && feature.measure < mean + std } }
0
Kotlin
0
1
2a3300ea32dda160d400258f2400c03ad84cb713
5,115
parallel-feature-selection
MIT License
src/main/kotlin/g0501_0600/s0502_ipo/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0502_ipo // #Hard #Array #Sorting #Greedy #Heap_Priority_Queue // #2023_01_06_Time_799_ms_(54.55%)_Space_88.5_MB_(9.09%) import java.util.PriorityQueue class Solution { inner class Data(var profit: Int, var capital: Int) // max heap for profit var profitMaxHeap = PriorityQueue<Data> { d1, d2 -> -1 * Integer.compare( d1.profit, d2.profit ) } // min heap for capital var capitalMinHeap = PriorityQueue<Data> { d1, d2 -> Integer.compare(d1.capital, d2.capital) } fun findMaximizedCapital(k: Int, w: Int, profits: IntArray, capital: IntArray): Int { init(profits, capital) var maxCapital = w var currentCapital = w for (i in 0 until k) { // first fetch all tasks you can do with current capital and add those in profit max heap while (capitalMinHeap.isNotEmpty() && currentCapital >= capitalMinHeap.peek().capital) { profitMaxHeap.add(capitalMinHeap.poll()) } // if profit max heap is empty we can do nothing so break if (profitMaxHeap.isEmpty()) break // add profit to current capital and update maxCapital currentCapital += profitMaxHeap.poll().profit maxCapital = Math.max(maxCapital, currentCapital) } return maxCapital } private fun init(profits: IntArray, capital: IntArray) { for (i in profits.indices) { capitalMinHeap.add(Data(profits[i], capital[i])) } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,562
LeetCode-in-Kotlin
MIT License
Special_factorials/Kotlin/src/main/kotlin/Special.kt
ncoe
108,064,933
false
{"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409}
import java.math.BigInteger import java.util.function.Function /* n! = 1 * 2 * 3 * ... * n */ fun factorial(n: Int): BigInteger { val bn = BigInteger.valueOf(n.toLong()) var result = BigInteger.ONE var i = BigInteger.TWO while (i <= bn) { result *= i++ } return result } /* if(n!) = n */ fun inverseFactorial(f: BigInteger): Int { if (f == BigInteger.ONE) { return 0 } var p = BigInteger.ONE var i = BigInteger.ONE while (p < f) { p *= i++ } if (p == f) { return i.toInt() - 1 } return -1 } /* sf(n) = 1! * 2! * 3! * ... . n! */ fun superFactorial(n: Int): BigInteger { var result = BigInteger.ONE for (i in 1..n) { result *= factorial(i) } return result } /* H(n) = 1^1 * 2^2 * 3^3 * ... * n^n */ fun hyperFactorial(n: Int): BigInteger { var result = BigInteger.ONE for (i in 1..n) { val bi = BigInteger.valueOf(i.toLong()) result *= bi.pow(i) } return result } /* af(n) = -1^(n-1)*1! + -1^(n-2)*2! + ... + -1^(0)*n! */ fun alternatingFactorial(n: Int): BigInteger { var result = BigInteger.ZERO for (i in 1..n) { if ((n - i) % 2 == 0) { result += factorial(i) } else { result -= factorial(i) } } return result } /* n$ = n ^ (n - 1) ^ ... ^ (2) ^ 1 */ fun exponentialFactorial(n: Int): BigInteger { var result = BigInteger.ZERO for (i in 1..n) { result = BigInteger.valueOf(i.toLong()).pow(result.toInt()) } return result } fun testFactorial(count: Int, f: Function<Int, BigInteger>, name: String) { println("First $count $name:") for (i in 0 until count) { print("${f.apply(i)} ") } println() } fun testInverse(f: Long) { val n = inverseFactorial(BigInteger.valueOf(f)) if (n < 0) { println("rf($f) = No Solution") } else { println("rf($f) = $n") } } fun main() { testFactorial(10, ::superFactorial, "super factorials") println() testFactorial(10, ::hyperFactorial, "hyper factorials") println() testFactorial(10, ::alternatingFactorial, "alternating factorials") println() testFactorial(5, ::exponentialFactorial, "exponential factorials") println() testInverse(1) testInverse(2) testInverse(6) testInverse(24) testInverse(120) testInverse(720) testInverse(5040) testInverse(40320) testInverse(362880) testInverse(3628800) testInverse(119) }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
2,529
rosetta
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[46]全排列.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.collections.ArrayList //给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。 // // // // 示例 1: // // //输入:nums = [1,2,3] //输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] // // // 示例 2: // // //输入:nums = [0,1] //输出:[[0,1],[1,0]] // // // 示例 3: // // //输入:nums = [1] //输出:[[1]] // // // // // 提示: // // // 1 <= nums.length <= 6 // -10 <= nums[i] <= 10 // nums 中的所有整数 互不相同 // // Related Topics 数组 回溯算法 // 👍 1423 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun permute(nums: IntArray): List<List<Int>> { //dfs 递归回溯 var res = ArrayList<ArrayList<Int>>() //使用一个boolean 类型数组来记录是否使用过一个数字 var isUse = BooleanArray(nums.size) dfs(0,isUse,nums.size,nums,LinkedList<Int>(),res) return res } private fun dfs(index: Int, use: BooleanArray, size: Int, nums: IntArray, stack: LinkedList<Int>, res: java.util.ArrayList<java.util.ArrayList<Int>>) { //递归结束条件 if(index == size){ res.add(ArrayList(stack)) } //逻辑处理 进入下层循环 for (i in nums.indices){ //如果已经使用 跳过 if (use[i]) continue //标记已经使用 use[i] = true //保存当前数 stack.addLast(nums[i]) dfs(index+1,use,size,nums,stack,res) //不符合 回溯 use[i] = false stack.removeLast() } //数据reverse } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,843
MyLeetCode
Apache License 2.0
src/Day06.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
private fun isUniqueMarker(s: String): Boolean { for (i in s.indices) { if (s.indexOf(s[i], i + 1) != -1) { return false } } return true } private fun endIndexOfMarker(input: List<String>, markerLength: Int): Int { val data = input[0] for (i in data.indices) { if (isUniqueMarker(data.substring(i, i + markerLength))) { return i + markerLength } } throw IllegalArgumentException("There is no start marker") } private fun part1(input: List<String>): Int { return endIndexOfMarker(input, 4) } private fun part2(input: List<String>): Int { return endIndexOfMarker(input, 14) } fun main() { val input = readInput("Day06") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
837
advent-of-code-2022
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/MissingNumber.kt
faniabdullah
382,893,751
false
null
//Given an array nums containing n distinct numbers in the range [0, n], return //the only number in the range that is missing from the array. // // // Example 1: // // //Input: nums = [3,0,1] //Output: 2 //Explanation: n = 3 since there are 3 numbers, so all numbers are in the range //[0,3]. 2 is the missing number in the range since it does not appear in nums. // // // Example 2: // // //Input: nums = [0,1] //Output: 2 //Explanation: n = 2 since there are 2 numbers, so all numbers are in the range //[0,2]. 2 is the missing number in the range since it does not appear in nums. // // // Example 3: // // //Input: nums = [9,6,4,2,3,5,7,0,1] //Output: 8 //Explanation: n = 9 since there are 9 numbers, so all numbers are in the range //[0,9]. 8 is the missing number in the range since it does not appear in nums. // // // Example 4: // // //Input: nums = [0] //Output: 1 //Explanation: n = 1 since there is 1 number, so all numbers are in the range [0 //,1]. 1 is the missing number in the range since it does not appear in nums. // // // // Constraints: // // // n == nums.length // 1 <= n <= 10⁴ // 0 <= nums[i] <= n // All the numbers of nums are unique. // // // // Follow up: Could you implement a solution using only O(1) extra space //complexity and O(n) runtime complexity? // Related Topics Array Hash Table Math Bit Manipulation Sorting 👍 4009 👎 2686 // package leetcodeProblem.leetcode.editor.en class MissingNumber { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun missingNumber(nums: IntArray): Int { val n = nums.size val total = n * (n + 1) / 2 var sum = 0 for (num in nums) { sum += num } return total - sum } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,026
dsa-kotlin
MIT License
src/main/kotlin/com/sk/topicWise/trie/211. Add and Search Word - Data structure design.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.trie class WordDictionary() { private class TrieNode { var wordEnd = false var children = HashMap<Char, TrieNode>() } private var root = TrieNode() fun addWord(word: String) { var cur = root for (ch in word) { if (!cur.children.containsKey(ch)) cur.children[ch] = TrieNode() cur = cur.children[ch]!! } cur.wordEnd = true } fun search(word: String): Boolean { return search(word, 0, root) } private fun search(word: String, k: Int, trieNode: TrieNode): Boolean { var cur = trieNode for (i in k..word.lastIndex) { val ch = word[i] if (ch == '.') { for (node in cur.children.values) { if (search(word, i + 1, node)) return true } return false } if (!cur.children.containsKey(ch)) return false cur = cur.children[ch]!! } return cur.wordEnd } } //###################################################################### // //###################################################################### class WordDictionary211_2() { private val root = TrieNode() fun addWord(word: String) { var cur = root for (ch in word) { val idx = ch - 'a' if (cur.children[idx] == null) cur.children[idx] = TrieNode() cur = cur.children[idx]!! } cur.wordEnd = true } fun search(word: String): Boolean { return find(word, 0, root) } private fun find(word: String, k: Int, node: TrieNode): Boolean { var cur = node for (i in k..word.lastIndex) { val ch = word[i] if (ch == '.') { for (n in cur.children) { if (n == null) continue if (find(word, i + 1, n)) return true } return false } val idx = ch - 'a' if (cur.children[idx] == null) return false cur = cur.children[idx]!! } return cur.wordEnd } private class TrieNode { val children = arrayOfNulls<TrieNode>(26) var wordEnd = false } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
2,297
leetcode-kotlin
Apache License 2.0
advent-of-code-2021/src/code/day13a/Main.kt
Conor-Moran
288,265,415
false
{"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733}
package code.day13a import java.io.File import java.lang.Integer.max import kotlin.math.min fun main() { doIt("Day 13a Part 2: Test Input", "src/code/day13a/test.input", part2) doIt("Day 13a Part 2: Real Input", "src/code/day13a/part1.input", part2); } fun doIt(msg: String, input: String, calc: (nums: List<String>) -> String) { val lines = arrayListOf<String>() File(input).forEachLine { lines.add(it) } println(String.format("%s: Ans: %s", msg , calc(lines))) } val part2: (List<String>) -> String = { lines -> val input = parse(lines) val points = mutableSetOf<Point>() points.addAll(input.points) for (fold in input.folds) { fold(points, fold) } toString(grid(points)) } fun grid(points: Set<Point>): Grid { var maxX = Int.MIN_VALUE var maxY = Int.MIN_VALUE for (point in points) { maxX = max(maxX, point.x) maxY = max(maxY, point.y) } val g = Array(maxX + 1) { Array<Char>(maxY + 1) { ' ' } } for (point in points) { g[point.x][point.y] = '#' } return g } fun fold(points: MutableSet<Point>, fold: Fold) { return when (fold.axis) { 'x' -> foldLeft(points, fold.pos) else -> foldUp(points, fold.pos) } } fun foldUp(points: MutableSet<Point>, splitPos: Int) { val shiftedPoints = mutableSetOf<Point>() for(point in points) { if (point.y > splitPos) { shiftedPoints.add(point) } } points.removeAll(shiftedPoints) for (point in shiftedPoints) { point.y = splitPos - (point.y - splitPos) if (!points.contains(point)) { points.add(point) } } } fun foldLeft(points: MutableSet<Point>, splitPos: Int) { val shiftedPoints = mutableSetOf<Point>() for(point in points) { if (point.x > splitPos) { shiftedPoints.add(point) } } points.removeAll(shiftedPoints) for (point in shiftedPoints) { point.x = splitPos - (point.x - splitPos) if (!points.contains(point)) { points.add(point) } } } private fun toString(grid: Grid): String { val sb = StringBuilder() sb.append(System.lineSeparator()) for(j in grid[0].indices) { for (i in grid.indices) { sb.append(grid[i][j]) } sb.append(System.lineSeparator()) } sb.append(System.lineSeparator()) return sb.toString() } val parse: (List<String>) -> Input = { lines -> val points = mutableListOf<Point>() val folds = mutableListOf<Fold>() lines.filter { !it.isNullOrBlank() }.forEach { if (!it.startsWith("fold along")) { val coords = it.split(",").map { v -> v.toInt() } val point = Point(coords[0], coords[1]) points.add(point) } else { val rawFolds = it.substringAfter("fold along ").split("=") folds.add(Fold(rawFolds[0][0], rawFolds[1].toInt())) } } Input(points.toTypedArray(), folds.toTypedArray()) } typealias Grid = Array<Array<Char>> data class Point(var x: Int, var y: Int) class Fold(val axis: Char, val pos: Int) class Input(val points: Array<Point>, val folds: Array<Fold>)
0
Kotlin
0
0
ec8bcc6257a171afb2ff3a732704b3e7768483be
3,218
misc-dev
MIT License
src/main/kotlin/Excercise13.kt
underwindfall
433,989,850
false
{"Kotlin": 55774}
private fun part1() { val input = getInputAsTest("13") var a = input .takeWhile { it.isNotEmpty() } .map { it.split(",").map { it.toInt() }.let { (x, y) -> Point(x, y) } } .toSet() val i = input.indexOf("") + 1 val s = input[i] val pr = "fold along " check(s.startsWith(pr)) val ss = s.substring(pr.length) val z = ss.substringAfter('=').toInt() a = when (ss[0]) { 'x' -> { a .map { p -> if (p.x > z) { Point(2 * z - p.x, p.y) } else p } .toSet() } 'y' -> { a.map { p -> if (p.y > z) Point(p.x, p.y - z) else p }.toSet() } else -> error(ss) } println("Part1 ${a.size}") } private fun part2() { val input = getInputAsTest("13") var a = input .takeWhile { it.isNotEmpty() } .map { it.split(",").map { it.toInt() }.let { (x, y) -> Point(x, y) } } .toSet() for (i in input.indexOf("") + 1 until input.size) { val s = input[i] val pr = "fold along " check(s.startsWith(pr)) val ss = s.substring(pr.length) val z = ss.substringAfter('=').toInt() when (ss[0]) { 'x' -> { a = a .map { p -> if (p.x > z) { Point(2 * z - p.x, p.y) } else p } .toSet() } 'y' -> { a = a .map { p -> if (p.y > z) { Point(p.x, 2 * z - p.y) } else p } .toSet() } else -> error(ss) } } println("Part2 ${a.size}") val b = Array(6) { CharArray(40) { '.' } } for (p in a) { b[p.y][p.x] = '█' } for (c in b) println(c.concatToString()) } data class Point(val x: Int, val y: Int) fun main() { part1() part2() }
0
Kotlin
0
0
4fbee48352577f3356e9b9b57d215298cdfca1ed
1,847
advent-of-code-2021
MIT License
src/main/kotlin/dev/siller/aoc2023/Day13.kt
chearius
725,594,554
false
{"Kotlin": 50795, "Shell": 299}
package dev.siller.aoc2023 import kotlin.math.min data object Day13 : AocDayTask<UInt, UInt>( day = 13, exampleInput = """ |#.##..##. |..#.##.#. |##......# |##......# |..#.##.#. |..##..##. |#.#.##.#. | |#...##..# |#....#..# |..##..### |#####.##. |#####.##. |..##..### |#....#..# """.trimMargin(), expectedExampleOutputPart1 = 405u, expectedExampleOutputPart2 = 400u ) { private class AshRockPattern(lines: List<String>) { val rows = lines .map { line -> line.replace('#', '0').replace('.', '1').trimStart('0').toULong(2) } val columns = lines .first() .mapIndexed { x, _ -> lines.joinToString(separator = "") { line -> "${line[x]}" } } .map { line -> line.replace('#', '0').replace('.', '1').trimStart('0').toULong(2) } } override fun runPart1(input: List<String>): UInt = parsePatterns(input).sumOf { pattern -> (getMirrorLocation(pattern.rows) ?: 0u) * 100u + (getMirrorLocation(pattern.columns) ?: 0u) } override fun runPart2(input: List<String>): UInt = parsePatterns(input).sumOf { pattern -> (getMirrorLocation(pattern.rows, 1u) ?: 0u) * 100u + (getMirrorLocation(pattern.columns, 1u) ?: 0u) } private fun getMirrorLocation( list: List<ULong>, smudgeCount: UInt = 0u ): UInt? { var index: UInt? = null for (i in 0..<(list.size - 1)) { var count = 0u for (j in 0..<min(i + 1, list.size - i - 1)) { count += getNumberOfDifferentBits(list[i - j], list[i + j + 1]) if (count > smudgeCount) { break } } if (count == smudgeCount) { index = (i + 1).toUInt() break } } return index } private fun getNumberOfDifferentBits( a: ULong, b: ULong ): UInt { var count = 0u var n = a xor b while (n > 0uL) { count += (n and 1uL).toUInt() n = n shr 1 } return count } private fun parsePatterns(input: List<String>): MutableList<AshRockPattern> { var inputToBeProcessed = input val patterns = mutableListOf<AshRockPattern>() while (inputToBeProcessed.isNotEmpty()) { patterns += AshRockPattern(inputToBeProcessed.takeWhile { it.isNotBlank() }) inputToBeProcessed = inputToBeProcessed.dropWhile { it.isNotBlank() }.drop(1) } return patterns } }
0
Kotlin
0
0
fab1dd509607eab3c66576e3459df0c4f0f2fd94
2,900
advent-of-code-2023
MIT License
src/net/sheltem/aoc/y2023/Day22.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 import net.sheltem.common.mapParallel suspend fun main() { Day22().run() } class Day22 : Day<Long>(5, 7) { override suspend fun part1(input: List<String>): Long = input.map { it.toBrick() }.settle().canDisintegrate().count().toLong() override suspend fun part2(input: List<String>): Long = input.map { it.toBrick() }.settle().disintegrate().sum() } private suspend fun List<Brick>.disintegrate(): List<Long> = mapParallel { disBrick -> val stack = this.toMutableList() val removedBricks = mutableListOf(disBrick) stack.remove(disBrick) do { val noSupport = stack.filter { it.allSupportsIn(removedBricks) } stack.removeAll(noSupport) removedBricks.addAll(noSupport) } while (noSupport.isNotEmpty()) removedBricks.size - 1L } private fun List<Brick>.settle(): List<Brick> { val movedBricks = mutableListOf<Brick>() sortedBy { it.z.first } .map { brick -> var currentBrick = brick var supported = false while (!supported) { val supportingBricks = movedBricks.filter { currentBrick.under(it) } supported = supportingBricks.isNotEmpty() || currentBrick.z.first == 0 if (supported) { supportingBricks.forEach { it.connect(currentBrick) } movedBricks += currentBrick } else { val nextZ = movedBricks.filter { it.z.last < currentBrick.z.first - 1 }.maxOfOrNull { it.z.last }?.let { it + 1 } ?: 0 val height = currentBrick.z.last - currentBrick.z.first currentBrick = currentBrick.copy(z = nextZ..(nextZ + height)) } } } return movedBricks } private fun List<Brick>.canDisintegrate() = filter { !it.supports.any { supportedBricks -> supportedBricks.supportedBy.size == 1 } } private fun String.toBrick(): Brick = split("~") .map { it.split(",").map { coord -> coord.toInt() } } .let { (left, right) -> Brick(left[0]..right[0], left[1]..right[1], left[2]..right[2]) } private data class Brick(val x: IntRange, val y: IntRange, val z: IntRange) { val supports = mutableListOf<Brick>() val supportedBy = mutableListOf<Brick>() fun putOnTop(other: Brick) { supports.add(other) } fun supported(other: Brick) { supportedBy.add(other) } fun connect(other: Brick) { this.putOnTop(other) other.supported(this) } fun under(other: Brick) = other.x.any{ this.x.contains(it) } && other.y.any { this.y.contains(it) } && other.z.last == this.z.first - 1 fun allSupportsIn(bricks: List<Brick>) = supportedBy.isNotEmpty() && supportedBy.all { support -> bricks.contains(support) } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,877
aoc
Apache License 2.0
src/day14/Day14.kt
pocmo
433,766,909
false
{"Kotlin": 134886}
package day14 import java.io.File fun readFile(fileName: String): Pair<String, Map<String, String>> { return readFromString(File(fileName) .readText() .trim()) } fun Map<String, String>.toCharacterMap(): Map<String, Char> { return mapValues { (_, character) -> character[0] } } fun performInsertion(template: String, map: Map<String, String>): String { val insertions = mutableListOf<String>() val groups = template.windowed(size = 2, step = 1, partialWindows = false) groups.forEach { group -> val insertion = map[group] ?: throw IllegalStateException("No mapping for $group") insertions.add(insertion) } return buildString { insertions.forEachIndexed { index, insertion -> append(template[index]) append(insertion) } append(template.last()) } } fun createGroupCount(template: String): Map<String, Long> { val map = mutableMapOf<String, Long>() template.windowed(size = 2, step = 1, partialWindows = false).forEach { group -> map.count(group, 1) } return map } fun MutableMap<Char, Long>.count(character: Char, count: Long) { val value = getOrDefault(character, 0L) val updated = value + count if (updated < value) { throw IllegalStateException("Oops, we failed") } put(character, updated) } fun MutableMap<String, Long>.count(group: String, count: Long = 1L) { val value = getOrDefault(group, 0L) val updated = value + count if (updated < value) { throw IllegalStateException("Oops, we failed") } put(group, updated) } fun Map<String, Char>.toInsertionMap(): Map<String, Pair<String, String>> { return mapValues { (group, character) -> Pair( "${group[0]}$character", "$character${group[1]}" ) } } fun countAllTheThings( template: String, times: Int, characterMap: Map<String, Char>, insertionMap: Map<String, Pair<String, String>> ): Map<Char, Long> { val countCharacters = mutableMapOf<Char, Long>() // B -> 0 var groupCount = createGroupCount(template) // AB -> 0 repeat(times) { val updatedGroupCount = mutableMapOf<String, Long>() groupCount.forEach { (group, count) -> val insertion = characterMap[group] ?: throw IllegalStateException("No character mapping for group: $group") countCharacters.count(insertion, count) val (first, second) = insertionMap[group] ?: throw IllegalStateException("No group mapping for group: $group") updatedGroupCount.count(first, count) updatedGroupCount.count(second, count) } groupCount = updatedGroupCount } template.toCharArray().forEach { character -> countCharacters.count(character, 1) } return countCharacters } fun countQuantities(input: String): Map<Char, Int> { return input.toCharArray().groupBy { it } .mapValues { (_, list) -> list.size } } fun Map<Char, Int>.max(): Pair<Char, Int> { return maxByOrNull { (_, count) -> count}!!.toPair() } fun Map<Char, Int>.min(): Pair<Char, Int> { return minByOrNull { (_, count) -> count}!!.toPair() } fun Map<Char, Long>.maxLong(): Pair<Char, Long> { return maxByOrNull { (_, count) -> count}!!.toPair() } fun Map<Char, Long>.minLong(): Pair<Char, Long> { return minByOrNull { (_, count) -> count}!!.toPair() } fun readFromString(input: String): Pair<String, Map<String, String>> { val lines = input.lines() val template = lines[0] val map = mutableMapOf<String, String>() for (line in lines.drop(2)) { val (from, to) = line.split(" -> ") map[from] = to } return Pair(template, map) } fun part1() { var (template, map) = readFile("day14.txt") repeat(10) { template = performInsertion(template, map) } val quantities = countQuantities(template) val (minCharacter, minValue) = quantities.min() val (maxCharacter, maxValue) = quantities.max() println("Min: $minCharacter => $minValue") println("Max: $maxCharacter => $maxValue") val result = maxValue - minValue println("Result: $result") } fun part2() { val (template, map) = readFile("day14.txt") val characterMap = map.toCharacterMap() val insertionMap = characterMap.toInsertionMap() val countMap = countAllTheThings( template, 40, characterMap, insertionMap ) val (maxChar, maxCount) = countMap.maxLong() val (minChar, minCount) = countMap.minLong() println("Max $maxChar = $maxCount") println("Min $minChar = $minCount") println("Result = ${maxCount - minCount}") } fun main() { println(">> PART 1") part1() println(">> PART 2") part2() }
0
Kotlin
1
2
73bbb6a41229e5863e52388a19108041339a864e
4,844
AdventOfCode2021
Apache License 2.0
leetcode2/src/leetcode/closestDivisors.kt
hewking
68,515,222
false
null
package leetcode /** * @Classname closestDivisors * @Description TODO * @Date 2020-05-16 13:47 * @Created by jianhao * 给你一个整数 num,请你找出同时满足下面全部要求的两个整数: 两数乘积等于 num + 1 或 num + 2 以绝对差进行度量,两数大小最接近 你可以按任意顺序返回这两个整数。 示例 1: 输入:num = 8 输出:[3,3] 解释:对于 num + 1 = 9,最接近的两个因数是 3 & 3;对于 num + 2 = 10, 最接近的两个因数是 2 & 5,因此返回 3 & 3 。 示例 2: 输入:num = 123 输出:[5,25] 示例 3: 输入:num = 999 输出:[40,25] */ object ClosestDivisors { class Solution { fun closestDivisors(num: Int): IntArray { val first = num + 1 val second = num + 2 // 1. 如果从num 开根号开始,如果根号9 == 3 ,那么两个数就最近 // 但是不是自然数,不符合需求 val a_ = findMinDistance(first); val b_ = findMinDistance(second) return if (a_[0] - a_[1] > b_[0] - b_[1]) { b_ } else a_ } fun findMinDistance(num:Int): IntArray { var a = Math.sqrt(num.toDouble()) var a_ = a.toInt() for (i in a_ downTo 0) { val b = num.div(a_) if (b * a_ == num) { return intArrayOf(a_,b) } } return intArrayOf(-1,Int.MAX_VALUE) } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,535
leetcode
MIT License
src/main/kotlin/ru/timakden/aoc/year2022/Day17.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import ru.timakden.aoc.util.Point import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 17: Pyroclastic Flow](https://adventofcode.com/2022/day/17). */ object Day17 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day17").single() println("Part One: ${part1(input)}") println("Part Two: ${part2(input, 1000000000000L)}") } } fun part1(input: String): Int { val wind = windIterator(input) val shapes = shapeIterator() val occupied = mutableSetOf<Point>() repeat(2022) { val currentTop = occupied.top var current = shapes.next().relTo(currentTop).tryMove(occupied, Point(2, 0)) while (true) { current = current.tryMove(occupied, windVector(wind)) val tryFall = current.tryMove(occupied, Point(0, -1)) if (tryFall == current) { occupied.addAll(current.points) break } else current = tryFall } } return occupied.maxOf(Point::y) + 1 } fun part2(input: String, lastShape: Long): Long { val wind = windIterator(input) val shapes = shapeIterator() val occupied = hashSetOf<Point>() val diffs = StringBuilder() for (i in 0..<lastShape) { val currentTop = occupied.top var cur = shapes.next().relTo(currentTop).tryMove(occupied, Point(2, 0)) while (true) { val windVector = windVector(wind) cur = cur.tryMove(occupied, windVector) val tryFall = cur.tryMove(occupied, Point(0, -1)) if (tryFall == cur) { occupied.addAll(cur.points) diffs.append(occupied.top - currentTop) val periodicSequenceSearchLength = 20 if (diffs.length > periodicSequenceSearchLength * 2) { val repetitions = diffs.windowed(periodicSequenceSearchLength).count { it == diffs.takeLast(periodicSequenceSearchLength) } if (repetitions > 1) { val (start, period) = diffs.asSequence().withIndex().windowed(periodicSequenceSearchLength) .map { val foundIndex = diffs.indexOf( it.map(IndexedValue<Char>::value).joinToString(""), it.last().index ) it.first().index to (foundIndex - it.first().index) }.firstOrNull { it.second >= 0 } ?: break val periodicSequence = diffs.substring(start..<start + period) val numberOfRepetitions = (lastShape - start) / period val repetitionIncrement = periodicSequence.map(Char::digitToInt).sum() val startIncrement = diffs.substring(0..<start).map(Char::digitToInt).sum() val remainder = lastShape - (start - 1) - (numberOfRepetitions * period) - 1 val tailIncrement = periodicSequence.take(remainder.toInt()).map(Char::digitToInt).sum() return startIncrement.toLong() + (numberOfRepetitions * repetitionIncrement) + tailIncrement } } break } else cur = tryFall } } return -1L } private fun windVector(wind: Iterator<Char>) = when (wind.next()) { '>' -> Point(1, 0) '<' -> Point(-1, 0) else -> error("Unsupported wind direction") } private fun windIterator(input: String) = iterator { while (true) { yieldAll(input.toList()) } } private fun shapeIterator() = iterator { val x = buildList { add(Shape(0, 0, 1, 0, 2, 0, 3, 0)) add(Shape(1, 0, 0, 1, 1, 1, 2, 1, 1, 2)) add(Shape(0, 0, 1, 0, 2, 0, 2, 1, 2, 2)) add(Shape(0, 0, 0, 1, 0, 2, 0, 3)) add(Shape(0, 0, 1, 0, 0, 1, 1, 1)) } while (true) { yieldAll(x) } } private val Set<Point>.top get() = if (isEmpty()) -1 else maxOf(Point::y) data class Shape(val points: List<Point>) { constructor(vararg points: Int) : this(points.asSequence().chunked(2) { (a, b) -> Point(a, b) }.toList()) fun relTo(currentTop: Int) = Shape(points.map { it.copy(y = currentTop + it.y + 4) }) fun tryMove(occupied: Set<Point>, vector: Point): Shape { val nextPos = points.map { it + vector } for (point in nextPos) { if (occupied.contains(point) || point.x < 0 || point.x > 6 || point.y < 0) return this } return Shape(nextPos) } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
5,178
advent-of-code
MIT License
src/main/kotlin/g2301_2400/s2382_maximum_segment_sum_after_removals/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2382_maximum_segment_sum_after_removals // #Hard #Array #Prefix_Sum #Union_Find #Ordered_Set // #2023_07_02_Time_857_ms_(50.00%)_Space_60_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { private class UF(n: Int) { var root: IntArray var sum: LongArray init { this.root = IntArray(n) this.root.fill(-1) sum = LongArray(n) } fun insert(x: Int, value: Int) { if (root[x] != -1 || sum[x] != 0L) { return } this.root[x] = x sum[x] = value.toLong() } fun find(x: Int): Int { var x = x while (root[x] != x) { val fa = root[x] val ga = root[fa] root[x] = ga x = fa } return x } fun union(x: Int, y: Int) { val rx = find(x) val ry = find(y) if (x == y) { return } root[rx] = ry sum[ry] += sum[rx] } fun has(x: Int): Boolean { return root[x] != -1 || sum[x] != 0L } } fun maximumSegmentSum(nums: IntArray, removeQueries: IntArray): LongArray { val n = removeQueries.size val ret = LongArray(n) var max = 0L val uf = UF(n) for (i in n - 1 downTo 0) { val u = removeQueries[i] uf.insert(u, nums[u]) var v = u - 1 while (v <= u + 1) { if (v >= 0 && v < n && uf.has(v)) { uf.union(v, u) } v += 2 } ret[i] = max val ru = uf.find(u) max = Math.max(max, uf.sum[ru]) } return ret } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,847
LeetCode-in-Kotlin
MIT License
src/solutionsForBookCrackingTheCodingInterview/linkedLists/MathActions.kt
mrkostua
120,207,236
false
null
package solutionsForBookCrackingTheCodingInterview.linkedLists /** * @author <NAME> * @created on 3/20/2018 * "Cracking the Coding Interview" task 2.4 */ /** * Task : * You have two numbers represented by a linked list, where each node contains a single * digit. The digits are stored in reverse order, such that the 1’s digit is at the head of * the list. Write a function that adds the two numbers and returns the sum as a linked * list. */ /** * recursive method for adding, * pros - bby using linkedList we can represent big numbers with low memory usage. * nodes stored in reverse order so the head is points to last digit (smallest as 002) */ fun addNumbers(firstNumber: LinkedList2.Node<Int>, secondNumber: LinkedList2.Node<Int>, lastAddNumber: Int = 0) { val toBiggerNumber: Int val sum: Int = firstNumber.data + secondNumber.data + lastAddNumber if (sum >= 10) { toBiggerNumber = 1 firstNumber.data = sum - 10 } else { toBiggerNumber = 0 firstNumber.data = firstNumber.data + secondNumber.data } if (firstNumber.next != null || secondNumber.next != null) { addNumbers(if (firstNumber.next == null) { firstNumber.next = LinkedList2.Node(0, null) firstNumber.next } else firstNumber.next, if (secondNumber.next == null) { secondNumber.next = LinkedList2.Node(0, null) secondNumber } else secondNumber.next, toBiggerNumber) } else if (toBiggerNumber > 0) { firstNumber.next = LinkedList2.Node(1, null) } } private fun <T> reverseList(head: LinkedList2.Node<T>): LinkedList2<T> { val reverseList = LinkedList2<T>() var tmp: LinkedList2.Node<T>? = head while (tmp != null) { reverseList.addFirst(tmp.data) tmp = tmp.next } return reverseList } fun main(args: Array<String>) { val n1 = LinkedList2<Int>() val n2 = LinkedList2<Int>() n1.addFirst(5) n1.addLast(6) n1.addLast(9) n2.addFirst(9) n2.addLast(5) n2.addLast(9) println("initial data: \nfirst number : " + reverseList(n1.head).toString() + " second number : " + reverseList(n2.head).toString()) addNumbers(n1.head, n2.head) println("\nResult of adding 2 numbers : " + reverseList(n1.head).toString()) }
0
Kotlin
0
0
bfb7124e93e485bee5ee8c4b69bf9c0a0a532ecf
2,385
Cracking-the-Coding-Interview-solutions
MIT License
src/Utils.kt
MisterTeatime
561,848,263
false
{"Kotlin": 37980}
import java.io.File import java.math.BigInteger import java.security.MessageDigest import kotlin.math.absoluteValue /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt").readLines() /** * Converts string to md5 hash. */ fun String.md5(): String = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16).padStart(32, '0') typealias Graph = Map<String, List<String>> typealias Path = List<String> typealias Fold = Pair<Char, Int> data class Point2D (var x: Int, var y: Int) { operator fun plus(inc: Point2D) = Point2D(x + inc.x, y + inc.y) operator fun minus(inc: Point2D) = Point2D(x - inc.x, y - inc.y) fun neighbors4(): List<Point2D> { val neighborPoints = listOf(Point2D(1,0), Point2D(0,1), Point2D(-1, 0), Point2D(0,-1)) return neighborPoints.map { this + it }.sortedWith(Point2DComparator()) } fun neighbors8(): List<Point2D> { val neighborPoints = listOf( Point2D(1,0), Point2D(1,1), Point2D(0,1), Point2D(-1,1), Point2D(-1,0), Point2D(-1,-1), Point2D(0,-1), Point2D(1,-1) ) return neighborPoints.map { this + it }.sortedWith(Point2DComparator()) } fun neighbors4AndSelf(): List<Point2D> { val neighborPoints = neighbors4().toMutableList() neighborPoints.add(this) return neighborPoints.sortedWith(Point2DComparator()) } fun neighbors8AndSelf(): List<Point2D> { val neighborPoints = neighbors8().toMutableList() neighborPoints.add(this) return neighborPoints.sortedWith(Point2DComparator()) } fun distanceTo(other: Point2D) = (this.x - other.x).absoluteValue + (this.y - other.y).absoluteValue class Point2DComparator: Comparator<Point2D> { override fun compare(p0: Point2D?, p1: Point2D?): Int { return if (p0 == null || p1 == null) 0 else { when { (p0.y > p1.y) -> 1 (p0.y < p1.y) -> -1 else -> { when { (p0.x > p1.x) -> 1 (p0.x < p1.x) -> -1 else -> 0 } } } } } } } class Line(coords: List<String>) { val start: Point2D val end: Point2D init { val startPoint = coords[0].split(",") val endPoint = coords[1].split(",") this.start = Point2D(startPoint[0].toInt(), startPoint[1].toInt()) this.end = Point2D(endPoint[0].toInt(), endPoint[1].toInt()) } fun isHorizontal() = start.y == end.y fun isVertical() = start.x == end.x fun contains(point: Point2D) = point.y == getYAt(point.x) fun getYAt(x: Int) = ((end.y - start.y)/(end.x - start.x)) * (x - start.x) + start.y fun getAllIntegerPoints(): List<Point2D> { return when { isHorizontal() -> { when { (start.x < end.x) -> IntRange(start.x, end.x).map{ p -> Point2D(p, start.y) } else -> IntRange(end.x, start.x).map{ p -> Point2D(p, start.y) } } } isVertical() -> { when { (start.y < end.y) -> IntRange(start.y, end.y).map{ p -> Point2D(start.x, p) } else -> IntRange(end.y, start.y).map { p -> Point2D(start.x, p) } } } else -> { when { (start.x < end.x) -> IntRange(start.x, end.x).map{ p -> Point2D(p, getYAt(p)) } else -> IntRange(end.x, start.x).map{ p -> Point2D(p, getYAt(p)) } } } } } override fun toString(): String { return "(${start.x}, ${start.y}) -> (${end.x}, ${end.y})" } } class MyStack<E>(vararg items: E): Collection<E> { private val elements = items.toMutableList() fun push(element: E) = elements.add(element) fun peek(): E = elements.last() fun pop(): E = elements.removeAt(elements.size-1) override fun isEmpty() = elements.isEmpty() override fun contains(element: E) = elements.contains(element) override fun containsAll(elements: Collection<E>) = elements.containsAll(elements) override fun toString() = "Stack(${elements.joinToString()})" override fun iterator() = elements.iterator() override val size: Int get() = elements.size } data class Area<T>(var points: List<MutableList<T>>) { fun at(p: Point2D): T? { return points.getOrElse(p.y) { listOf() }.getOrNull(p.x) } fun setValue(p: Point2D, v: T) { if (at(p) != null) points[p.y][p.x] = v } companion object Factory { fun toIntArea(input: List<String>): Area<Int> { return Area(input.map { it.map { ch -> ch.toString().toInt() }.toMutableList() }) } fun toBinaryArea(input: List<String>, one: Char, zero: Char): Area<Int> { return Area(input.map { it.map { c -> when (c) { one -> 1 zero -> 0 else -> 0 } }.toMutableList() }) } } } data class Point3D(val x: Int, val y: Int, val z: Int) { operator fun plus(inc: Point3D) = Point3D(x + inc.x, y + inc.y, z + inc.z) operator fun minus(inc: Point3D) = Point3D(x - inc.x, y - inc.y, z - inc.z) } fun <T> List<T>.partitionGroups(divider: T): List<List<T>> { var startIndex = 0 val result = mutableListOf<List<T>>() this.forEachIndexed { index, t -> if (t == divider) { result.add(this.subList(startIndex, index)) startIndex = index + 1 } } if (startIndex < this.size) result.add(this.subList(startIndex, this.size)) return result }
0
Kotlin
0
0
d684bd252a9c6e93106bdd8b6f95a45c9924aed6
6,040
AoC2022
Apache License 2.0
2021/src/main/kotlin/day25_imp.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Parser import utils.Solution import utils.Vec2i import utils.wrap fun main() { Day25Imp.run() } object Day25Imp : Solution<IntGrid>() { override val name = "day25" private const val EMPTY = 0 private const val EAST = 1 private const val SOUTH = 2 override val parser = Parser { input -> input .replace('.', '0') .replace('>', '1') .replace('v', '2') }.map { IntGrid.singleDigits(it) } override fun part1(input: IntGrid): Number? { val grid = input.toMutable() var steps = 0 val swaps = mutableSetOf<Pair<Vec2i, Vec2i>>() while (true) { var moves = 0 // move to east first.. for (x in 0 until grid.width) { for (y in 0 until grid.height) { val toX = (x + 1).wrap(grid.width) if (grid[x][y] == EAST && grid[toX][y] == EMPTY) { moves++ swaps.add(Vec2i(x, y) to Vec2i(toX, y)) } } } for (swap in swaps) { grid.swap(swap.first, swap.second) } swaps.clear() // ..then move to south for (x in 0 until grid.width) { for (y in 0 until grid.height) { val toY = (y + 1).wrap(grid.height) if (grid[x][y] == SOUTH && grid[x][toY] == EMPTY) { moves++ swaps.add(Vec2i(x, y) to Vec2i(x, toY)) } } } for (swap in swaps) { grid.swap(swap.first, swap.second) } swaps.clear() steps++ if (moves == 0) { break } } return steps } fun IntGrid.print() { for (y in 0 until height) { for (x in 0 until width) { print(when (this[x][y]) { EAST -> '>' SOUTH -> 'v' else -> '.' }) } println() } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,807
aoc_kotlin
MIT License
kotlin/graphs/spanningtree/SteinerTree.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.spanningtree object SteinerTree { fun minLengthSteinerTree(g: Array<IntArray>, verticesToConnect: IntArray): Int { val n = g.size val m = verticesToConnect.size if (m <= 1) return 0 for (k in 0 until n) for (i in 0 until n) for (j in 0 until n) g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]) val dp = Array(1 shl m) { IntArray(n) } for (i in 0 until m) for (j in 0 until n) dp[1 shl i][j] = g[verticesToConnect[i]][j] for (i in 1 until 1 shl m) { if (i - 1 and i != 0) { for (j in 0 until n) { dp[i][j] = Integer.MAX_VALUE / 2 var k: Int = i - 1 and i while (k > 0) { dp[i][j] = Math.min(dp[i][j], dp[k][j] + dp[i xor k][j]) k = k - 1 and i } } for (j in 0 until n) { for (k in 0 until n) { dp[i][j] = Math.min(dp[i][j], dp[i][k] + g[k][j]) } } } } return dp[(1 shl m) - 1][verticesToConnect[0]] } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,176
codelibrary
The Unlicense
Bootcamp_01/src/exercise2/src/main/kotlin/Exercise1.kt
Hasuk1
740,111,124
false
{"Kotlin": 120039}
import kotlin.math.PI import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.pow import kotlin.math.sqrt fun readZone(): Zone? { println("Enter zone parameters:") val input = readLine() ?: return null val parts = input.split(" ") return try { when (parts.size) { 2 -> parts[0].split(";") .let { (x, y) -> CircleZone(Pair(x.toInt(), y.toInt()), parts[1].toInt()) } 3 -> { TriangleZone( listOf(parts[0].split(";").let { (x, y) -> Pair(x.toInt(), y.toInt()) }, parts[1].split(";").let { (x, y) -> Pair(x.toInt(), y.toInt()) }, parts[2].split(";").let { (x, y) -> Pair(x.toInt(), y.toInt()) }) ) } 4 -> { RectangleZone( listOf(parts[0].split(";").let { (x, y) -> Pair(x.toInt(), y.toInt()) }, parts[1].split(";").let { (x, y) -> Pair(x.toInt(), y.toInt()) }, parts[2].split(";").let { (x, y) -> Pair(x.toInt(), y.toInt()) }, parts[3].split(";").let { (x, y) -> Pair(x.toInt(), y.toInt()) }) ) } else -> null } } catch (e: Exception) { println("Invalid input. Please enter valid zone parameters.") null } } fun readIncident(): Incident? { val phones = arrayOf( "89583278394", "+74829573828", null, "+7-938-284-35-66", "74831743929", null, "89453337248", "+74924753932", null, null ) val descriptions = arrayOf( "My cat can't get off the tree", "I can't find my TV remote", "There is an UFO kidnapping a cow", "There is a bug in compiler, help me please!", "two number 9's, a number 9 large, a number 6 with extra dip..." ) fun getIncidentType(description: String): IncidentType? { return when { "FIRE" in description.uppercase() -> IncidentType.FIRE "GAS" in description.uppercase() && "LEAK" in description.uppercase() -> IncidentType.GAS_LEAK "CAT" in description.uppercase() && "TREE" in description.uppercase() -> IncidentType.CAT_ON_TREE else -> null } } println("Enter an incident coordinates:") return try { val input = readLine() ?: throw Exception() if (input.split(" ").size != 1) throw Exception() val coordinates = input.split(";").map { it.toIntOrNull() ?: throw Exception() } if (coordinates.size != 2) throw Exception() val description = descriptions.random() val phone = phones.random() val type = getIncidentType(description) Incident(coordinates[0], coordinates[1], description, phone, type) } catch (e: Exception) { null } } data class Incident( val x: Int, val y: Int, val description: String, val phoneNumber: String?, val type: IncidentType? ) enum class IncidentType(val type: String) { FIRE("Fire"), GAS_LEAK("Gas leak"), CAT_ON_TREE("Cat on the tree") } open class Zone { private val kPhoneNumber = "88008473824" open fun isIncidentInside(incident: Incident?): Boolean { return false } open fun getPhoneNumber(): String { return kPhoneNumber } } class CircleZone(private val center: Pair<Int, Int>, private val radius: Int) : Zone() { private val kPhoneNumber = "89347362826" override fun isIncidentInside(incident: Incident?): Boolean { return if (incident != null) { val distance = sqrt( (incident.x - center.first).toDouble().pow(2) + (incident.y - center.second).toDouble() .pow(2) ) distance < radius } else false } override fun getPhoneNumber(): String { return kPhoneNumber } } class TriangleZone(private val points: List<Pair<Int, Int>>) : Zone() { private val kPhoneNumber = "84352835724" override fun isIncidentInside(incident: Incident?): Boolean { return if (incident != null) { val (x, y) = Pair(incident.x.toDouble(), incident.y.toDouble()) val (x1, y1) = points[0] val (x2, y2) = points[1] val (x3, y3) = points[2] val area = 0.5 * (-y2 * x3 + y1 * (-x2 + x3) + x1 * (y2 - y3) + x2 * y3) val s = 1 / (2 * area) * (y1 * x3 - x1 * y3 + (y3 - y1) * x + (x1 - x3) * y) val t = 1 / (2 * area) * (x1 * y2 - y1 * x2 + (y1 - y2) * x + (x2 - x1) * y) s > 0 && t > 0 && 1 - s - t > 0 } else false } override fun getPhoneNumber(): String { return kPhoneNumber } } class RectangleZone(private val points: List<Pair<Int, Int>>) : Zone() { private val kPhoneNumber = "89857889497" override fun isIncidentInside(incident: Incident?): Boolean { if (incident == null) return false val point = Point(incident.x.toDouble(), incident.y.toDouble()) var angleSum = 0.0 for (i in points.indices) { val vi = Point(points[i].first.toDouble(), points[i].second.toDouble()) val vPrev = Point( points[(i + points.size - 1) % points.size].first.toDouble(), points[(i + points.size - 1) % points.size].second.toDouble() ) angleSum += angleBetweenPoints(point, vPrev, vi) } return abs(angleSum) >= 0.000001 } override fun getPhoneNumber(): String { return kPhoneNumber } private fun angleBetweenPoints(p: Point, a: Point, b: Point): Double { val angle1 = atan2(a.y - p.y, a.x - p.x) val angle2 = atan2(b.y - p.y, b.x - p.x) var angle = angle2 - angle1 if (angle > PI) { angle -= 2 * PI } else if (angle < -PI) { angle += 2 * PI } return angle } data class Point(val x: Double, val y: Double) }
0
Kotlin
0
1
1dc4de50dd3cd875e3fe76e3da4a58aa04bb87c7
5,445
Kotlin_bootcamp
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumSubseq.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD import java.util.Arrays /** * 1498. Number of Subsequences That Satisfy the Given Sum Condition * @see <a href="https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition"> * Source</a> */ fun interface NumSubseq { operator fun invoke(nums: IntArray, target: Int): Int } class NumSubseqBinarySearch : NumSubseq { override operator fun invoke(nums: IntArray, target: Int): Int { val n: Int = nums.size Arrays.sort(nums) val power = IntArray(n) power[0] = 1 for (i in 1 until n) { power[i] = power[i - 1] * 2 % MOD } var answer = 0 // Iterate over each left pointer. for (left in 0 until n) { // Find the insertion position for `target - nums[left]` // 'right' equals the insertion index minus 1. val right = binarySearchRightmost(nums, target - nums[left]) - 1 if (right >= left) { answer += power[right - left] answer %= MOD } } return answer } private fun binarySearchRightmost(nums: IntArray, target: Int): Int { var left = 0 var right = nums.size - 1 while (left <= right) { val mid = left + (right - left) / 2 if (nums[mid] <= target) { left = mid + 1 } else { right = mid - 1 } } return left } } class NumSubseqTwoPointers : NumSubseq { override operator fun invoke(nums: IntArray, target: Int): Int { val n: Int = nums.size nums.sort() // Precompute the value of 2 to the power of each value. val power = IntArray(n) power[0] = 1 for (i in 1 until n) { power[i] = power[i - 1] * 2 % MOD } var answer = 0 var left = 0 var right = n - 1 while (left <= right) { if (nums[left] + nums[right] <= target) { answer += power[right - left] answer %= MOD left++ } else { right-- } } return answer } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,879
kotlab
Apache License 2.0
src/main/kotlin/day11_dumbo_octopus/DumboOctopus.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day11_dumbo_octopus import geom2d.Rect import geom2d.asLinearOffset import geom2d.asPoint import java.util.* /** * Conway's game of life, but with cascade! Since each state is wholly derived * from the prior state, that suggests an immutable fold of some sort. But with * the cascade, it's not going to be a _simple_ fold. Each iteration will need * to have some stateful recursive walk inside to cascade the flashes from * octopus to octopus. * * Part two's just a matter of setting up a forever loop and some way of knowing * how many flashes occurred on a given step. The former's simple; the latter's * already known - though perhaps not explicitly - so that the right octopuses * can be reset to zero after the cascade. */ fun main() { util.solve(1588, ::partOne) util.solve(517, ::partTwo) } fun partOne(input: String) = partOne(input, 100) private class Grid(input: String) { val width = input.indexOf('\n') var grid = input .filter { it != '\n' } .map(Char::digitToInt) val height = grid.size / width val bounds = Rect(width.toLong(), height.toLong()) var flashes = 0 var ticks = 0 fun tick(): Int { // everyone goes up by one val next = grid .map { it + 1 } as MutableList // greater than nine flashes val queue: Queue<Int> = LinkedList() fun illuminate(idx: Int) { queue.add(idx) next[idx] += 1 } next.forEachIndexed { i, it -> if (it > 9) { queue.add(i) } } val flashed = mutableSetOf<Int>() while (queue.isNotEmpty()) { val i = queue.remove() if (next[i] <= 9) continue if (!flashed.add(i)) continue bounds.asPoint(i.toLong()) .neighbors(bounds) .forEach { illuminate(bounds.asLinearOffset(it).toInt()) } } // reset flashers to zero flashed.forEach { next[it] = 0 } grid = next flashes += flashed.size ticks += 1 return flashed.size } } fun partOne(input: String, steps: Int): Int { val grid = Grid(input) repeat(steps) { grid.tick() } return grid.flashes } fun partTwo(input: String): Int { val grid = Grid(input) val all = grid.bounds.pointCount.toInt() while (true) { if (grid.tick() == all) { return grid.ticks } } }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
2,490
aoc-2021
MIT License
src/Day01.kt
robotfooder
573,164,789
false
{"Kotlin": 25811}
fun main() { fun groupedElves(input: List<String>): List<List<Int>> = input .chunkedBy { it.isBlank() } .map { elf -> elf.map { it.toInt() } } fun part1(input: List<String>): Int = groupedElves(input) .maxOf { it.sum() } fun part2(input: List<String>): Int = groupedElves(input) .sortedByDescending { it.sum() } .take(3) .sumOf { it.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9876a52ef9288353d64685f294a899a58b2de9b5
708
aoc2022
Apache License 2.0
src/main/java/kt/day1/PermutationGeneratorKotlin.kt
surya-uppuluri
292,050,828
false
{"Java": 9862, "Kotlin": 5746}
package kt.day1 import java.util.* internal class PermutationGeneratorKotlin { /** * Given input as 1,2,3,4 generate all permutations of it as - * 1234 * 1243 * 1324 * 1342 * 1423 * 1432 * ---- * 2134 * 2143 * 2314 * 2341 * 2413 * 2431 * ---- * 3124 * 3142 * 3241 * 3214 * 3412 * 3421 * ---- * 4123 * 4132 * 4213 * 4231 * 4312 * 4321 */ private var allPermutations: ArrayList<Any> = ArrayList<Any>() lateinit var input: List<Int> fun generatePermutations(input: List<Int>): ArrayList<Any> { this.input = input //declaring and assigning to class variable to avoid passing this variable around in backtracking/recursion. /** * Algorithm to generate permutations of a given array/string * --------------------------------------------------- * * If you look at the example of human mind generating permutations, it does it systematically. Think how? * 1. Take a number, generate all possibilities with that number. * 2. Then remove the number that you just took and start over again till each permutation is generated having size * equal to the size of given input. [2134 has same size as 1234. You removed initial 1 and replaced it with 2 * to get a new permutation. * 3. We are going to do the same programmatically. Watch out how. */ val eachRow: ArrayList<Any> = ArrayList<Any>() val visited = BooleanArray(input.size) //I prefer array rather than list for bool because it comes prepopulated with false which is what I want. backtrack(eachRow, visited) return allPermutations } private fun backtrack(eachRow: ArrayList<Any>, visited: BooleanArray) { /** Define base case first. When do you stop recursing for a given row? * When you find that a row has all 4 digits populated for a input size of 4. */ if (eachRow.size === input.size) { allPermutations.add(ArrayList(eachRow)) return } for (i in input.indices) { if (visited[i]) continue //if a column in current iteration is marked as true, continue till the end and find new permutations eachRow.add(input[i]) //If it's not true, it means it's not in current permutation yet. Add it and backtrack visited[i] = true //well you've already visited the column. Mark it true. backtrack(eachRow, visited) //backtrack with current configuration eachRow.remove(eachRow.size - 1) //Now, just like your mind removed the last right most element to replace it with a new element to generate a new permutation, let the code do the same. visited[i] = false //I want to give rise to new permutations } } }
0
Java
0
0
5cddbecb5502294537137b6864aaf54eb001be5d
2,911
september-leetcode-challenge
Apache License 2.0
src/main/kotlin/g2301_2400/s2385_amount_of_time_for_binary_tree_to_be_infected/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2385_amount_of_time_for_binary_tree_to_be_infected // #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_07_02_Time_609_ms_(100.00%)_Space_75.2_MB_(100.00%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private var max = 0 fun amountOfTime(root: TreeNode?, start: Int): Int { dfs(root, start, Distance(-1)) return max } private fun dfs(root: TreeNode?, start: Int, l: Distance): Int { if (root == null) { return 0 } val ld = Distance(-1) val rd = Distance(-1) val left = dfs(root.left, start, ld) val right = dfs(root.right, start, rd) if (l.`val` == -1 && start == root.`val`) { max = Math.max(left, right) l.`val` = 1 } if (ld.`val` != -1) { max = Math.max(max, ld.`val` + right) l.`val` = ld.`val` + 1 } else if (rd.`val` != -1) { max = Math.max(max, rd.`val` + left) l.`val` = rd.`val` + 1 } return Math.max(left, right) + 1 } private class Distance internal constructor(var `val`: Int) }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,383
LeetCode-in-Kotlin
MIT License
src/test/kotlin/com/igorwojda/string/isanagram/solution.kt
Daenges
400,897,104
true
{"Kotlin": 217983}
package com.igorwojda.string.isanagram private object Solution1 { private fun isAnagram(str1: String, str2: String): Boolean { val a1 = str1.toUpperCase().filter { it.isLetter() }.groupBy { it } val a2 = str2.toUpperCase().filter { it.isLetter() }.groupBy { it } return a1 == a2 } } private object Solution2 { private fun isAnagram(str1: String, str2: String): Boolean { return getCharFrequency(str1) == getCharFrequency(str2) } private fun getCharFrequency(str: String): Map<Char, List<Char>> { return str.toLowerCase() .filter { it.isLetterOrDigit() } .groupBy { it } } } private object Solution3 { private fun isAnagram(str1: String, str2: String): Boolean { return getCharFrequency(str1) == getCharFrequency(str2) } private fun getCharFrequency(str: String): Map<Char, Int> { return str.toLowerCase() .filter { it.isLetterOrDigit() } .groupingBy { it } .eachCount() } } private object Solution4 { private fun isAnagram(str1 : String, str2 : String) : Boolean { return if (str1.isNotEmpty() && str2.isNotEmpty()) { val str1FirstLetter = str1[0] val str1Rest = str1.substring(1) return if(str2.contains(str1FirstLetter, true)) { val str2Rest = str2.replaceFirst(str1FirstLetter.toString(), "", true) isAnagram(str1Rest, str2Rest) } else { false } } else { true } } } private object KtLintWillNotComplain
0
Kotlin
0
0
cd1d0c0b76dfef09ad8a2984674cdb4cb3bbea9c
1,634
kotlin-coding-challenges
MIT License
kotlin/src/main/java/com/samelody/samples/kotlin/algorithms/quicksort.kt
belinwu
140,991,591
false
{"Kotlin": 70895, "Java": 1117}
package com.samelody.samples.kotlin.algorithms import com.samelody.samples.kotlin.example import com.samelody.samples.kotlin.swapAt import java.util.* fun <T : Comparable<T>> MutableList<T>.hoarePartition(low: Int, high: Int): Int { val pivot = this[low] var i = low - 1 var j = high + 1 while (true) { do { j -= 1 } while (this[j] > pivot) do { i += 1 } while (this[i] < pivot) if (i < j) swapAt(i, j) else return j } } fun <T : Comparable<T>> MutableList<T>.hoareQuicksort(low: Int, high: Int) { if (low >= high) return val pivot = hoarePartition(low, high) hoareQuicksort(low, pivot) hoareQuicksort(pivot + 1, high) } fun <T : Comparable<T>> MutableList<T>.lomutoPartition(low: Int, high: Int): Int { val pivot = this[high] var i = low for (j in low until high) { if (this[j] <= pivot) { swapAt(i, j) i += 1 } } swapAt(i, high) return i } fun <T : Comparable<T>> MutableList<T>.lomutoQuicksort(low: Int, high: Int) { if (low >= high) return val pivot = lomutoPartition(low, high) lomutoQuicksort(low, pivot - 1) lomutoQuicksort(pivot + 1, high) } fun <T : Comparable<T>> MutableList<T>.lomutoMedian(low: Int, high: Int): Int { val mid = (low + high) / 2 if (this[low] > this[mid]) { swapAt(low, mid) } if (this[low] > this[high]) { swapAt(low, high) } if (this[mid] > this[high]) { swapAt(mid, high) } return mid } fun <T : Comparable<T>> MutableList<T>.lomutoMedianQuicksort(low: Int, high: Int) { if (low >= high) return val median = lomutoMedian(low, high) swapAt(median, high) val pivot = lomutoPartition(low, high) lomutoQuicksort(low, pivot - 1) lomutoQuicksort(pivot + 1, high) } fun <T : Comparable<T>> MutableList<T>.dutchFlagPartition( low: Int, high: Int, pivotIndex: Int ): Pair<Int, Int> { val pivot = this[pivotIndex] var smaller = low var equal = low var larger = high while (equal <= larger) { when { this[equal] < pivot -> { swapAt(equal, smaller) smaller += 1 equal += 1 } this[equal] == pivot -> { equal += 1 } else -> { swapAt(equal, larger) larger -= 1 } } } return smaller to larger } fun <T : Comparable<T>> MutableList<T>.dutchFlagQuicksort(low: Int, high: Int) { if (low >= high) return val middle = dutchFlagPartition(low, high, high) dutchFlagQuicksort(low, middle.first - 1) dutchFlagQuicksort(middle.second + 1, high) } fun<T: Comparable<T>> MutableList<T>.lomutoQuicksortIterative(low: Int, high: Int) { val stack = Stack<Int>() stack.push(low) stack.push(high) while (!stack.isEmpty()) { val end = stack.pop() ?: continue val start = stack.pop() ?: continue val p = this.lomutoPartition(start, end) if ((p - 1) > start) { stack.push(start) stack.push(p - 1) } if ((p + 1) < end) { stack.push(p + 1) stack.push(end) } } } fun<T: Comparable<T>> MutableList<T>.lomutoQuicksortIterativeUseArray(low: Int, high: Int) { val stack = IntArray(high - low + 1) var top = -1 stack[++top] = low stack[++top] = high while (top >= 0) { val end = stack[top--] val start = stack[top--] val p = lomutoPartition(start, end) if ((p - 1) > start) { stack[++top] = start stack[++top] = p - 1 } if ((p + 1) < end) { stack[++top] = p + 1 stack[++top] = end } } } fun main() { "Lomuto Quicksort" example { val list = arrayListOf(12, 0, 3, 9, 2, 21, 18, 27, 1, 5, 8, -1, 8) println(list) list.lomutoQuicksort(0, list.size - 1) println(list) } "Lomuto Quicksort Interatively" example { val list = arrayListOf(12, 0, 3, 9, 2, 21, 18, 27, 1, 5, 8, -1, 8) println(list) list.lomutoQuicksortIterative(0, list.size - 1) println(list) } "Lomuto Median Quicksort" example { val list = arrayListOf(12, 0, 3, 9, 2, 21, 18, 27, 1, 5, 8, -1, 8) println(list) list.lomutoMedianQuicksort(0, list.size - 1) println(list) } "Hoare Quicksort" example { val list = arrayListOf(12, 0, 3, 9, 2, 21, 18, 27, 1, 5, 8, -1, 8) println(list) list.hoareQuicksort(0, list.size - 1) println(list) } "Dutch Flag Quicksort" example { val list = arrayListOf(12, 0, 3, 9, 2, 21, 18, 27, 1, 5, 8, -1, 8) println(list) list.dutchFlagQuicksort(0, list.size - 1) println(list) } }
0
Kotlin
0
2
dce2b98cb031df6bbf04cfc576541a2d96134b5d
4,893
samples
Apache License 2.0
src/Day05.kt
thelmstedt
572,818,960
false
{"Kotlin": 30245}
import java.io.File import java.util.* fun main() { fun parseCommands(moves: String): List<List<Int>> { val commands = moves.lineSequence() .filter { it.isNotBlank() } .map { move -> "[0-9]+".toRegex().allMatches(move).map { it.toInt() } }.toList() return commands } fun stacks(map: String): MutableList<Stack<String>> { val bucketCount = map.lines().last().replace(" ", "").length val columns = mutableListOf<Stack<String>>() (0 until bucketCount).forEach { idx -> val col = Stack<String>() columns.add(col) } val mapLines = map.lines() .dropLast(1) .filter { it.isNotBlank() } .forEach { line -> line.drop(1).every(4).forEachIndexed { index, s -> if (s.isNotBlank()) { columns[index].push(s) } } } columns.forEach { it.reverse() } return columns } fun part1(file: File): Any { val (map, moves) = file.readText().split("\n\n") println(map) println(moves) val commands = parseCommands(moves) val stacks = stacks(map) stacks.forEach { println(it) } commands.forEach { (move, from, to) -> (0 until move).forEach { _ -> val pop = stacks[from - 1].pop() println("$pop from $from to $to") stacks[to - 1].push(pop) stacks.forEach { println(it) } println() } } stacks.forEach { println(it) } var answer = "" stacks.forEach { answer += it.pop() } return answer } fun part2(file: File): Any { val (map, moves) = file.readText().split("\n\n") println(map) println(moves) val commands = parseCommands(moves) val stacks = stacks(map) stacks.forEach { println(it) } commands.forEach { (move, from, to) -> val popped = mutableListOf<String>() (0 until move).forEach { _ -> popped.add(stacks[from - 1].pop()) } println("XXX $popped from $from to $to") popped.reversed().forEach { stacks[to - 1].push(it) } stacks.forEach { println(it) } println() } stacks.forEach { println(it) } var answer = "" stacks.forEach { answer += it.pop() } return answer } println(part1(File("src", "Day05_test.txt"))) println(part1(File("src", "Day05.txt"))) println(part2(File("src", "Day05_test.txt"))) println(part2(File("src", "Day05.txt"))) }
0
Kotlin
0
0
e98cd2054c1fe5891494d8a042cf5504014078d3
3,006
advent2022
Apache License 2.0
src/day5.kt
SerggioC
573,171,085
false
{"Kotlin": 8824}
import java.io.File import java.util.Stack fun main() { val file5 = File("src", "day5.txt").readText() val (stacks, movementsStr) = file5.split("\r\n\r\n") val stackLines = stacks.split("\r\n") val movements = movementsStr.split("\r\n") var stackMap = getStackMapFromInput(stackLines) println(stackMap) movements.forEach { movement -> val (n, f) = movement.replace("move ", "").split(" from ") val numberOfMoves = n.toInt() val (from, to) = f.split(" to ").map { it.toInt() } repeat(numberOfMoves) { stackMap[to]!!.push(stackMap[from]!!.pop()) } } println(stackMap) val result = stackMap.map { it.value.pop() }.joinToString(separator = "") { it.toString() } println("result is $result") // part 2 stackMap = getStackMapFromInput(stackLines) movements.forEach { movement -> val (n, f) = movement.replace("move ", "").split(" from ") val numberOfMoves = n.toInt() val (from, to) = f.split(" to ").map { it.toInt() } val listToAdd = mutableListOf<Char>() repeat(numberOfMoves) { listToAdd.add(stackMap[from]!!.pop()) } listToAdd.reversed().forEach { stackMap[to]!!.push(it) } } val result2 = stackMap.map { it.value.pop() }.joinToString(separator = "") { it.toString() } println("result2 is $result2") } private fun getStackMapFromInput( stackLines: List<String>, ): MutableMap<Int, Stack<Char>> { val stackMap = mutableMapOf<Int, Stack<Char>>() (stackLines.size - 2 downTo 0).forEach { lineIndex -> val line = stackLines[lineIndex] (1..line.length step 4).forEachIndexed { stepIndex, charIndex -> val stackIndex = stepIndex + 1 val stack = stackMap[stackIndex] ?: Stack<Char>() val char = line[charIndex] if (char.isLetter()) { stack.push(char) stackMap[stackIndex] = stack } } } return stackMap }
0
Kotlin
0
0
d56fb119196e2617868c248ae48dcde315e5a0b3
2,049
aoc-2022
Apache License 2.0
src/y2022/Day07.kt
Yg0R2
433,731,745
false
null
package y2022 import DayX class Day07 : DayX<Int>(95_437, 24_933_642) { override fun part1(input: List<String>): Int { val rootDir = Dir("/") initDir(input, rootDir) return getFoldersSize(rootDir) .filter { it.key <= 100_000 } .keys .sum() } override fun part2(input: List<String>): Int { val rootDir = Dir("/") initDir(input, rootDir) val freeSpace = 70_000_000 - rootDir.getSize() val requiredSpace = 30_000_000 return getFoldersSize(rootDir) .keys .filter { it >= requiredSpace - freeSpace } .min() } private fun getNextCommandLineIndex( input: List<String>, startLineIndex: Int ): Int { return input .drop(startLineIndex) .indexOfFirst { it.startsWith("$") } .let { if (it == -1) { input.size - 1 } else { it + startLineIndex } } } private fun initDir( input: List<String>, currentDir: Dir, startLineIndex: Int = 0, ) { val nextCommandIndex = with(getNextCommandLineIndex(input, startLineIndex) + 1) { if (this >= input.size) { input.size } else { this } } input.subList(startLineIndex, nextCommandIndex) .forEachIndexed { index, line -> when { line == "$ cd /" -> { var rootDir = currentDir while (rootDir.parentDir != null) { rootDir = rootDir.parentDir!! } initDir(input, rootDir, (startLineIndex + index + 1)) } line == "$ cd .." -> { initDir(input, currentDir.parentDir!!, (startLineIndex + index + 1)) } line.startsWith("$ cd") -> { val subFolderName = line.substring(5) val subFolder = currentDir.subDirs .first { it.name == subFolderName } initDir(input, subFolder, (startLineIndex + index + 1)) } line == "$ ls" -> { initDir(input, currentDir, startLineIndex + index + 1) } else -> { if (line.startsWith("dir")) { Dir( name = line.substring(4), parentDir = currentDir ).let { currentDir.subDirs.add(it) } } else { line.split(" ") .let { File( name = it[1], size = it[0].toInt() ) } .let { currentDir.files.add(it) } } } } } } private fun getFoldersSize(currentDir: Dir): Map<Int, Dir> { val foldersSize: MutableMap<Int, Dir> = mutableMapOf() foldersSize[currentDir.getSize()] = currentDir currentDir.subDirs .forEach { foldersSize.putAll(getFoldersSize(it)) } return foldersSize } private data class Dir( var name: String, var parentDir: Dir? = null, var subDirs: MutableList<Dir> = mutableListOf(), var files: MutableList<File> = mutableListOf() ) { fun getSize(): Int = subDirs.sumOf { it.getSize() } + files.sumOf { it.size } override fun toString(): String = name } private data class File( val name: String, val size: Int ) { override fun toString(): String = name } }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
4,303
advent-of-code
Apache License 2.0
src/day24/Day24.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day24 import lib.DecreaseYDirection import lib.IncreaseYDirection import lib.LeftDirection import lib.Point2D import lib.RightDirection import lib.Vector2D import lib.directionsClockwise import readInput fun main() { val day = 24 // val testInput = readInput("day$day/testInput") // check(part1(testInput) == 18) val input = readInput("day$day/input") // println(part1(input)) println(part2(input)) } fun readWinds(input: List<String>): MutableList<Pair<Point2D, Vector2D>> { val winds = mutableListOf<Pair<Point2D, Vector2D>>() val h = input.size val w = input[0].length (0 until h).forEach { y -> (0 until w).forEach { x -> val c = input[y][x] val p = Point2D(x, y) when (c) { '>' -> winds.add(p to RightDirection) '<' -> winds.add(p to LeftDirection) 'v' -> winds.add(p to IncreaseYDirection) '^' -> winds.add(p to DecreaseYDirection) else -> {} } } } return winds } fun updateWindPositions(winds: MutableList<Pair<Point2D, Vector2D>>, w: Int, h: Int) { for (i in winds.indices) { val wind = winds[i] val newPosition = wind.first + wind.second var x = newPosition.x var y = newPosition.y if (x < 1) { x = (w - 2) } if (x > w - 2) { x = 1 } if (y < 1) { y = (h - 2) } if (y > h - 2) { y = 1 } winds[i] = Point2D(x, y) to wind.second } } fun part1(input: List<String>): Int { val h = input.size val w = input[0].length val start = Point2D(1, 0) val destination = Point2D(w - 2, h - 1) val winds = readWinds(input) var minute = 0 val childs = mutableSetOf<Point2D>() childs.add(start) var notFound = true while (notFound) { updateWindPositions(winds, w, h) val windsPositions = winds.map { it.first }.toSet() val newChilds = mutableSetOf<Point2D>() for (childNode in childs) { directionsClockwise.forEach { dir -> val p = childNode + dir if (p == destination) { notFound = false } if (((p.x in 1 until w - 1) && (p.y in 1 until h - 1)) || p == start) { if (!windsPositions.contains(p)) { newChilds.add(p) } } } if (!windsPositions.contains(childNode)) { newChilds.add(childNode) } } childs.clear() childs.addAll(newChilds) minute++ println("Minute: $minute, childCount: ${childs.size}") } return minute } fun part2(input: List<String>): Int { val h = input.size val w = input[0].length val start = Point2D(1, 0) val destination = Point2D(w - 2, h - 1) val winds = readWinds(input) var minute = 0 val childs = mutableSetOf<Point2D>() childs.add(start) // reached goal, come back, reached goal againe val destinations = listOf(destination, start, destination) var currentDestinationIndex = 0 while (currentDestinationIndex != 3) { updateWindPositions(winds, w, h) minute++ val windsPositions = winds.map { it.first }.toSet() val newChilds = mutableSetOf<Point2D>() var reachedCurrentDestination = false for (childNode in childs) { directionsClockwise.forEach { dir -> val p = childNode + dir if (p == destinations[currentDestinationIndex]) { reachedCurrentDestination = true } if (((p.x in 1 until w - 1) && (p.y in 1 until h - 1)) || p == start) { if (!windsPositions.contains(p)) { newChilds.add(p) } } } if (!windsPositions.contains(childNode)) { newChilds.add(childNode) } } childs.clear() if (reachedCurrentDestination) { childs.add(destinations[currentDestinationIndex]) currentDestinationIndex++ } else { childs.addAll(newChilds) } println("Minute: $minute, childCount: ${childs.size}, reachedCurrentDestination: $reachedCurrentDestination") } return minute }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
4,531
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2023/d01/Day01.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d01 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines val englishDigits = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, ) fun String.getDigit(idx: Int): Int? { if (this[idx].isDigit()) { return this[idx].digitToInt() } englishDigits.keys.forEach { name -> if (idx + name.length <= this.length && this.substring(idx until idx + name.length) == name) { return englishDigits[name] } } return null } fun getCalibration1(line: String) = "${line.first { it.isDigit() }}${line.last { it.isDigit() }}".toInt() fun getCalibration2(line: String): Int { val digits = line.indices.mapNotNull { line.getDigit(it) } return digits.first() * 10 + digits.last() } fun main() = timed { val lines = (DATAPATH / "2023/day01.txt").useLines { it.toList() } lines .sumOf { getCalibration1(it) } .also { println("Part one: $it") } lines .sumOf { getCalibration2(it) } .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,236
advent-of-code
MIT License
ceria/05/src/main/kotlin/Solution.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File; var ventLines = mutableListOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>() fun main(args : Array<String>) { arrangeInput(File(args.first()).readLines()) println("Solution 1: ${solution1()}") println("Solution 2: ${solution2()}") } private fun solution1() :Int { var ventCounts = mutableMapOf<Pair<Int, Int>, Int>() for (line in ventLines) { if (line.first.first == line.second.first) { // x of both points are the same, this is a vertical line var start = line.first.second var end = line.second.second if (start > end) { // flip the start and end so we don't have to use downTo in the loop start = line.second.second end = line.first.second } for (y in start..end) { val newPoint = Pair<Int, Int>(line.first.first, y) val count = ventCounts.get(newPoint)?.let{ ventCounts.get(newPoint) } ?: 0 ventCounts.put(newPoint, count + 1) } } else // Must use an if statement here, because the input looks like it includes diagnols... if (line.first.second == line.second.second) { var start = line.first.first var end = line.second.first if (start > end) { // flip the start and end so we don't have to use downTo in the loop start = line.second.first end = line.first.first } // y of both points are the same, this is a horizontal line for (x in start..end) { val newPoint = Pair<Int, Int>(x, line.first.second) val count = ventCounts.get(newPoint)?.let{ ventCounts.get(newPoint) } ?: 0 ventCounts.put(newPoint, count + 1) } } } return ventCounts.values.filter { it > 1 }.count() } private fun solution2() :Int { var ventCounts = mutableMapOf<Pair<Int, Int>, Int>() for (line in ventLines) { if (line.first.first == line.second.first) { // x of both points are the same, this is a vertical line var start = line.first.second var end = line.second.second if (start > end) { // flip the start and end so we don't have to use downTo in the loop start = line.second.second end = line.first.second } for (y in start..end) { val newPoint = Pair<Int, Int>(line.first.first, y) val count = ventCounts.get(newPoint)?.let{ ventCounts.get(newPoint) } ?: 0 ventCounts.put(newPoint, count + 1) } } else // Must use an if statement here, because the input looks like it includes diagnols... if (line.first.second == line.second.second) { var start = line.first.first var end = line.second.first if (start > end) { // flip the start and end so we don't have to use downTo in the loop start = line.second.first end = line.first.first } // y of both points are the same, this is a horizontal line for (x in start..end) { val newPoint = Pair<Int, Int>(x, line.first.second) val count = ventCounts.get(newPoint)?.let{ ventCounts.get(newPoint) } ?: 0 ventCounts.put(newPoint, count + 1) } } else { // This is a diagonal line val count = ventCounts.get(line.first)?.let{ ventCounts.get(line.first) } ?: 0 ventCounts.put(line.first, count + 1) var x = line.first.first var y = line.first.second while (x != line.second.first) { if (x > line.second.first) { x -= 1 } else { x += 1 } if (y < line.second.second) { y += 1 } else { y -= 1 } val newPoint = Pair<Int, Int>(x, y) val updatedCount = ventCounts.get(newPoint)?.let{ ventCounts.get(newPoint) } ?: 0 ventCounts.put(newPoint, updatedCount + 1) } } } return ventCounts.values.filter { it > 1 }.count() } private fun arrangeInput(input: List<String>) { for (line in input) { val points = line.split(" -> ") val firstPoint = points[0].split(",") val secondPoint = points[1].split(",") val start = Pair<Int, Int>(firstPoint.first().toInt(), firstPoint.last().toInt()) val end = Pair<Int, Int>(secondPoint.first().toInt(), secondPoint.last().toInt()) ventLines.add(Pair<Pair<Int, Int>, Pair<Int, Int>>(start, end)) } }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
5,287
advent-of-code-2021
MIT License
src/Day01.kt
yashpalrawat
573,264,560
false
{"Kotlin": 12474}
import java.util.* private fun getSortedEnergyLevels(input: List<String>) : List<Int> { val energyLevels = mutableListOf<Int>() val result = mutableListOf<Int>() input.forEach { if (it.isNotEmpty()) { energyLevels.add(it.toInt()) } else { result.add(energyLevels.sum()) energyLevels.clear() } } return result.sortedDescending() } fun main() { fun part1(input: List<String>): Int { val energyLevels = getSortedEnergyLevels(input) return energyLevels[0] } fun part2(input: List<String>): Int { val energyLevels = getSortedEnergyLevels(input) return energyLevels[0] + energyLevels[1] + energyLevels[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
78a3a817709da6689b810a244b128a46a539511a
982
code-advent-2022
Apache License 2.0
src/main/kotlin/io/github/misawa/coassign/Solution.kt
MiSawa
226,680,692
false
null
package io.github.misawa.coassign import kotlin.math.max class Solution( private val graph: BipartiteGraph, private val used: BooleanArray, private val potential: WeightArray ) { val value: LargeWeight init { var res: LargeWeight = 0 for (e in graph.forwardEdges) if (used[e]) res += graph.weights[e] value = res } fun getMatches(): List<Pair<Int, Int>> = graph.forwardEdges.filter { used[it] }.map { if (graph.flipped) { ((graph.targets[it] - graph.lSize) to graph.sources[it]) } else { (graph.sources[it] to (graph.targets[it] - graph.lSize)) } } fun checkConstraints() { val matchCount = IntArray(graph.numV) for (e in graph.forwardEdges) if (used[e]) { ++matchCount[graph.sources[e]] ++matchCount[graph.targets[e]] } for (u in graph.nodes) check(matchCount[u] <= graph.multiplicities[u]) { "The matching includes too many edges adjacent to $u" } } fun checkOptimality() { for (e in graph.edges) { val rWeight = graph.weights[e] - potential[graph.sources[e]] + potential[graph.targets[e]] if (rWeight > 0) check(used[e]) { "There's an edge that has positive residual weight but not used" } if (rWeight < 0) check(!used[e]) { "There's an edge that has negative residual weight but used" } } fun sgn(u: Node): Int = if (u < graph.lSize) 1 else -1 var dual: LargeWeight = 0 for (u in graph.nodes) dual += graph.multiplicities[u] * max(0, sgn(u) * potential[u]).toLargeWeight() for (e in graph.forwardEdges) dual += max( 0, graph.weights[e] - potential[graph.sources[e]] + potential[graph.targets[e]] ) check(value == dual) { "Primal and dual value should be the same. Primal: $value, dual: $dual" } } fun check() { checkConstraints() checkOptimality() } }
0
Kotlin
0
0
2b723480d16e7c9517cf1e5394405a466a5a5360
1,986
coassign
MIT License
src/Day01.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 for (line in input) { if (line.isBlank()) { max = maxOf(max, current) current = 0 } else { current += line.toInt() } } max = maxOf(max, current) return max } fun part2(input: List<String>): Int { val elves = mutableListOf<Int>() var current = 0 for (line in input) { if (line.isBlank()) { elves += current current = 0 } else { current += line.toInt() } } elves += current elves.sortDescending() return elves.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24_000) check(part2(testInput) == 45_000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
1,079
AdventOfCode2022
Apache License 2.0
src/Day03.kt
ricardorlg-yml
573,098,872
false
{"Kotlin": 38331}
fun main() { val priorities = ('a'..'z') .plus('A'..'Z') .mapIndexed { index, c -> c to index + 1 } .toMap() fun intersect(strings: List<String>): Set<Char> { return strings .map(String::toSet) .reduce { acc, set -> acc.intersect(set) } } fun part1(input: List<String>): Int { return input .map { it.chunked(it.length / 2) } .sumOf { priorities[intersect(it).single()]!! } } fun part2(input: List<String>): Int { return input .chunked(3) .sumOf { priorities[intersect(it).single()]!! } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d7cd903485f41fe8c7023c015e4e606af9e10315
842
advent_code_2022
Apache License 2.0
day11/src/main/kotlin/Day11.kt
bzabor
160,240,195
false
null
class Day11(private val input: List<String>?) { val gridSize = 301 val cellGrid = Array(gridSize) { Array(gridSize) { 0 } } fun part1(): String { setPowerLevel(7989) return findMaxPowerForDim(3).toString() } fun part2(): String { return findMaxDim().toString() } //Find the fuel cell's rack ID, which is its X coordinate plus 10. //Begin with a power level of the rack ID times the Y coordinate. //Increase the power level by the value of the grid serial number (your puzzle input). //Set the power level to itself multiplied by the rack ID. //Keep only the hundreds digit of the power level (so 12345 becomes 3; numbers with no hundreds digit become 0). //Subtract 5 from the power level. fun setPowerLevel(gridSerialNumber: Int) { for (y in 1 until gridSize) { for (x in 1 until gridSize) { val rackId = x + 10 val powerLevel = (rackId * (rackId * y + gridSerialNumber)).toString() var hundredsDigit = if (powerLevel.length >= 3) powerLevel.dropLast(2).takeLast(1).toInt() else 0 hundredsDigit -= 5 cellGrid[x][y] = hundredsDigit } } } private fun findMaxPowerForDim(gridDim: Int): Int { var maxPowerX = 0 var maxPowerY = 0 var maxPower = 0 for (y in 1 until gridSize - gridDim) { for (x in 1 until gridSize - gridDim) { var power = 0 for (powerY in y until y + gridDim) { for (powerX in x until x + gridDim) { power += cellGrid[powerX][powerY] if (power > maxPower) { maxPowerX = x maxPowerY = y maxPower = power } } } } } println("MAX FOR DIM $gridDim x $gridDim AT LOCATION (${maxPowerX},${maxPowerY}) IS $maxPower") return maxPower } private fun findMaxDim(): Int { var maxPowerDim = 0 var maxPower = 0 for (gridDim in 1 until gridSize) { // for (gridDim in 16..16) { val maxPowerForDim = findMaxPowerForDim(gridDim) if (maxPowerForDim > maxPower) { maxPower = maxPowerForDim maxPowerDim = gridDim println("Max power grid dim: $maxPowerDim x $maxPowerDim has a MAX POWER of $maxPower") } } println("FINAL MAX POWER DIM: $maxPowerDim x $maxPowerDim with MAX POWER OF $maxPower") return maxPowerDim } } //
0
Kotlin
0
0
14382957d43a250886e264a01dd199c5b3e60edb
2,710
AdventOfCode2018
Apache License 2.0
src/main/kotlin/co/csadev/advent2022/Day02.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 2 * Problem Description: http://adventofcode.com/2021/day/2 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources class Day02(override val input: String = Resources.resourceAsText("22day02.txt")) : BaseDay<String, Int, Int> { enum class RPS(val opp: String, val beats: String, val draw: String, val loses: String) { Rock("A", "Y", "X", "Z"), Paper("B", "Z", "Y", "X"), Scissors("C", "X", "Z", "Y"); companion object { private fun selfVal(s: String) = 1 + values().first { it.draw == s }.ordinal fun score(o: String, s: String) = selfVal(s) + values() .first { it.opp == o } .run { if (beats == s) 6 else if (loses == s) 0 else 3 } fun strat(o: String, s: String) = values() .first { it.opp == o } .run { when (s) { "X" -> selfVal(loses) "Y" -> 3 + selfVal(draw) else -> 6 + selfVal(beats) } } } } private val strategy = input.lines().map { it.split(" ") } override fun solvePart1() = strategy.sumOf { RPS.score(it[0], it[1]) } override fun solvePart2() = strategy.sumOf { RPS.strat(it[0], it[1]) } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
1,432
advent-of-kotlin
Apache License 2.0
src/day08/Day08.kt
sanyarajan
572,663,282
false
{"Kotlin": 24016}
package day08 import readInputText fun main() { fun getTreeGrid(input: String): MutableList<MutableList<Int>> { //a square grid of tree heights val treeGrid = mutableListOf<MutableList<Int>>() // convert input to treeGrid input.lines().forEach { line -> val row = mutableListOf<Int>() line.forEach { char -> row.add(char.toString().toInt()) } treeGrid.add(row) } return treeGrid } fun part1(input: String): Int { var numVisible = 0 val treeGrid = getTreeGrid(input) // count all trees on the edges numVisible += treeGrid[0].size * 4 - 4 var visible: Boolean // for each tree not on the edges consider it to be visible if it is taller than any tree in the same row or column for (i in 1 until treeGrid.size - 1) { for (j in 1 until treeGrid[i].size - 1) { visible = false val treeHeight = treeGrid[i][j] // check row if (treeGrid[i].subList(0, j).all { it < treeHeight } || treeGrid[i].subList(j + 1, treeGrid[i].size) .all { it < treeHeight }) { visible = true } // check column if (treeGrid.subList(0, i).all { it[j] < treeHeight } || treeGrid.subList(i + 1, treeGrid.size) .all { it[j] < treeHeight }) { visible = true } if (visible) { numVisible++ } } } //println(numVisible) return numVisible } fun part2(input: String): Int { val treeGrid = getTreeGrid(input) var maxScenicScore = 0 var numVisibleTop: Int var numVisibleBottom: Int var numVisibleLeft: Int var numVisibleRight: Int var scenicScore: Int // for each tree count the number of trees visible from that tree in each direction separately for (i in 0 until treeGrid.size) { for (j in 0 until treeGrid[i].size) { numVisibleTop = 0 numVisibleBottom = 0 numVisibleLeft = 0 numVisibleRight = 0 val treeHeight = treeGrid[i][j] // for this tree count how many are visible to the top stopping at the first tree taller or equal in height to this one for (k in i - 1 downTo 0) { if (treeGrid[k][j] >= treeHeight) { numVisibleTop++ break } numVisibleTop++ } // for this tree count how many are visible to the bottom stopping at the first tree taller or equal in height to this one for (k in i + 1 until treeGrid.size) { if (treeGrid[k][j] >= treeHeight) { numVisibleBottom++ break } numVisibleBottom++ } // for this tree count how many are visible to the left stopping at the first tree taller or equal in height to this one for (k in j - 1 downTo 0) { if (treeGrid[i][k] >= treeHeight) { numVisibleLeft++ break } numVisibleLeft++ } // for this tree count how many are visible to the right stopping at the first tree taller or equal in height to this one for (k in j + 1 until treeGrid[i].size) { if (treeGrid[i][k] >= treeHeight) { numVisibleRight++ break } numVisibleRight++ } //println("tree at $i, $j has $numVisible visible") // calculate the scenic score for this tree scenicScore = numVisibleTop * numVisibleBottom * numVisibleLeft * numVisibleRight if (scenicScore > maxScenicScore) { maxScenicScore = scenicScore } } } //println(maxScenicScore) return maxScenicScore } // test if implementation meets criteria from the description, like: val testInput = readInputText("day08/Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInputText("day08/day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e23413357b13b68ed80f903d659961843f2a1973
4,667
Kotlin-AOC-2022
Apache License 2.0
src/Day04.kt
YunxiangHuang
572,333,905
false
{"Kotlin": 20157}
fun main() { class Range(r: String) { private val sepIdx = r.indexOf('-') private var begin = kotlin.run { Integer.valueOf(r.subSequence(0, sepIdx).toString()) } private var end = kotlin.run { Integer.valueOf(r.subSequence(sepIdx + 1, r.length).toString()) } fun contains(other: Range): Boolean { return this.begin <= other.begin && this.end >= other.end } fun overlap(other: Range): Boolean { return other.begin in this.begin..this.end || other.end in this.begin..this.end } } val input = readInput("Day04") var containTotal = 0 var overlapTotal = 0 for (line in input) { val slices = line.split(',') val rangeA = Range(slices[0]) val rangeB = Range(slices[1]) if (rangeA.contains(rangeB) || rangeB.contains(rangeA)) { containTotal++ } if (rangeA.overlap(rangeB) || rangeB.overlap(rangeA)) { overlapTotal++ } } println("Part I: $containTotal") println("Part II: $overlapTotal") }
0
Kotlin
0
0
f62cc39dd4881f4fcf3d7493f23d4d65a7eb6d66
1,163
AoC_2022
Apache License 2.0
openrndr-shape/src/commonMain/kotlin/org/openrndr/shape/LineSegment3D.kt
openrndr
122,222,767
false
{"Kotlin": 2343473, "ANTLR": 9333, "GLSL": 2677, "CSS": 87}
package org.openrndr.shape import org.openrndr.math.Vector3 import kotlin.math.max import kotlin.math.min data class LineSegment3D(val start: Vector3, val end: Vector3) { val direction get() = (end - start) fun nearest(query: Vector3): Vector3 { val l2 = end.minus(start).squaredLength if (l2 == 0.0) return start var t = ((query.x - start.x) * (end.x - start.x) + (query.y - start.y) * (end.y - start.y) + (query.z - start.z)* (end.z - start.z) ) / l2 t = max(0.0, min(1.0, t)) return Vector3(start.x + t * (end.x - start.x),start.y + t * (end.y - start.y), start.z + t * (end.z - start.z)) } fun distance(query: Vector3): Double { return (nearest(query)-query).length } fun squaredDistance(query: Vector3): Double { return (nearest(query)-query).squaredLength } fun sub(t0: Double, t1: Double): LineSegment3D { var z0 = t0 var z1 = t1 if (t0 > t1) { z1 = t0 z0 = t1 } return when { z0 == 0.0 -> split(z1)[0] z1 == 1.0 -> split(z0)[1] else -> split(z0)[1].split(org.openrndr.math.map(z0, 1.0, 0.0, 1.0, z1))[0] } } fun split(t: Double): Array<LineSegment3D> { val u = t.coerceIn(0.0, 1.0) val cut = start + (end.minus(start) * u) return arrayOf(LineSegment3D(start, cut), LineSegment3D(cut, end)) } fun position(t: Double) = start + (end.minus(start) * t) val path: Path3D get() = Path3D.fromPoints(listOf(start, end), false) } fun Segment3D(x0: Double, y0: Double, z0:Double, x1: Double, y1: Double, z1:Double) = Segment3D(Vector3(x0, y0, z0), Vector3(x1, y1, z1))
34
Kotlin
71
808
7707b957f1c32d45f2fbff6b6a95a1a2da028493
1,731
openrndr
BSD 2-Clause FreeBSD License
src/main/kotlin/lyrics/Analysis.kt
yukinsnow
302,052,124
true
{"Kotlin": 176568, "CSS": 1679, "JavaScript": 491, "HTML": 445}
package lyrics import model.LyricsType import model.LyricsType.KANA_CV import model.LyricsType.KANA_VCV import model.LyricsType.ROMAJI_CV import model.LyricsType.ROMAJI_VCV import model.LyricsType.UNKNOWN import model.Note import model.Project import model.Track fun analyseLyricsTypeForProject(project: Project): LyricsType { if (project.tracks.isEmpty()) return UNKNOWN val maxNoteCountInAllTracks = project.tracks.maxBy { it.notes.count() }!!.notes.count() val minNoteCountForAvailableTrack = maxNoteCountInAllTracks * MIN_NOTE_RATIO_FOR_AVAILABLE_TRACK val availableResults = project.tracks .filter { it.notes.count() >= minNoteCountForAvailableTrack } .map { analyseLyricsTypeForTrack(it) } .distinct() .filter { it != UNKNOWN } return if (availableResults.count() > 1) { UNKNOWN } else { availableResults.firstOrNull() ?: UNKNOWN } } private fun analyseLyricsTypeForTrack(track: Track): LyricsType { val total = track.notes.count() val types = track.notes.map { checkNoteType(it) } val typePercentages = LyricsType.values() .map { type -> type to types.count { it == type } } .map { it.first to (it.second.toDouble() / total) } return typePercentages .find { it.second > MIN_RELIABLE_PERCENTAGE } ?.first ?: UNKNOWN } private fun checkNoteType(note: Note): LyricsType { val lyric = note.lyric if (lyric.contains(" ")) { val mainLyric = lyric.substring(lyric.indexOf(" ") + 1) if (mainLyric.isKana) return KANA_VCV if (mainLyric.isRomaji) return ROMAJI_VCV } else { if (lyric.isKana) return KANA_CV if (lyric.isRomaji) return ROMAJI_CV } return UNKNOWN } private const val MIN_RELIABLE_PERCENTAGE = 0.7 private const val MIN_NOTE_RATIO_FOR_AVAILABLE_TRACK = 0.1
0
Kotlin
0
1
439073496530b5326ae860f96886a4c337cc1622
1,867
utaformatix3
Apache License 2.0
src/main/kotlin/me/consuegra/algorithms/KMergeTwoSortedLinkedLists.kt
aconsuegra
91,884,046
false
{"Java": 113554, "Kotlin": 79568}
package me.consuegra.algorithms import me.consuegra.datastructure.KListNode /** * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together * the nodes of the first two lists. */ class KMergeTwoSortedLinkedLists { fun merge(list1: KListNode<Int>?, list2: KListNode<Int>?) : KListNode<Int>? { var auxList1 = list1 var auxList2 = list2 var result: KListNode<Int>? = null while (auxList1 != null || auxList2 != null) { when { auxList1 != null && auxList2 != null -> { if (auxList1.data <= auxList2.data) { result = result?.append(auxList1.data) ?: KListNode(auxList1.data) auxList1 = auxList1.next } else { result = result?.append(auxList2.data) ?: KListNode(auxList2.data) auxList2 = auxList2.next } } auxList1 != null -> { result = result?.append(auxList1.data) ?: KListNode(auxList1.data) auxList1 = auxList1.next } auxList2 != null -> { result = result?.append(auxList2.data) ?: KListNode(auxList2.data) auxList2 = auxList2.next } } } return result } fun mergeRec(list1: KListNode<Int>?, list2: KListNode<Int>?) : KListNode<Int>? { if (list1 == null) { return list2 } if (list2 == null) { return list1 } val result: KListNode<Int>? if (list1.data < list2.data) { result = list1 result.next = merge(list1.next, list2) } else { result = list2 result.next = merge(list1, list2.next) } return result } }
0
Java
0
7
7be2cbb64fe52c9990b209cae21859e54f16171b
1,923
algorithms-playground
MIT License
src/questions/MaxAreaOfIsland.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * You are given an m x n binary matrix grid. An island is a group of 1's (representing land) * connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. * Return the maximum area of an island in grid. If there is no island, return 0. * <img src="https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg" height="150" width="150"/> * [Source](https://leetcode.com/problems/max-area-of-island) */ @UseCommentAsDocumentation private fun maxAreaOfIsland(grid: Array<IntArray>): Int { val seen = mutableSetOf<Pair<Int, Int>>() var max = 0 for (row in 0..grid.lastIndex) { for (col in 0..grid[0].lastIndex) { max = maxOf(max, maxConnected(grid, row, col, seen)) } } return max } private fun maxConnected(grid: Array<IntArray>, row: Int, col: Int, seen: MutableSet<Pair<Int, Int>>): Int { if (row > grid.lastIndex || row < 0 || col < 0 || col > grid[0].lastIndex) { return 0 } val point = Pair(row, col) if (point in seen) { return 0 } seen.add(point) if (grid[row][col] == 1) { return 1 + maxConnected(grid, row - 1, col, seen) .plus(maxConnected(grid, row + 1, col, seen)) .plus(maxConnected(grid, row, col + 1, seen)) .plus(maxConnected(grid, row, col - 1, seen)) } return 0 } fun main() { maxAreaOfIsland( arrayOf( intArrayOf(0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0), intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0), intArrayOf(0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0), intArrayOf(0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0), intArrayOf(0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0), intArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0), intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0), intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0) ) ) shouldBe 6 }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,062
algorithms
MIT License
src/main/kotlin/org/example/e3fxgaming/wortproblem/ExtendedCYKAlgorithm.kt
E3FxGaming
418,121,777
false
{"Kotlin": 9405}
package org.example.e3fxgaming.wortproblem fun main() { val fileContent = InputReader::class.java.getResource("/inputChomskyNF.txt")?.readText() ?: throw Exception("No rules found") val inputReader = InputReader(fileContent) val firstTestWord = "abaaba" val secondTestWord = "abbbba" val thirdTestWord = "bbabbbaabbaabbbabb" val falseWord = "aaabbbb" val solver = Solver(inputReader) println("$firstTestWord: ${solver.solve(firstTestWord)}") println("$secondTestWord: ${solver.solve(secondTestWord)}") println("$thirdTestWord: ${solver.solve(thirdTestWord)}") println("$falseWord: ${solver.solve(falseWord)}") println(inputReader) } /** * Class for reading the Chomsky NF input. Also holds the cache. */ class InputReader(fileContent: String) { //Maps second part of rule to all possible first parts private val rules = fileContent.split(System.getProperty("line.separator")) .map { it.split("->") } .map { Rule(it[0], it[1]) } val reversedRules = rules.groupBy { it.productionOutput } //caching rule wrappers to speed up subsequent same-word-evaluations val cache: MutableMap<String, DerivationWrapper> = mutableMapOf() override fun toString(): String { return "Read ${rules.size } rules. Current cache size: ${cache.size} entries." } } /** * An element of the production system, that can transform a [variable] into a [productionOutput] */ data class Rule(val variable: String, val productionOutput: String) { override fun toString(): String { return "$variable->$productionOutput" } } /** * Since the same [word] may be derived in multiple ways, this DerivationWrapper bundles the possible [derivations]. * Also stores information about its direct [left] and [right] DerivationWrapper descendants. * */ data class DerivationWrapper(val word: String, val derivations: List<DerivationOperation>, val left: DerivationWrapper?, val right: DerivationWrapper?) { fun getChild(childSelector: (DerivationWrapper) -> DerivationWrapper?, collectionList: MutableList<DerivationWrapper>): List<DerivationWrapper> { collectionList.add(this) childSelector(this)?.getChild(childSelector, collectionList) return collectionList } override fun toString(): String { return derivations.joinToString("\n") } } /** * Represents a single derivation A -> A B with [rule], where A ends at [firstSegmentEndsAtIndex]. */ data class DerivationOperation(val rule: Rule, val firstSegmentEndsAtIndex: Int) { override fun toString(): String { return "$rule ($firstSegmentEndsAtIndex)" } } /** * Wrapper class for solving word problems. * [inputReader] provides the grammar information. */ class Solver(private val inputReader: InputReader) { /** * Tests whether a [word] string belongs to the language of the provided grammar. */ fun solve(word: String): Boolean { val solutionPyramid: MutableList<List<DerivationWrapper>> = mutableListOf() //create foundation row of solutionPyramid word.map { wordChar -> val substring = wordChar.toString() inputReader.cache[substring]?.let { return@map it } val derivations = inputReader.reversedRules[substring]?.map { rule -> DerivationOperation(rule, 0) }.orEmpty() DerivationWrapper(substring, derivations, null, null).also { inputReader.cache[it.word] = it } }.let { firstRow -> solutionPyramid.add(firstRow) } //create top rows of solutionPyramid do { val lastRow = solutionPyramid.last() val combinationPairs = (0 until lastRow.lastIndex).map { indexFirstElement -> val leftDerivationWrapper = lastRow[indexFirstElement] val rightDerivationWrapper = lastRow[indexFirstElement + 1] val substring = word.substring(indexFirstElement, indexFirstElement + solutionPyramid.size + 1) combinePairs(leftDerivationWrapper, rightDerivationWrapper, substring) } solutionPyramid.add(combinationPairs) } while (solutionPyramid.last().size != 1) return solutionPyramid.last().first().derivations.any { it.rule.variable == "S" } } /** * Combines a [leftDerivationWrapper] and [rightDerivationWrapper] into a superior [DerivationWrapper] for a given [word] */ private fun combinePairs(leftDerivationWrapper: DerivationWrapper, rightDerivationWrapper: DerivationWrapper, word: String): DerivationWrapper { inputReader.cache[word]?.let { return it } val leftDerivationWrappers = leftDerivationWrapper.getChild({it.left}, mutableListOf()) val rightDerivationWrappers = rightDerivationWrapper.getChild({it.right}, mutableListOf()) if(leftDerivationWrappers.size != rightDerivationWrappers.size) throw Exception("DerivationWrapper not balanced") val pairs = leftDerivationWrappers.zip(rightDerivationWrappers.reversed()).filterNot { it.first.derivations.isEmpty() || it.second.derivations.isEmpty() } val derivationOperations = pairs.map { derivationWrappers -> val firstProductionInputs = derivationWrappers.first.derivations.map { it.rule.variable } val secondProductionInputs = derivationWrappers.second.derivations.map { it.rule.variable } val productionPairs = firstProductionInputs.toPairList(secondProductionInputs).map { it.joinToString(" ") } val applicableRules = productionPairs.mapNotNull { productionPair -> inputReader.reversedRules[productionPair] }.flatten() applicableRules.map { DerivationOperation(it, derivationWrappers.first.word.length) } }.flatten() return DerivationWrapper(word, derivationOperations, leftDerivationWrapper, rightDerivationWrapper).also { inputReader.cache[it.word] = it } } } /** * Creates the Cartesian product of the elements of this List and a different [otherList] List. */ private fun List<String>.toPairList(otherList: List<String>) = flatMap { aItem -> otherList.map { bItem -> listOf(aItem, bItem) } }
0
Kotlin
1
2
292026d34ab9392d662730c4de26b08a93752d53
6,400
ExtendedCYK-Algorithm
Creative Commons Zero v1.0 Universal
src/aoc2022/Day11.kt
Playacem
573,606,418
false
{"Kotlin": 44779}
package aoc2022 import utils.lcm import utils.readInputText typealias WorryLevel = Long fun String.toWorryLevelOrNull(): WorryLevel? = toLongOrNull() infix fun WorryLevel.divisibleBy(divisor: Int) = this % divisor == 0L private class Monkey( val name: String, val items: MutableList<WorryLevel>, val operation: (WorryLevel) -> WorryLevel, val testDivisor: Int, val targetMonkeyIfTrue: Int, val targetMonkeyIfFalse: Int, var itemsInspected: Long = 0 ) private fun Monkey.test(a: WorryLevel): Boolean { return a divisibleBy testDivisor } private class MonkeyBuilder { var name: String = "" val items: MutableList<WorryLevel> = mutableListOf() var operation: (WorryLevel) -> WorryLevel = { it } var testDivisor: Int = -1 var targetMonkeyIfTrue: Int = -1 var targetMonkeyIfFalse: Int = -1 } private fun createOperation(s: String): (WorryLevel) -> WorryLevel { val (_, operator, op2) = s.split(" ") return when(operator) { "+" -> { old -> old + (op2.toWorryLevelOrNull() ?: old) } "*" -> { old -> old * (op2.toWorryLevelOrNull() ?: old) } else -> error("Unknown operator: $operator") } } private fun createMonkey(input: String): Monkey { val lines = input.split("\n") val builder = MonkeyBuilder() lines.map { it.trim() }.forEach { line -> when { line.startsWith("aoc2022.Monkey") -> builder.name = line.removeSuffix(":") line.startsWith("Starting items:") -> builder.items.addAll( line.split(':')[1].split(", ").map { it.trim().toWorryLevelOrNull() ?: error("") } ) line.startsWith("Operation:") -> builder.operation = createOperation(line.substringAfter("new = ")) line.startsWith("Test:") -> Regex("""^Test: divisible by (\d+)$""").find(line)?.let { builder.testDivisor = it.groupValues[1].toInt() } ?: error("no regex match for aoc2022.test!") line.startsWith("If ") -> Regex("""^If (\w+): throw to monkey (\d+)$""").find(line)?.let { val trueFalse = it.groupValues[1] val target = it.groupValues[2].toInt() when (trueFalse) { "true" -> builder.targetMonkeyIfTrue = target "false" -> builder.targetMonkeyIfFalse = target else -> error("Unknown if value: $trueFalse") } } ?: error("no regex match for if!") else -> error("Unhandled line: $line") } } return Monkey( name = builder.name, items = builder.items.toMutableList(), operation = builder.operation, testDivisor = builder.testDivisor, targetMonkeyIfTrue = builder.targetMonkeyIfTrue, targetMonkeyIfFalse = builder.targetMonkeyIfFalse ) } private fun monkeys(input: List<String>): List<Monkey> { return input.map { createMonkey(it) } } private fun playRound(monkeys: List<Monkey>, worryReductionActive: Boolean, commonModulus: Int) { monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() monkey.itemsInspected += 1 // worry increase due to inspection val worriedItem = monkey.operation(item) // monkey is done / divide by 3 val boredItem = if (worryReductionActive) { worriedItem / 3 } else { worriedItem % commonModulus } val testResult = monkey.test(boredItem) val targetIndex = if (testResult) { monkey.targetMonkeyIfTrue } else { monkey.targetMonkeyIfFalse } monkeys[targetIndex].items.add(boredItem) } } } private fun printMonkeyStatus(monkeys: List<Monkey>) { monkeys.forEach { println("${it.name}: ${it.items} [inspected: ${it.itemsInspected}]") } } fun main() { val (year, day) = 2022 to "Day11" fun part1(input: List<String>): Long { val monkeys = monkeys(input) repeat(20) { playRound(monkeys, true, 1) } printMonkeyStatus(monkeys) return monkeys.map { it.itemsInspected }.sortedDescending().take(2).reduce { acc, i -> acc * i } } fun part2(input: List<String>): Long { val monkeys = monkeys(input) val commonModulus = monkeys.map { it.testDivisor }.lcm().toInt() repeat(10000) { playRound(monkeys, false, commonModulus) println("Round ${it + 1} over") } printMonkeyStatus(monkeys) return monkeys.map { it.itemsInspected }.sortedDescending().take(2).reduce { acc, i -> acc * i } } val testInput = readInputText(year, "${day}_test").split("\n\n") val input = readInputText(year, day).split("\n\n") // aoc2022.test if implementation meets criteria from the description, like: check(part1(testInput) == 10605L) println(part1(input)) println("====") check(part2(testInput) == 2_713_310_158L) println(part2(input)) }
0
Kotlin
0
0
4ec3831b3d4f576e905076ff80aca035307ed522
5,131
advent-of-code-2022
Apache License 2.0
src/Day09.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
import kotlin.math.absoluteValue fun main() { fun bothParts(input: List<String>, ropeLength: Int): Int { // fill elements with ropeLength amount of Points set at coordinates 0, 0 var elements = List(ropeLength) { Point(0, 0) } return input.flatMap { val steps = it.split(" ")[1].toInt() val head = elements.first() val path = pathInDirection(head, Direction.from(it.split(" ")[0]), steps + 1) path.map { p -> elements = simulateRope(p, elements, emptyList()) elements.last() } }.toSet().size } val testInput = readLines("Day09_test") check(bothParts(testInput, 2) == 13) val testInput2 = readLines("Day09_test2") check(bothParts(testInput2, 10) == 36) val input = readLines("Day09") println(bothParts(input, 2)) println(bothParts(input, 10)) } fun simulateRope(head: Point, elements: List<Point>, acc: List<Point>): List<Point> { return if (elements.isEmpty()) { acc } else { val e = elements.first() if ((head.x - e.x).absoluteValue > 1 || (head.y - e.y).absoluteValue > 1) { val newPosition = e.stepIn(direction(e, head)) simulateRope(newPosition, elements.tail(), acc.plus(newPosition)) } else { acc.plus(elements) } } }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
1,377
advent-of-code-kotlin-2022
Apache License 2.0
src/day04/Day04.kt
jpveilleux
573,221,738
false
{"Kotlin": 42252}
package day04 import readInput fun main() { val testInputFileName = "./day04/Day04_test" val part1controlFileName = "./day04/Day04_part1_control" val inputFileName = "./day04/Day04" val part1controlInput = readInput(part1controlFileName) val input = readInput(inputFileName) fun part1(input: List<String>): Int { var nbrFound = 0; println("List of pairs that did not contain one or the other:") input.map { val pairArray = it.split(",") val pair1 = pairArray[0].split("-") val pair2 = pairArray[1].split("-") val pair1Part1 = pair1[0].toInt(); val pair1Part2 = pair1[1].toInt(); val pair2Part1 = pair2[0].toInt(); val pair2Part2 = pair2[1].toInt(); if (pair1Part1 in pair2Part1..pair2Part2 && pair1Part2 in pair2Part1..pair2Part2) { nbrFound++ } else if (pair2Part1 in pair1Part1..pair1Part2 && pair2Part2 in pair1Part1..pair1Part2) { nbrFound++ } else { println(pairArray) } } println("Number of pairs that contained one or the other: $nbrFound") println("-------------------------------------------------------------") return nbrFound } fun part2 (input: List<String>): Int { var nbrFound = 0; println("List of pairs that did not overlap each-other:") input.map { val pairArray = it.split(",") val pair1 = pairArray[0].split("-") val pair2 = pairArray[1].split("-") val pair1Part1 = pair1[0].toInt(); val pair1Part2 = pair1[1].toInt(); val pair2Part1 = pair2[0].toInt(); val pair2Part2 = pair2[1].toInt(); if (pair1Part1 in pair2Part1..pair2Part2 || pair1Part2 in pair2Part1..pair2Part2) { nbrFound++ } else if (pair2Part1 in pair1Part1..pair1Part2 || pair2Part2 in pair1Part1..pair1Part2) { nbrFound++ } else { println(pairArray); } } println("Number of pairs that contained one or the other: $nbrFound") println("-------------------------------------------------------------") return nbrFound } check(part1(part1controlInput) == 2) check(part2(part1controlInput) == 4) //part2(part1controlInput); part1(input) part2(input) }
0
Kotlin
0
0
5ece22f84f2373272b26d77f92c92cf9c9e5f4df
2,475
jpadventofcode2022
Apache License 2.0
src/hongwei/leetcode/playground/leetcodecba/E58LengthOfLastWord.kt
hongwei-bai
201,601,468
false
{"Java": 143669, "Kotlin": 38875}
package hongwei.leetcode.playground.leetcodecba class E58LengthOfLastWord { fun test() { val testData = arrayOf( "Hello World" to 5, " " to 0, "a " to 1 ) val onlyTestIndex = -1 testData.forEachIndexed { i, pair -> if (!(onlyTestIndex >= 0 && onlyTestIndex != i)) { val input1 = pair.first as String val expectedOutput = pair.second as Int val output = lengthOfLastWord(input1) var pass = expectedOutput == output if (pass) { println("test[$i] passed.") } else { println("test[$i] FAILED!") println("test[$i] output: $output") } } } } fun lengthOfLastWord(s: String): Int { val cs = s.toCharArray() var i = cs.size - 1 var c = 0 while (i >= 0) { while (i >= 0 && cs[i] == ' ') i-- while (i >= 0 && cs[i] != ' ') { i-- c++ } break } return c } fun lengthOfLastWord2(s: String): Int { val a = s.trim().split(" ") if (a == null || a.isEmpty()) { return 0 } return a.last().length } } /* https://leetcode.com/problems/length-of-last-word/ 58. Length of Last Word Easy 971 3004 Add to List Share Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0. A word is a maximal substring consisting of non-space characters only. Example 1: Input: s = "Hello World" Output: 5 Example 2: Input: s = " " Output: 0 Constraints: 1 <= s.length <= 104 s consists of only English letters and spaces ' '. Accepted 475,316 Submissions 1,420,184 */
0
Java
0
1
9d871de96e6b19292582b0df2d60bbba0c9a895c
1,911
leetcode-exercise-playground
Apache License 2.0
src/d05/Main.kt
cweckerl
572,838,803
false
{"Kotlin": 12921}
package d05 import java.io.File import java.util.LinkedList fun main() { fun part1(input: List<String>) { val (a, b) = input.partition { !Regex("""move \d+ from \d+ to \d+""").matches(it) } val crates = mutableMapOf<Int, LinkedList<Char>>() a.forEach { line -> line.forEachIndexed { i, c -> if (c.isLetter()) { val n = (i / 4) + 1 crates.getOrPut(n) { LinkedList<Char>() }.addLast(c) } } } b.forEach { val (n, src, dst) = Regex("""move (\d+) from (\d+) to (\d+)""").find(it)!!.destructured (0 until n.toInt()).forEach { _ -> val tmp = crates[src.toInt()]!!.removeFirst() crates[dst.toInt()]!!.addFirst(tmp) } } crates.toSortedMap().forEach { print(it.value.peekFirst()) } print('\n') } fun part2(input: List<String>) { val (a, b) = input.partition { !Regex("""move \d+ from \d+ to \d+""").matches(it) } val crates = mutableMapOf<Int, LinkedList<Char>>() a.forEach { line -> line.forEachIndexed { i, c -> if (c.isLetter()) { val n = (i / 4) + 1 crates.getOrPut(n) { LinkedList<Char>() }.addLast(c) } } } b.forEach { val (n, src, dst) = Regex("""move (\d+) from (\d+) to (\d+)""").find(it)!!.destructured val crane = LinkedList<Char>() (0 until n.toInt()).forEach { _ -> val tmp = crates[src.toInt()]!!.removeFirst() crane.addFirst(tmp) } crane.forEach { c -> crates[dst.toInt()]!!.addFirst(c) } } crates.toSortedMap().forEach { print(it.value.peekFirst()) } print('\n') } val input = File("src/d05/input").readLines() part1(input) part2(input) }
0
Kotlin
0
0
612badffbc42c3b4524f5d539c5cbbfe5abc15d3
1,967
aoc
Apache License 2.0
src/common_prefix/CommonPrefix.kt
AhmedTawfiqM
458,182,208
false
{"Kotlin": 11105}
package common_prefix //https://leetcode.com/problems/longest-common-prefix/ object CommonPrefix { private fun longestCommonPrefix(list: Array<String>): String { if (list.isEmpty()) return "" var prefix = list[0] list.forEach { while (it.indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length - 1) } } return prefix } @JvmStatic fun main(args: Array<String>) { println(longestCommonPrefix(arrayOf("flower", "flow", "flight"))) println(longestCommonPrefix(arrayOf("dog", "racecar", "car"))) println(longestCommonPrefix(arrayOf("ahmed", "sahm", "wassbah"))) } } /* * Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lower-case English letters. **/
0
Kotlin
0
1
a569265d5f85bcb51f4ade5ee37c8252e68a5a03
1,167
ProblemSolving
Apache License 2.0
src/main/kotlin/ca/voidstarzero/isbd/ParserUtils.kt
hzafar
262,218,140
false
null
package ca.voidstarzero.isbd import ca.voidstarzero.isbd.titlestatement.ast.* import ca.voidstarzero.marc.MARCField import ca.voidstarzero.marc.fieldData fun cleanInput(input: String): String { val REPLACE = 0xfffd.toChar() return input .replace(" = ", "$REPLACE=$REPLACE") .replace(" : ", "$REPLACE:$REPLACE") .replace(" / ", "$REPLACE/$REPLACE") .replace(" ; ", "$REPLACE;$REPLACE") .replace("...", "___") .removeSuffix(".") .trim() } fun prepare(input: String): List<String> { return droppedPeriods(cleanInput(input)) } fun findPeriods(input: String): List<Int> { return input.mapIndexedNotNull { i, c -> when (c) { '.' -> i else -> null } } } fun periodCombinations(positions: List<Int>): List<List<Int>> { return when (positions) { emptyList<Int>() -> listOf(emptyList()) else -> { val rest = periodCombinations( positions.subList( 1, positions.size ) ) rest.map { it.plus(positions[0]) } .plus(rest) } } } fun droppedPeriods(input: String): List<String> { return periodCombinations( findPeriods( input ) ).map { combination -> input.filterIndexed { i, _ -> i !in combination } } } // idea is we want to detect improper punctuation and // try to correct it to give a better parse. this may // ultimately not be the right way to do this. fun punctuationFixes(input: MARCField): MARCField { // if colon at subfield boundary is missing preceding space, add it in val withColonSpaces = input.subfields.map { if (it.second.matches(".*[^ ]:$".toRegex())) { val fieldData = it.second.substring(0, it.second.length - 1) + " :" Pair(it.first, fieldData) } else { it } } return MARCField( input.tag, input.indicators, withColonSpaces ) } fun usesISBD(input: MARCField): Boolean { if (input.subfields.any { it.first == 'c' } && !input.fieldData().contains(" / ")) { return false; } if (input.subfields.any { it.first == 'b' } && !input.fieldData().contains(" : | = ".toRegex())) { return false; } return true; } fun simpleParse(input: MARCField): TitleStatement { return TitleStatement( titles = listOf( Monograph( titleProper = TitleProper(input.subfields.firstOrNull{ it.first == 'a' }?.second ?: ""), otherInfo = input.subfields.filter { it.first == 'b' }.map { OtherInfo(it.second) } ) ), sors = input.subfields.filter { it.first == 'c' }.map { SOR(it.second) } ) }
2
Kotlin
0
2
16bb26858722ca818c0a9f659be1cc9d3e4e7213
2,841
isbd-parser
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2022/Day09.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2022 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.test.assertEquals object Day09 : AbstractDay() { @Test fun tests() { assertEquals(13, compute(testInput, 2)) assertEquals(6212, compute(puzzleInput, 2)) assertEquals(1, compute(testInput, 10)) assertEquals( 36, compute( """ R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20 """.trimIndent().lines(), 10 ) ) assertEquals(2522, compute(puzzleInput, 10)) } private fun compute(input: List<String>, ropeSize: Int): Int { val rope = Rope(ropeSize) val visited = mutableSetOf(rope.tail) input .flatMap { it.parse() } .forEach { direction -> rope.move(direction) visited.add(rope.tail) } return visited.size } private class Rope(private val positions: List<Position>) { constructor(ropeSize: Int) : this(List(ropeSize) { Position(0, 0) }) fun move(direction: String) { head.move(direction) for (i in 1 until positions.size) { positions[i].follow(positions[i - 1]) } } private val head: Position get() = positions.first() val tail: Position get() = positions.last().copy() } private data class Position(var x: Int, var y: Int) { fun move(direction: String) { when (direction) { "R" -> x++ "L" -> x-- "U" -> y++ "D" -> y-- } } fun follow(other: Position) { val xDiff = other.x - x val yDiff = other.y - y if (xDiff * xDiff + yDiff * yDiff > 2) { x += sign(xDiff) y += sign(yDiff) } } } private fun String.parse(): List<String> { val (direction, cnt) = split(" ") return List(cnt.toInt()) { direction } } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
2,149
aoc
Apache License 2.0
src/week2/PacificAtlantic.kt
anesabml
268,056,512
false
null
package week2 import kotlin.system.measureNanoTime class PacificAtlantic { /** * Using two boolean matrix to keep track of the grid elements that each ocean can be reached from * in the end if the grid element can be reached from both oceans we add it to the list. * Time complexity: O(n*m) * Space complexity: O(n*m) */ fun pacificAtlantic(matrix: Array<IntArray>): List<List<Int>> { if (matrix.isEmpty()) return emptyList() val output = mutableListOf<List<Int>>() val pacificVisited = Array(matrix.size) { BooleanArray(matrix[0].size) } val atlanticVisited = Array(matrix.size) { BooleanArray(matrix[0].size) } // Loop through the matrix to check the visited elements from both sides (right, left) for (i in matrix.indices) { dfs(matrix, pacificVisited, Int.MIN_VALUE, i, 0) dfs(matrix, atlanticVisited, Int.MIN_VALUE, i, matrix[0].size - 1) } // Loop through the matrix to check the visited elements from both sides (up, bottom) for (i in matrix[0].indices) { dfs(matrix, pacificVisited, Int.MIN_VALUE, 0, i) dfs(matrix, atlanticVisited, Int.MIN_VALUE, matrix.size - 1, i) } for (i in pacificVisited.indices) { for (j in pacificVisited[i].indices) { if (pacificVisited[i][j] && atlanticVisited[i][j]) { output.add(listOf(i, j)) } } } return output } private fun dfs(matrix: Array<IntArray>, visited: Array<BooleanArray>, prevHeight: Int, i: Int, j: Int) { if (i < 0 || i >= matrix.size || j < 0 || j >= matrix[0].size || matrix[i][j] < prevHeight || visited[i][j]) { return } visited[i][j] = true dfs(matrix, visited, matrix[i][j], i - 1, j) dfs(matrix, visited, matrix[i][j], i + 1, j) dfs(matrix, visited, matrix[i][j], i, j - 1) dfs(matrix, visited, matrix[i][j], i, j + 1) } /** * Same as the solution before but instead of two boolean matrix we use on integer matrix * Time complexity: O(n*m) * Space complexity: O(n*m) */ private val PACIFIC = 1 private val ATLANTIC = 2 private val BOTH = 3 fun pacificAtlantic2(matrix: Array<IntArray>): List<List<Int>> { if (matrix.isEmpty()) return emptyList() val output = mutableListOf<List<Int>>() val visited = Array(matrix.size) { IntArray(matrix[0].size) } // Loop through the matrix to check the visited elements from both sides (right, left) for (i in matrix.indices) { dfs(matrix, visited, Int.MIN_VALUE, i, 0, PACIFIC) dfs(matrix, visited, Int.MIN_VALUE, i, matrix[0].size - 1, ATLANTIC) } // Loop through the matrix to check the visited elements from both sides (up, bottom) for (i in matrix[0].indices) { dfs(matrix, visited, Int.MIN_VALUE, 0, i, PACIFIC) dfs(matrix, visited, Int.MIN_VALUE, matrix.size - 1, i, ATLANTIC) } for (i in visited.indices) { for (j in visited[i].indices) { if (visited[i][j] == 3) { output.add(listOf(i, j)) } } } return output } private fun dfs(matrix: Array<IntArray>, visited: Array<IntArray>, prevHeight: Int, i: Int, j: Int, ocean: Int) { if (i < 0 || i >= matrix.size || j < 0 || j >= matrix[0].size || matrix[i][j] < prevHeight || visited[i][j] == ocean || visited[i][j] == BOTH) { return } visited[i][j] = if (visited[i][j] > 0) BOTH else ocean dfs(matrix, visited, matrix[i][j], i - 1, j, ocean) dfs(matrix, visited, matrix[i][j], i + 1, j, ocean) dfs(matrix, visited, matrix[i][j], i, j - 1, ocean) dfs(matrix, visited, matrix[i][j], i, j + 1, ocean) } } fun main() { val input = arrayOf( intArrayOf(1, 2, 2, 3, 5), intArrayOf(3, 2, 3, 4, 4), intArrayOf(2, 4, 5, 3, 1), intArrayOf(6, 7, 1, 4, 5), intArrayOf(5, 1, 1, 2, 4) ) val pacificAtlantic = PacificAtlantic() val firstSolutionTime = measureNanoTime { println(pacificAtlantic.pacificAtlantic(input)) } val secondSolutionTime = measureNanoTime { println(pacificAtlantic.pacificAtlantic2(input)) } println("First Solution execution time: $firstSolutionTime") println("Second Solution execution time: $secondSolutionTime") }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
4,547
leetCode
Apache License 2.0
src/Day08.kt
matusekma
572,617,724
false
{"Kotlin": 119912, "JavaScript": 2024}
class Day08 { fun part1(grid: List<String>): Int { val width = grid[0].length val height = grid.size var visibleTrees = width * 2 + height * 2 - 4 for (i in 1..height - 2) { for (j in 1..width - 2) { if (visibleInRow(grid, i, j) || visibleInColumn(grid, i, j)) { visibleTrees++ } } } return visibleTrees } private fun visibleInColumn(grid: List<String>, row: Int, column: Int): Boolean { var visibleDown = true for (i in row - 1 downTo 0) { if (grid[i][column] >= grid[row][column]) { visibleDown = false break; } } var visibleUp = true for (i in row + 1 until grid.size) { if (grid[i][column] >= grid[row][column]) { visibleUp = false break; } } return visibleUp || visibleDown } private fun visibleInRow(grid: List<String>, row: Int, column: Int): Boolean { var visibleLeft = true for (j in column - 1 downTo 0) { if (grid[row][j] >= grid[row][column]) { visibleLeft = false break; } } var visibleRight = true for (j in column + 1 until grid[0].length) { if (grid[row][j] >= grid[row][column]) { visibleRight = false break; } } return visibleLeft || visibleRight } fun part2(grid: List<String>): Int { var highestScore = 0 val width = grid[0].length val height = grid.size for (i in 1..height - 2) { for (j in 1..width - 2) { val score = scoreUp(grid, i, j) * scoreDown(grid, i, j) * scoreLeft(grid, i, j) * scoreRight(grid, i, j) if (score > highestScore) highestScore = score } } return highestScore } private fun scoreUp(grid: List<String>, row: Int, column: Int): Int { var scoreUp = 0 for (i in row + 1 until grid.size) { scoreUp++ if (grid[i][column] >= grid[row][column]) { return scoreUp } } return scoreUp } private fun scoreDown(grid: List<String>, row: Int, column: Int): Int { var scoreUp = 0 for (i in row - 1 downTo 0) { scoreUp++ if (grid[i][column] >= grid[row][column]) { return scoreUp } } return scoreUp } private fun scoreLeft(grid: List<String>, row: Int, column: Int): Int { var scoreUp = 0 for (j in column - 1 downTo 0) { scoreUp++ if (grid[row][j] >= grid[row][column]) { return scoreUp } } return scoreUp } private fun scoreRight(grid: List<String>, row: Int, column: Int): Int { var scoreUp = 0 for (j in column + 1 until grid[0].length) { scoreUp++ if (grid[row][j] >= grid[row][column]) { return scoreUp } } return scoreUp } } fun main() { val day08 = Day08() val input = readInput("input08_1") println(day08.part1(input)) println(day08.part2(input)) }
0
Kotlin
0
0
744392a4d262112fe2d7819ffb6d5bde70b6d16a
3,371
advent-of-code
Apache License 2.0
src/year2023/03/Day03.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2023.`03` import readInput private const val CURRENT_DAY = "03" private data class Point( val x: Int, val y: Int, ) private data class NumberDataStore( val digits: List<DataPoint>, ) { fun digitRepresentation(): Int { return digits.joinToString("") { it.data }.toInt() } fun isNearAnyOfSymbols( symbols: Collection<Point>, ): Boolean { return digits.any { dataPoint -> dataPoint.position.neighbours().any { neighbour -> symbols.contains(neighbour) } } } override fun toString(): String { return "NumberDataStore[" + digits.joinToString(separator = "") { it.data } + "]" } } private data class DataPoint( val data: String, val position: Point, ) private fun Point.neighbours(): Set<Point> { return setOf( Point(x + 1, y), Point(x - 1, y), Point(x, y + 1), Point(x, y - 1), Point(x + 1, y + 1), Point(x - 1, y - 1), Point(x + 1, y - 1), Point(x - 1, y + 1), ) } private data class SymbolDataStore( val symbolPoint: DataPoint, ) { override fun toString(): String { return "SymbolDataStore[" + symbolPoint.data + "]" } } private fun parseIntoLineOfDataPoints(line: String, y: Int): List<DataPoint> { val allDataPoints = mutableListOf<DataPoint>() line.forEachIndexed { x, c -> if (c.isDigit()) { allDataPoints.add(DataPoint(c.toString(), Point(x, y))) } if (c.isDigit().not() && c != '.') { allDataPoints.add(DataPoint(c.toString(), Point(x, y))) } } return allDataPoints } private const val UNINITIALISED = -1 private fun List<DataPoint>.toListOfNumbers(): List<NumberDataStore> { var prevX = UNINITIALISED val resList = mutableListOf<NumberDataStore>() val buffList = mutableListOf<DataPoint>() filter { it.data.toIntOrNull() != null } .forEach { dataPoint -> val currentPos = dataPoint.position.x prevX = if (prevX == UNINITIALISED) { buffList.add(dataPoint) currentPos } else if (prevX + 1 == currentPos) { buffList.add(dataPoint) currentPos } else { resList.add(NumberDataStore(buffList.toList())) buffList.clear() buffList.add(dataPoint) currentPos } } if (buffList.isNotEmpty()) { resList.add(NumberDataStore(buffList.toList())) } return resList } private fun List<DataPoint>.toListOfSymbols(): List<SymbolDataStore> { val resList = mutableListOf<SymbolDataStore>() filter { it.data.toIntOrNull() == null } .forEach { dataPoint -> resList.add(SymbolDataStore(dataPoint)) } return resList } private fun prepareOutput( input: List<String> ): Pair<List<NumberDataStore>, Set<SymbolDataStore>> { val allNumbers = mutableListOf<NumberDataStore>() val allSymbols = mutableSetOf<SymbolDataStore>() input.mapIndexed { y, s -> parseIntoLineOfDataPoints(s, y) } .map { dataPoints -> dataPoints.toListOfNumbers() to dataPoints.toListOfSymbols() } .forEach { (numbers, symbols) -> allNumbers.addAll(numbers) allSymbols.addAll(symbols) } return allNumbers to allSymbols } fun main() { fun part1(input: List<String>): Int { val (allNumbers, allSymbols) = prepareOutput(input) val symbolPointsSet = allSymbols.map { it.symbolPoint.position }.toSet() return allNumbers .filter { numberDataStore -> numberDataStore.isNearAnyOfSymbols(symbolPointsSet) } .sumOf { numberDataStore -> numberDataStore.digitRepresentation() } } fun part2(input: List<String>): Int { val (allNumbers, allSymbols) = prepareOutput(input) val symbolPointsSet = allSymbols .filter { it.symbolPoint.data == "*" } .map { it.symbolPoint.position } .toSet() val resSum = symbolPointsSet.map { symbolPoint -> allNumbers.filter { numberDataStore -> numberDataStore.isNearAnyOfSymbols(setOf(symbolPoint)) } } .filter { it.size == 2 } .sumOf { gearList -> gearList.fold<NumberDataStore, Int>(1) { prod, item -> prod * item.digitRepresentation() } } return resSum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${CURRENT_DAY}_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 4361) val part2Test = part2(testInput) println(part2Test) check(part2Test == 467835) val input = readInput("Day$CURRENT_DAY") // Part 1 // 562922 - false val part1 = part1(input) println(part1) check(part1 == 550934) // Part 2 val part2 = part2(input) println(part2) check(part2 == 81997870) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
5,129
KotlinAdventOfCode
Apache License 2.0