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/day6/LanternFish.kt
Arch-vile
433,381,878
false
{"Kotlin": 57129}
package day6 import utils.read fun main() { solve().let { println(it) } } fun solve(): List<Long> { var startingFishes = read("./src/main/resources/day6Input.txt") .flatMap { it.split(",").map { it.toInt() } } return listOf(countFish(startingFishes, 80), countFish(startingFishes, 256)) } private fun countFish(startingFishes: List<Int>, totalDays: Int): Long { val cache = mutableMapOf<String, Long>() fun countDescendants(dayNow: Int, ticker: Int): Long { if (dayNow > totalDays) return 0 if (cache.contains("$dayNow,$ticker")) return cache["$dayNow,$ticker"]!! val firstSpawnOn = dayNow + ticker val spawnOn = (firstSpawnOn..totalDays step 7) // Count myself val result = 1 + // add all my children and their descendants spawnOn.sumOf { day -> countDescendants(day, 9) } cache["$dayNow,$ticker"] = result return result } return startingFishes.sumOf { countDescendants( 1, it) } }
0
Kotlin
0
0
4cdafaa524a863e28067beb668a3f3e06edcef96
1,026
adventOfCode2021
Apache License 2.0
src/Day07.kt
cagriyildirimR
572,811,424
false
{"Kotlin": 34697}
// Create a class representing a directory class Dir(val up: Dir? = null) { // Maps of subdirectories and files in this directory val subdirs = mutableMapOf<String, Dir>() val files = mutableMapOf<String, Long>() var sum = 0L } fun day07Part1() { // Set up the root directory val root = Dir() var currentDir = root // Read the input val input = readInput("Day07") // Process each line of the input for (i in input) { // Check if the i starts with the "cd" command when { i.startsWith("$ cd ") -> { val dir = i.substringAfter("$ cd").trim() // Check if the user is trying to navigate to the root directory currentDir = when (dir) { "/" -> root // Check if the user is trying to navigate to the parent directory ".." -> currentDir.up!! // Navigate to the specified subdirectory else -> currentDir.subdirs.getOrPut(dir) { Dir(currentDir) } } } // Check if the i starts with the "ls" command i.startsWith("$ ls") -> { // Ignore this command } else -> { // Split the i into the size and name of the file/directory val (size, name) = i.split(" ") // Check if this i describes a directory if (size == "dir") { // Create the directory and add it to the map of subdirectories currentDir.subdirs.getOrPut(name) { Dir(currentDir) } } else { // Add the file to the map of files in the current directory currentDir.files[name] = size.toLong() } } } } // Calculate the total size of the file system var result = 0L val dirs = ArrayList<Dir>() fun scan(dir: Dir): Long { var sum = 0L for (d in dir.subdirs.values) { sum += scan(d) } sum += dir.files.values.sum() if (sum <= 100000) result += sum dir.sum = sum dirs.add(dir) return sum } val total = scan(root) println(result) // Check if the total size is greater than the maximum allowed size val maxAllowed = 70000000L val needed = 30000000L dirs.sortBy { it.sum } // Calculate the amount to delete and find the directory containing the largest amount to delete val delete = total - (maxAllowed - needed) val largestDir = dirs.find { it.sum >= delete } // Print the size largestDir?.sum?.print() }
0
Kotlin
0
0
343efa0fb8ee76b7b2530269bd986e6171d8bb68
2,698
AoC
Apache License 2.0
src/Day05.kt
hanmet
573,490,488
false
{"Kotlin": 9896}
import java.util.* fun main() { fun getTestStacks(): List<Stack<Char>> { val stack1 = Stack<Char>() stack1.addAll(listOf('Z', 'N')) val stack2 = Stack<Char>() stack2.addAll(listOf('M', 'C', 'D')) val stack3 = Stack<Char>() stack3.addAll(listOf('P')) return listOf(stack1, stack2, stack3) } fun getStacks(): List<Stack<Char>> { val stack1 = Stack<Char>() stack1.addAll(listOf('W', 'D', 'G', 'B', 'H', 'R', 'V')) val stack2 = Stack<Char>() stack2.addAll(listOf('J', 'N', 'G', 'C', 'R', 'F')) val stack3 = Stack<Char>() stack3.addAll(listOf('L', 'S', 'F', 'H', 'D', 'N', 'J')) val stack4 = Stack<Char>() stack4.addAll(listOf('J', 'D', 'S', 'V')) val stack5 = Stack<Char>() stack5.addAll(listOf('S', 'H', 'D', 'R', 'Q', 'W', 'N', 'V')) val stack6 = Stack<Char>() stack6.addAll(listOf('P', 'G', 'H', 'C', 'M')) val stack7 = Stack<Char>() stack7.addAll(listOf('F', 'J', 'B', 'G', 'L', 'Z', 'H', 'C')) val stack8 = Stack<Char>() stack8.addAll(listOf('S', 'J', 'R')) val stack9 = Stack<Char>() stack9.addAll(listOf('L', 'G', 'S', 'R', 'B', 'N', 'V', 'M')) return listOf(stack1, stack2, stack3, stack4, stack5, stack6, stack7, stack8, stack9) } fun part1(input: String, stacks: List<Stack<Char>>): String { val (crates, rearrangements) = input.split("\n\n") rearrangements.split("\n").forEach { val count = it.substringBefore("from").substringAfter("move").trim().toInt() val from = it.substringAfter("from").substringBefore("to").trim().toInt() -1 val to = it.substringAfter("to").trim().toInt() -1 for (i in 0 until count) { stacks[to].push(stacks[from].peek()) stacks[from].pop() } } var result = "" stacks.forEach{ result += it.peek() } return result } fun part2(input: String, stacks: List<Stack<Char>>): String { val (crates, rearrangements) = input.split("\n\n") rearrangements.split("\n").forEach { val count = it.substringBefore("from").substringAfter("move").trim().toInt() val from = it.substringAfter("from").substringBefore("to").trim().toInt() -1 val to = it.substringAfter("to").trim().toInt() -1 val tmpStack = Stack<Char>() for (i in 0 until count) { tmpStack.push(stacks[from].peek()) stacks[from].pop() } for (i in 0 until count) { stacks[to].push(tmpStack.peek()) tmpStack.pop() } } var result = "" stacks.forEach{ result += it.peek() } return result } // test if implementation meets criteria from the description, like: val testInput = readText("Day05_test") check(part1(testInput, getTestStacks()) == "CMZ") val input = readText("Day05") println(part1(input, getStacks())) println(part2(input, getStacks())) }
0
Kotlin
0
0
e4e1722726587639776df86de8d4e325d1defa02
3,205
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day14/Day14.kt
jankase
573,187,696
false
{"Kotlin": 70242}
package day14 import Day import solve import kotlin.math.max import kotlin.math.min data class Coordinate(val x: Int, val y: Int) : Comparable<Coordinate> { companion object { fun valueOf(value: String): Coordinate { val (x, y) = value.split(",").map(String::toInt) return Coordinate(x, y) } } override fun compareTo(other: Coordinate): Int { val xCompare = x.compareTo(other.x) return if (xCompare == 0) y.compareTo(other.y) else xCompare } infix fun listTo(that: Coordinate): List<Coordinate> { return when { x == that.x -> { val startY = min(y, that.y) val endY = max(y, that.y) (startY..endY).map { Coordinate(x, it) } } y == that.y -> { val startX = min(x, that.x) val endX = max(x, that.x) (startX..endX).map { Coordinate(it, y) } } else -> error("Invalid edge for progression") } } } data class ObstaclePath(val elements: List<Coordinate>) { companion object { fun valueOf(value: String): ObstaclePath = ObstaclePath(value.split(" -> ").map(Coordinate::valueOf)) } val obstacles: List<Coordinate> get() { return when { elements.isEmpty() -> listOf() elements.size == 1 -> listOf(elements.first()) else -> { elements.windowed(2).map { (start, end) -> start listTo end } .flatten() .distinct() } } } } class Cave(private val obstacles: MutableList<Coordinate>, val useFloor: Boolean = false) { val floorY: Int = obstacles.maxOf { it.y } + 2 fun deliverSandUntilFallToAbyssOrIsNotPossibleToAdd(startCoordinate: Coordinate): Int { if (useFloor) { val minX = startCoordinate.x - floorY - 1 val maxX = startCoordinate.x + floorY + 1 obstacles.addAll(Coordinate(minX, floorY) listTo Coordinate(maxX, floorY)) } var numberOfSandPieces = 0 var currentSandPosition: Coordinate = startCoordinate while (currentSandPosition.y != Int.MAX_VALUE && !obstacles.contains(startCoordinate)) { currentSandPosition = startCoordinate currentSandPosition = performMoveUntilStableOrFall(currentSandPosition) if (currentSandPosition.y != Int.MAX_VALUE) { numberOfSandPieces++ obstacles.add(currentSandPosition) } if (numberOfSandPieces % 100 == 0) { println("Added $numberOfSandPieces pieces") } } return numberOfSandPieces } private fun performMoveUntilStableOrFall(coordinate: Coordinate): Coordinate { if (obstacles.none { it.x == coordinate.x && it.y > coordinate.y }) return Coordinate(coordinate.x, Int.MAX_VALUE) val bellowObstacle = obstacles.filter { it.x == coordinate.x && it.y > coordinate.y }.minOf { it } val coordinateAfterFall = bellowObstacle.copy(y = bellowObstacle.y - 1) return when { obstacles.none { it.x == coordinateAfterFall.x - 1 && it.y == coordinateAfterFall.y + 1 } -> performMoveUntilStableOrFall(Coordinate(coordinateAfterFall.x - 1, coordinateAfterFall.y + 1)) obstacles.none { it.x == coordinateAfterFall.x + 1 && it.y == coordinateAfterFall.y + 1 } -> performMoveUntilStableOrFall(Coordinate(coordinateAfterFall.x + 1, coordinateAfterFall.y + 1)) else -> coordinateAfterFall } } } class Day14 : Day(14, 2022, "Regolith Reservoir") { override fun part1(): Int { val cave = Cave( input.asSequence() .map(ObstaclePath::valueOf) .map(ObstaclePath::obstacles) .flatten() .distinct().sorted().toMutableList() ) return cave.deliverSandUntilFallToAbyssOrIsNotPossibleToAdd(Coordinate(500, 0)) } override fun part2(): Int { val cave = Cave( input.asSequence() .map(ObstaclePath::valueOf) .map(ObstaclePath::obstacles) .flatten() .distinct().sorted().toMutableList(), true ) return cave.deliverSandUntilFallToAbyssOrIsNotPossibleToAdd(Coordinate(500, 0)) } } fun main() { solve<Day14> { day14demo part1 24 part2 93 } } private val day14demo = """ 498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9 """.trimIndent()
0
Kotlin
0
0
0dac4ec92c82a5ebb2179988fb91fccaed8f800a
4,738
adventofcode2022
Apache License 2.0
src/main/kotlin/adventofcode/year2021/Day10SyntaxScoring.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2021 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day10SyntaxScoring(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val lines by lazy { input.lines() } private val bracketMap = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>' ) private val scoreMapPartOne = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137 ) private val scoreMapPartTwo = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4 ) private fun List<Any>.middle() = this[size / 2] override fun partOne() = lines .mapNotNull { line -> val stack = ArrayDeque<Char>() line.forEach { char -> when (char) { in setOf('(', '[', '{', '<') -> stack.add(char) else -> if (char != bracketMap[stack.removeLast()]) return@mapNotNull char } } null } .sumOf { char -> scoreMapPartOne[char]!! } override fun partTwo() = lines .mapNotNull { line -> val stack = ArrayDeque<Char>() line.forEach { char -> when (char) { in setOf('(', '[', '{', '<') -> stack.add(char) else -> if (char != bracketMap[stack.removeLast()]) return@mapNotNull null } } stack.reversed().map { openingBracket -> bracketMap[openingBracket]!! } } .map { completion -> completion.fold(0L) { acc, char -> acc * 5 + scoreMapPartTwo[char]!! } } .sorted() .middle() }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,697
AdventOfCode
MIT License
src/aoc22/Day05.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc22.day05 import lib.Collections.headTail import lib.Solution import lib.Strings.ints typealias StackIndex = Int data class Crate(private val char: Char) { override fun toString(): String = "$char" companion object { fun parse(char: Char): Crate? = Crate(char).takeIf { char.isUpperCase() } } } data class CrateStack(private val arrayDeque: ArrayDeque<Crate> = ArrayDeque()) { fun copy() = CrateStack(ArrayDeque(this.arrayDeque)) fun push(crate: Crate) = arrayDeque.addLast(crate) fun pushN(crates: List<Crate>) = arrayDeque.addAll(crates) fun pop(): Crate = arrayDeque.removeLast() fun popN(n: Int): List<Crate> = arrayDeque.takeLast(n).also { repeat(it.size) { arrayDeque.removeLast() } } fun top(): Crate = arrayDeque.last() } data class Cargo( private val stackCount: Int, private val stacks: List<CrateStack> = List(stackCount) { CrateStack() }, ) { fun copy() = Cargo(stackCount, stacks.map(CrateStack::copy)) fun push(stackIndex: StackIndex, crate: Crate) = stacks[stackIndex].push(crate) fun pushN(stackIndex: StackIndex, crates: List<Crate>) = stacks[stackIndex].pushN(crates) fun pop(stackIndex: StackIndex): Crate = stacks[stackIndex].pop() fun popN(stackIndex: StackIndex, n: Int) = stacks[stackIndex].popN(n) fun topCrates(): List<Crate> = stacks.map(CrateStack::top) companion object { fun parse(stackCount: Int, stackLines: List<String>) = Cargo(stackCount).apply { stackLines.forEach { line -> line.forEachIndexed { idx, char -> Crate.parse(char)?.let { crate -> push(idx / 4, crate) } } } } } } data class Step(val quantity: Int, val from: StackIndex, val to: StackIndex) { companion object { fun parse(line: String): Step { val parts = line.split(" ") val quantity = parts[1].toInt() val from = parts[3].toInt() - 1 val to = parts[5].toInt() - 1 return Step(quantity, from, to) } } } data class Procedure(val steps: List<Step>) { fun run(block: (step: Step) -> Unit) = steps.forEach(block) companion object { fun parse(procedureLines: List<String>) = Procedure(procedureLines.map { line -> Step.parse(line) }) } } data class Input(val cargo: Cargo, val procedure: Procedure) typealias Output = Cargo private val solution = object : Solution<Input, Output>(2022, "Day05") { override fun parse(input: String): Input { val (cargoLines, procedureLines) = input.split("\n\n").map { it.lines() } val (stackIndexLine, stackLines) = cargoLines.reversed().headTail() val stackCount = checkNotNull(stackIndexLine).ints().max() return Input(Cargo.parse(stackCount, stackLines), Procedure.parse(procedureLines)) } override fun format(output: Output): String = output.topCrates().joinToString("") override fun part1(input: Input): Output { val cargo: Cargo = input.cargo.copy() input.procedure.run { (quantity, from, to) -> repeat(quantity) { val crate = cargo.pop(from) cargo.push(to, crate) } } return cargo } override fun part2(input: Input): Output { val cargo: Cargo = input.cargo.copy() input.procedure.run { (quantity, from, to) -> val crates = cargo.popN(from, quantity) cargo.pushN(to, crates) } return cargo } } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
3,433
aoc-kotlin
Apache License 2.0
src/Challenge2.kt
occmundial
517,843,760
false
{"Kotlin": 28105}
/* * Challenge #2 * * Date: 15/08/2022 * Difficulty: Medium * Create a function that translate from natural text to Morse code and vice versa. * - Must be automatically detect what type it is and perform the conversion. * - In Morse, dash "—", dot ".", a space " " between letters or symbols, and two spaces between words " " are supported. * - The supported morse alphabet will be the one shown in https://es.wikipedia.org/wiki/Código_morse. */ lateinit var naturalDictionary: Map<String, String> var morseDictionary = mutableMapOf<String, String>() fun main() { createDictionaries() val naturalText = "<NAME>" val morseText = ".... --- .-.. .- ---- . -.-. ---" println(decoder(naturalText)) println(decoder(morseText)) } private fun createDictionaries() { naturalDictionary = mapOf( "A" to ".-", "N" to "-.", "0" to "-----", "B" to "-...", "Ñ" to "--.--", "1" to ".----", "C" to "-.-.", "O" to "---", "2" to "..---", "CH" to "----", "P" to ".--.", "3" to "...--", "D" to "-..", "Q" to "--.-", "4" to "....-", "E" to ".", "R" to ".-.", "5" to ".....", "F" to "..-.", "S" to "...", "6" to "-....", "G" to "--.", "T" to "-", "7" to "--...", "H" to "....", "U" to "..-", "8" to "---..", "I" to "..", "V" to "...-", "9" to "----.", "J" to ".---", "W" to ".--", "." to ".-.-.-", "K" to "-.-", "X" to "-..-", "," to "--..--", "L" to ".-..", "Y" to "-.--", "?" to "..--..", "M" to "--", "Z" to "--..", "\"" to ".-..-.", "/" to "-..-." ) naturalDictionary.forEach { morseDictionary[it.value] = it.key } } private fun decoder(input: String): String { var output = "" if (input.contains(Regex("[a-zA-Z0-9]"))) { // texto output = getMorse(input) } else if (input.contains(".") || input.contains("-")) { // morse output = getNatural(input) } return output } private fun getMorse(input: String): String { var index = 0 var ch = false var output = "" input.uppercase().forEach { character -> if (!ch && character.toString() != " ") { val next = index + 1 if (character.toString() == "C" && next < input.length && input.uppercase()[next].toString() == "H") { output += naturalDictionary["CH"] ch = true } else { output += naturalDictionary[character.toString()] } output += " " } else { if (!ch) { output += " " } ch = false } index++ } return output } private fun getNatural(input: String): String { var output = "" input.split(" ").forEach { word -> word.split(" ").forEach { symbol -> if (symbol.isNotEmpty()) { output += morseDictionary[symbol] } } output += " " } return output }
1
Kotlin
0
1
f09ba0a03666ab9cf362adab62b897aa4e399171
2,994
Kotlin-Weekly-Challenge
The Unlicense
src/main/kotlin/org/vitrivr/cottontail/database/index/vaplus/MarksGenerator.kt
frankier
278,349,990
true
{"Kotlin": 1020644, "Dockerfile": 280}
package org.vitrivr.cottontail.database.index.vaplus import kotlin.math.max import kotlin.math.min import kotlin.math.pow object MarksGenerator { /** */ const val EPSILON = 10E-9 /** * Get marks. */ fun getNonUniformMarks(data: Array<DoubleArray>, marksPerDimension: IntArray): Array<DoubleArray> { val marks = getEquidistantMarks(data, marksPerDimension).map { val copy = it.copyOf(it.size + 1) copy[copy.size - 1] = copy[copy.size - 2] + EPSILON copy }.toTypedArray() /** * Iterate over dimensions. * Get marks of d-th dimension. * Do k-means. */ marksPerDimension.indices.map { d -> var delta: Double var deltaBar = Double.POSITIVE_INFINITY do { // k-means delta = deltaBar // pseudocode line 3 /** * Iterate over marks of d-th dimension. * Iterate over data. * Check if data point is in interval of marks. * Calculate mean of data points in interval (rj). * Return list of mean of every interval in d (rjs). */ val rjs = Array(marks[d].size - 1) { c -> var rj = 0.0 var rjAll = 0.0 var count = 0 var countAll = 0 data.forEach { if (it[d] >= marks[d][c] && it[d] < marks[d][c + 1]) { rj += it[d] count += 1 } rjAll += it[d] countAll += 1 } if (count == 0) { rjAll / countAll } else { rj / count } } // pseudocode line 7 /** * Iterate over marks of d-th dimension. * Adjust marks (moving along distance, no long equidistance) * The mark at position c is adjusted with "(first mean value + second mean value) / 2" */ (1 until marks[d].size - 1).forEach { c -> marks[d][c] = (rjs[c - 1] + rjs[c]) / 2 } // pseudocode line 8 /** * Iterate over marks of d-th dimension. * Iterate over data. * Check if data point is in interval of (new) marks. * If so, apply formula: * tmp = (difference between data point and c).pow(2) = euclidean distance * if distance > 0.999 then break */ deltaBar = (0 until marks[d].size - 1).sumByDouble { c -> var tmp = 0.0 data.forEach { if (it[d] >= marks[d][c] && it[d] < marks[d][c + 1]) { tmp += (it[d] - rjs[c]).pow(2) } } tmp } } while ((delta - deltaBar) / delta < 0.999) } return marks } /** * Create marks per dimension (equally spaced). */ fun getEquidistantMarks(data: Array<DoubleArray>, marksPerDimension: IntArray): Array<DoubleArray> { val min = getMin(data) val max = getMax(data) return Array(min.size) { i -> DoubleArray(marksPerDimension[i] * 2) { it * (max[i] - min[i]) / (marksPerDimension[i] * 2 - 1) + min[i] } } } /** * Get vector ([DoubleArray]) which values are minimal. */ private fun getMin(data: Array<DoubleArray>): DoubleArray { val out = DoubleArray(data.first().size) { Double.MAX_VALUE } for (array in data) { for (i in array.indices) { out[i] = min(out[i], array[i]) } } return out } /** * Get vector ([DoubleArray]) which values are maximal. */ private fun getMax(data: Array<DoubleArray>): DoubleArray { val out = DoubleArray(data.first().size) { Double.MIN_VALUE } for (array in data) { for (i in array.indices) { out[i] = max(out[i], array[i]) } } return out } }
0
Kotlin
0
0
e4ec66eaf014bb8ea4399cc7ea54062f16cf0c60
4,487
cottontaildb
MIT License
src/week-day-1/Sqrt.kt
luix
573,258,926
false
{"Kotlin": 7897, "Java": 232}
package week1 import kotlin.math.sqrt /** * Sqrt (easy) * Problem Statement * Given a non-negative integer x, return the square root of x rounded * down to the nearest integer. The returned integer should be non-negative as well. * * You must not use any built-in exponent function or operator. * * For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python. * * Example 1: * * Input: x = 8 * Output: 2 * Explanation: The square root of 8 is 2.8284, and since we need to * return the floor of the square root (integer), hence we returned 2. * Example 2: * * Input: x = 4 * Output: 2 * Explanation: The square root of 4 is 2. * Example 3: * * Input: x = 2 * Output: 1 * Explanation: The square root of 2 is 1.414, and since we need to return * the floor of the square root (integer), hence we returned 1. */ /* public int mySqrt(int x) { if (x < 2) return x; // return x if it is 0 or 1 int left = 2, right = x / 2; // initialize left and right pointers int pivot; long num; // use long to store result of pivot * pivot to prevent overflow while (left <= right) { // binary search for the square root pivot = left + (right - left) / 2; // find the middle element num = (long) pivot * pivot; if (num > x) right = pivot - 1; // if pivot * pivot is greater than x, set right to pivot - 1 else if (num < x) left = pivot + 1; // if pivot * pivot is less than x, set left to pivot + 1 else return pivot; // if pivot * pivot is equal to x, return pivot } return right; // return right after the loop } */ class Sqrt { fun sqrt(x: Int): Int { if (x < 2) return x var left = 2 var right = x / 2 var pivot: Int // use Double to store result of pivot * pivot to prevent overflow var num: Double while (left <= right) { // binary search for the square root pivot = left + (right - left) / 2 // find the middle element num = (pivot * pivot).toDouble() if (num > x) { // if pivot * pivot is greater than x, set right to pivot - 1 right = pivot - 1 } else if (num < x) { // if pivot * pivot is less than x, set left to pivot + 1 left = pivot + 1 } else { // if pivot * pivot is equal to x, return pivot return pivot } } // return right after the loop return right } } fun main() { val solution = Sqrt() val tests = listOf(8, 4, 2, 3, 15, 16, 32, 64, 128, 256, 512, 1024, 4096) tests.forEach { // assert(solution.sqrt(it) == sqrt(it.toDouble()).toInt()) println("The square root of $it is: ${solution.sqrt(it)}") } }
0
Kotlin
0
0
8e9b605950049cc9a0dced9c7ba99e1e2458e53e
2,823
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2023/Day21.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 21 - Step Counter * Problem Description: http://adventofcode.com/2023/day/21 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day21/ */ package com.ginsberg.advent2023 class Day21(input: List<String>) { private val gardenMap: Array<CharArray> = input.map { it.toCharArray() }.toTypedArray() private val start: Point2D = gardenMap.mapIndexedNotNull { y, row -> if ('S' in row) Point2D(row.indexOf('S'), y) else null }.first() fun solvePart1(goal: Int): Int = countSteps(goal).values.count { it % 2 == 0 } // Thanks https://github.com/villuna // @see https://github.com/villuna/aoc23/wiki/A-Geometric-solution-to-advent-of-code-2023,-day-21 fun solvePart2(stepCount: Int): Long { val steps = countSteps() val oddCorners = steps.count { it.value % 2 == 1 && it.value > 65 }.toLong() val evenCorners = steps.count { it.value % 2 == 0 && it.value > 65 }.toLong() val evenBlock = steps.values.count { it % 2 == 0 }.toLong() val oddBlock = steps.values.count { it % 2 == 1 }.toLong() val n: Long = ((stepCount.toLong() - (gardenMap.size / 2)) / gardenMap.size) val even: Long = n * n val odd: Long = (n + 1) * (n + 1) return (odd * oddBlock) + (even * evenBlock) - ((n + 1) * oddCorners) + (n * evenCorners) } private fun countSteps(max: Int = gardenMap.size): Map<Point2D, Int> = buildMap { val queue = ArrayDeque<Pair<Point2D, Int>>().apply { add(start to 0) } while (queue.isNotEmpty()) { queue.removeFirst().let { (location, distance) -> if (location !in this && distance <= max) { this[location] = distance queue.addAll( location .cardinalNeighbors() .filter { it !in this } .filter { gardenMap.isSafe(it) } .filter { gardenMap[it] != '#' } .map { it to distance + 1 } ) } } } } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
2,244
advent-2023-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/PathSum2.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 113. Path Sum II * @see <a href="https://leetcode.com/problems/path-sum-ii/">Source</a> */ fun interface PathSum2 { operator fun invoke(root: TreeNode?, targetSum: Int): List<List<Int>> } /** * Approach: Depth First Traversal | Recursion */ class PathSum2DFS : PathSum2 { override operator fun invoke(root: TreeNode?, targetSum: Int): List<List<Int>> { val pathsList: MutableList<List<Int>> = ArrayList() val pathNodes: MutableList<Int> = ArrayList() recurseTree(root, targetSum, pathNodes, pathsList) return pathsList } private fun recurseTree( node: TreeNode?, remainingSum: Int, pathNodes: MutableList<Int>, pathsList: MutableList<List<Int>>, ) { if (node == null) { return } // Add the current node to the path's list pathNodes.add(node.value) // Check if the current node is a leaf and also, if it // equals our remaining sum. If it does, we add the path to // our list of paths if (remainingSum == node.value && node.left == null && node.right == null) { pathsList.add(ArrayList(pathNodes)) } else { // Else, we will recurse on the left and the right children recurseTree(node.left, remainingSum - node.value, pathNodes, pathsList) recurseTree(node.right, remainingSum - node.value, pathNodes, pathsList) } // We need to pop the node once we are done processing ALL of it's // subtrees. pathNodes.removeAt(pathNodes.size - 1) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,245
kotlab
Apache License 2.0
src/main/kotlin/g2701_2800/s2713_maximum_strictly_increasing_cells_in_a_matrix/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2701_2800.s2713_maximum_strictly_increasing_cells_in_a_matrix // #Hard #Array #Dynamic_Programming #Sorting #Binary_Search #Matrix #Memoization // #2023_08_01_Time_1141_ms_(100.00%)_Space_110.2_MB_(54.55%) import java.util.concurrent.atomic.AtomicInteger class Solution { fun maxIncreasingCells(mat: Array<IntArray>): Int { val n = mat.size val m = mat[0].size val map: MutableMap<Int, MutableList<IntArray>> = HashMap() for (i in 0 until n) { for (j in 0 until m) { val `val` = mat[i][j] if (!map.containsKey(`val`)) { map.put(`val`, ArrayList()) } map[`val`]!!.add(intArrayOf(i, j)) } } val memo = Array(n) { IntArray(m) } val res = IntArray(n + m) val max = AtomicInteger() map.keys.stream().sorted().forEach { a: Int -> for (pos in map[a]!!) { val i = pos[0] val j = pos[1] memo[i][j] = res[i].coerceAtLeast(res[n + j]) + 1 max.set(max.get().coerceAtLeast(memo[i][j])) } for (pos in map[a]!!) { val i = pos[0] val j = pos[1] res[n + j] = res[n + j].coerceAtLeast(memo[i][j]) res[i] = res[i].coerceAtLeast(memo[i][j]) } } return max.get() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,438
LeetCode-in-Kotlin
MIT License
src/main/kotlin/g1101_1200/s1161_maximum_level_sum_of_a_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1101_1200.s1161_maximum_level_sum_of_a_binary_tree // #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_05_25_Time_445_ms_(87.50%)_Space_97.1_MB_(75.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 sums: MutableList<Int> = ArrayList() fun maxLevelSum(root: TreeNode?): Int { sums = ArrayList() find(root, 1) var ans = 1 var maxv = Int.MIN_VALUE for (i in sums.indices) { if (sums[i] > maxv) { maxv = sums[i] ans = i + 1 } } return ans } private fun find(root: TreeNode?, height: Int) { if (root == null) { return } if (sums.size < height) { sums.add(root.`val`) } else { sums[height - 1] = sums[height - 1] + root.`val` } find(root.left, height + 1) find(root.right, height + 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,181
LeetCode-in-Kotlin
MIT License
src/Day10.kt
undermark5
574,819,802
false
{"Kotlin": 67472}
fun main() { fun part1(input: List<String>): Long { var cycleCount = 0 var xRegister = 1 val cyclesOfInterest = mutableListOf(20,60,100,140,180,220) var sum = 0L input.forEach { if (it.startsWith("noop")) cycleCount++ if (it.startsWith("addx")) { cycleCount += 2 val currentCycle = if (cyclesOfInterest.isNotEmpty() && cycleCount >= cyclesOfInterest.peek()) { cyclesOfInterest.pop() } else { 0 } sum += xRegister * currentCycle xRegister += it.split(" ").last().toInt() } } return sum } fun part2(input: List<String>): String { var cycleCount = 0 var xRegister = 1 val cyclesOfInterest = mutableListOf(20,60,100,140,180,220) var sum = 0L val screen = List(6) {MutableList(40) {'.'} } var drawingCoords = 0 to 0 var isAdding = false var instructionPointer = 0 while (drawingCoords != 6 to 0) { if (drawingCoords.second in (xRegister -1)..(xRegister+1)) { screen[drawingCoords] = '#' } var (y, x) = drawingCoords x++ if (x >= 40) { x = 0 y++ } drawingCoords = y to x val instruction = input[instructionPointer] if (isAdding) { xRegister += instruction.split(" ").last().toInt() instructionPointer++ isAdding = false } else { if (instruction.startsWith("noop")) { instructionPointer++ } else { isAdding = true } } } input.forEach { if (it.startsWith("noop")) cycleCount++ if (it.startsWith("addx")) { cycleCount += 2 val currentCycle = if (cyclesOfInterest.isNotEmpty() && cycleCount >= cyclesOfInterest.peek()) { cyclesOfInterest.pop() } else { 0 } sum += xRegister * currentCycle xRegister += it.split(" ").last().toInt() } } if (drawingCoords.second in (xRegister -1)..(xRegister+1)) { screen[drawingCoords] = '#' } var (y, x) = drawingCoords x++ if (x >= 40) { x = 0 y++ } return screen.joinToString("\n") { it.joinToString("") } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") println(part1(testInput)) check(part1(testInput) == 13140L) check(part2(testInput) == """##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######.....""") val input = readInput("Day10") println(part1(input)) // println(part2(testInput)) println(part2(input)) }
0
Kotlin
0
0
e9cf715b922db05e1929f781dc29cf0c7fb62170
3,246
AoC_2022_Kotlin
Apache License 2.0
src/main/kotlin/g2601_2700/s2658_maximum_number_of_fish_in_a_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2658_maximum_number_of_fish_in_a_grid // #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find // #2023_07_21_Time_269_ms_(80.00%)_Space_45.4_MB_(80.00%) class Solution { fun findMaxFish(grid: Array<IntArray>): Int { val visited = Array(grid.size) { BooleanArray(grid[0].size) } val dir = arrayOf( intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0) ) fun isValid(x: Int, y: Int) = x in (0..grid.lastIndex) && y in (0..grid[0].lastIndex) && grid[x][y] != 0 && !visited[x][y] fun dfs(x: Int, y: Int): Int { if (!isValid(x, y)) { return 0 } visited[x][y] = true var total = grid[x][y] for (d in dir) { total += dfs(x + d[0], y + d[1]) } return total } var res = 0 for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] != 0) res = maxOf(res, dfs(i, j)) } } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,179
LeetCode-in-Kotlin
MIT License
src/Day01.kt
brste
577,510,164
false
{"Kotlin": 2640}
fun main() { fun topK(input: List<String>, k: Int) : List<Int> { val caloriesOfElves = mutableListOf<Int>() var sum = 0 for (line in input) { if (line.isBlank()) { caloriesOfElves.add(sum) sum = 0 } else { sum += line.toInt() } } // empty line at the end -> we don't need to do a last caloriesOfElves.ad(sum) return caloriesOfElves.sortedDescending().take(k) } fun part1(input: List<String>): Int = topK(input, 1).first() fun part2(input: List<String>): Int = topK(input, 3).sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
e8d6604575021fef95ad3d31cc8d61e929ac9efa
879
aoc-2022-kotlin
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/medium/Merge.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 56. 合并区间 * * 以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。 */ class Merge { companion object { @JvmStatic fun main(args: Array<String>) { Merge().merge(arrayOf(intArrayOf(1, 3), intArrayOf(2, 6), intArrayOf(8, 10), intArrayOf(15, 18))).forEach { println("${it[0]}, ${it[1]}") } Merge().merge(arrayOf(intArrayOf(1, 4), intArrayOf(0, 4))).forEach { println("${it[0]}, ${it[1]}") } } } // 输入:intervals = [[1,3],[2,6],[8,10],[15,18]] // 输出:[[1,6],[8,10],[15,18]] // 解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. fun merge(intervals: Array<IntArray>): Array<IntArray> { intervals.sortWith(Comparator { o1, o2 -> (o1?.get(0) ?: 0) - (o2?.get(0) ?: 0) }) val result = arrayListOf<IntArray>() intervals.forEach { val start = it[0] val end = it[1] if (result.isEmpty() || result[result.size - 1][1] < start) { result.add(intArrayOf(start, end)) } else { result[result.size - 1][1] = Math.max(result[result.size - 1][1], end) } } return result.toTypedArray() } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,506
daily_algorithm
Apache License 2.0
src/net/sheltem/aoc/y2022/Day11.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2022 import net.sheltem.common.MathOperation import net.sheltem.common.lastAsInt class Day11 : Day<Long>(10605, 2713310158) { override suspend fun part1(input: List<String>) = input.windowed(6, 7) .map { it.toMonkey() } .playRounds(20) .map { it.inspections } .sortedDescending() .take(2).let { (one, two) -> one * two } override suspend fun part2(input: List<String>): Long = input.windowed(6, 7) .map { it.toMonkey(false) } .playRounds(10000) .map { it.inspections } .sortedDescending() .take(2).let { (one, two) -> one * two } } suspend fun main() { Day11().run() } private fun List<Monkey>.playRounds(rounds: Int): List<Monkey> { repeat(rounds) { for (monkey in this) { monkey.takeTurn(this) } } return this } private fun List<String>.toMonkey(calm: Boolean = true): Monkey { val startingItems = this[1].substringAfter(":").split(",").map { it.trim() }.map { it.toLong() }.toMutableList() val operation = this[2] .substringAfter("= old ") .split(" ") .let { (op, second) -> Operation(MathOperation.fromSign(op), second.toLongOrDefault(-1L)) } val test = this.takeLast(3).toTest() return Monkey(startingItems, operation, test, calm) } private fun String.toLongOrDefault(default: Long) = toLongOrNull() ?: default private fun List<String>.toTest(): Test = Test( this[0].lastAsInt(" ").toLong(), this[1].lastAsInt(" "), this[2].lastAsInt(" "), ) private class Operation(val type: MathOperation, val value: Long) { fun execute(input: Long): Long { val secondOperand = if (value.toInt() == -1) input else value return when (type) { MathOperation.ADD -> input + secondOperand MathOperation.MULTIPLY -> input * secondOperand else -> input } } } private class Test(val divisor: Long, val successTarget: Int, val failureTarget: Int) { fun execute(inputVal: Long): Int = if ((inputVal % divisor).toInt() == 0) successTarget else failureTarget } private class Monkey(var items: MutableList<Long> = mutableListOf(), val op: Operation, val test: Test, val calm: Boolean) { var inspections = 0L fun takeTurn(monkeys: List<Monkey>) { val mod = monkeys.map { it.test.divisor }.reduce { acc, number -> acc * number } for (item in items) { inspections++ val (value, target) = inspect(item, mod) monkeys[target].items.add(value) } items = mutableListOf() } private fun inspect(item: Long, mod: Long): Pair<Long, Int> = op.execute(item) .let { if (calm) it / 3L else it % mod} .let { newValue -> newValue to test.execute(newValue) } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,837
aoc
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day17.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2022 import se.saidaspen.aoc.util.* import kotlin.math.absoluteValue fun main() = Day17.run() object Day17 : Day(2022, 17) { private var dash = "####" private var plus = ".#.\n###\n.#." private var lThing = "..#\n..#\n###" private var iThing = "#\n#\n#\n#" private var square = "##\n##" private val rocks = listOf(dash, plus, lThing, iThing, square).map { block -> toMap(block).filter { it.value == '#' }.map { it.key }.toSet()} private val vinds = input.e() private val up = P(0, -1) private val down = P(0, 1) private val left = P(-1, 0) private val right = P(1, 0) private const val leftWallX = -3 private const val rightWallX = 5 private const val bottom = 4 override fun part1(): Any { var vindI = 0 val map = mutableMapOf<Point, Char>() for (x in leftWallX..rightWallX) { map[P(x, bottom)] = '-' } var movingRock: Set<Point> = getRock(0, bottom) var nextRock = 1 var doVind = true var stoppedRocks = 0 while (stoppedRocks < 2023) { if (doVind) { val vind = vinds[vindI] vindI = (vindI + 1) % vinds.size val afterMoving = if (vind == '>') { move(movingRock, 1, right) } else { move(movingRock, 1, left) } if (afterMoving.map { it.x }.max() < rightWallX && afterMoving.map { it.x }.min() > leftWallX && !afterMoving.any { map.containsKey(it) } ) { movingRock = afterMoving } } else { val afterMoving = move(movingRock, 1, down) if (afterMoving.any { map.containsKey(it) }) { movingRock.forEach { map[it] = '#' } val rockType = nextRock nextRock = (nextRock + 1) % 5 val top = map.keys.map { it.second }.min() movingRock = getRock(rockType, top) stoppedRocks += 1 } else { movingRock = afterMoving } } doVind = !doVind } return map.keys.map { it.second }.min() * -1 + 2 } private fun getRock(t: Int, bottom: Int): Set<P<Int, Int>> { var rock = rocks[t % 5] val yMax = rock.map { it.second }.max() val bottomOfRockShouldBe = bottom - 4 val distanceToFloor = (yMax - bottomOfRockShouldBe).absoluteValue rock = if (bottomOfRockShouldBe < yMax) { move(rock, distanceToFloor, up) } else { move(rock, distanceToFloor, down)} return rock } private fun move(rock: Set<Pair<Int, Int>>, distance: Int, dir: Pair<Int, Int>): Set<P<Int, Int>> { return rock.map { it + (dir * distance) }.toSet() } override fun part2(): Any { val vinds = input.e() var vindI = 0 val map = mutableMapOf<Point, Char>() for (x in leftWallX..rightWallX) { map[P(x, bottom)] = '-' } var movingRock: Set<Point> = getRock(0, bottom) var nextRock = 1 var doVind = true var heightDiffs = "0" while (true) { if (doVind) { val vind = vinds[vindI] vindI = (vindI + 1) % Day17.vinds.size val afterMoving = if (vind == '>') { move(movingRock, 1, right) } else { move(movingRock, 1, left) } if (afterMoving.map { it.x }.max() < rightWallX && afterMoving.map { it.x }.min() > leftWallX && !afterMoving.any { map.containsKey(it) } ) { movingRock = afterMoving } } else { val afterMoving = move(movingRock, 1, down) if (afterMoving.any { map.containsKey(it) }) { val prevTop = map.keys.map { it.second }.min() movingRock.forEach { map[it] = '#' } val rockType = nextRock nextRock = (nextRock + 1) % 5 val top = map.keys.map { it.second }.min() val heightDiff = (top - prevTop).absoluteValue heightDiffs += heightDiff if (heightDiffs.length == 5001) { val newHeightDiffs = heightDiffs.drop(1000) var found = false var len = 20 var cycle = "" while (!found) { val needle = newHeightDiffs.substring(0, len) if (newHeightDiffs.substring(len).startsWith(needle)) { found = true cycle = needle continue } len += 1 } val lastIndex = heightDiffs.lastIndexOf(cycle) val whereInCycle = heightDiffs.length - (cycle.length + lastIndex) val heightAt5000 = heightDiffs.substring(1, 5000 + 1).e().sumOf { it.digitToInt() }.toLong() val heightIncreaseOneCycle = cycle.e().sumOf { it.digitToInt() }.toLong() val cycleB = len.toLong() val times = (1000000000000L - 5000L) / cycleB val getsUsTo = 5000L + times * cycleB val left = 1000000000000L - getsUsTo val currHeight = heightAt5000 + heightIncreaseOneCycle * times val heightAfter = (cycle + cycle).substring(whereInCycle, whereInCycle + left.toInt()).map { it.digitToInt() }.sum() val totalHeight = currHeight + heightAfter return totalHeight.toString() } movingRock = getRock(rockType, top) } else { movingRock = afterMoving } } doVind = !doVind } } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
6,307
adventofkotlin
MIT License
src/main/kotlin/ru/timakden/aoc/year2023/Day18.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2023 import ru.timakden.aoc.util.Point import ru.timakden.aoc.util.Polygon import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 18: <NAME>](https://adventofcode.com/2023/day/18). */ object Day18 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2023/Day18") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Long { var currentPoint = Point(0, 0) val trench = mutableListOf(currentPoint) input.forEach { s -> val digPlan = DigPlan.fromString(s) currentPoint = when (digPlan.direction) { 'R' -> currentPoint.moveRight(digPlan.meters) 'D' -> currentPoint.moveDown(digPlan.meters) 'L' -> currentPoint.moveLeft(digPlan.meters) 'U' -> currentPoint.moveUp(digPlan.meters) else -> currentPoint } trench += currentPoint } val polygon = Polygon(trench.distinct()) return (polygon.area + polygon.perimeter / 2 + 1).toLong() } @OptIn(ExperimentalStdlibApi::class) fun part2(input: List<String>): Long { var currentPoint = Point(0, 0) val trench = mutableListOf(currentPoint) input.forEach { s -> val digPlan = DigPlan.fromString(s) val meters = digPlan.color.substringAfter('#').dropLast(1).hexToInt() currentPoint = when (digPlan.color.last()) { '0' -> currentPoint.moveRight(meters) '1' -> currentPoint.moveDown(meters) '2' -> currentPoint.moveLeft(meters) '3' -> currentPoint.moveUp(meters) else -> currentPoint } trench += currentPoint } val polygon = Polygon(trench.distinct()) return (polygon.area + polygon.perimeter / 2 + 1).toLong() } private data class DigPlan(val direction: Char, val meters: Int, val color: String) { companion object { fun fromString(input: String): DigPlan { val direction = input.first() val meters = input.substringAfter(' ').substringBefore(' ').toInt() val color = input.substringAfter('(').substringBefore(')') return DigPlan(direction, meters, color) } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,516
advent-of-code
MIT License
src/main/kotlin/day15/day15.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package day15 import main.utils.measureAndPrint import main.utils.scanInts import utils.* import java.lang.Integer.min import kotlin.math.abs import kotlin.math.max fun main() { val test = readLines( """ Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3 """.trimIndent() ) val input = readFile("day15") class Grid(val cells: MutableMap<Coord, Char> = mutableMapOf()) { fun print() { val zX = cells.keys.maxOf { it.x } val aX = cells.keys.minOf { it.x } val zY = cells.keys.maxOf { it.y } val aY = cells.keys.minOf { it.y } println("X = $aX - $zX, Y=$aY - $zY") for (y in aY..zY) { print("%4d ".format(y)) for (x in aX..zX) { val pos = Coord(x, y) print(cells.getOrDefault(pos, '.')) } println() } } } data class Sensor(val pos: Coord, val beacon: Coord) { val distance = pos.chebyshevDistance(beacon) fun isInRange(loc: Coord) = this.pos.chebyshevDistance(loc) <= distance fun deadSpots(row: Int): IntRange? { val distanceToRow = abs(row - pos.y) return if (distanceToRow <= distance) { val diff = distance - distanceToRow (pos.x - diff)..(pos.x + diff) } else { null } } } fun printGrid(sensors: List<Sensor>) { val grid = mutableMapOf<Coord, Char>() sensors.forEach { sensor -> grid[sensor.pos] = 'S' grid[sensor.beacon] = 'B' } for (sensor in sensors) { val start = sensor.pos.x - sensor.distance val end = sensor.pos.x + sensor.distance val rows = (sensor.pos.y - sensor.distance)..(sensor.pos.y + sensor.distance) for (y in rows) { for (x in start..end) { val loc = Coord(x, y) if (sensor.isInRange(loc)) { if (!grid.containsKey(loc)) { grid[loc] = '#' } } } } } Grid(grid).print() } fun loadSensors(input: List<String>): List<Sensor> { return input.map { line -> line.scanInts().let { (a,b,c,d) -> Sensor(Coord(a,b), Coord(c,d)) } } } fun calcDeadSpots(sensors: List<Sensor>, row: Int): Int { val beacons = sensors.map { it.beacon } .filter { it.y == row } .map { it.x } .toSet() val deadSpots = sensors.filter { it.pos.y <= row + it.distance && it.pos.y >= row - it.distance }.mapNotNull { it.deadSpots(row) } .flatMap { r -> beacons.flatMap { beacon -> r.exclude(beacon) } } return joinRanges(deadSpots).sumOf { it.last - it.first + 1 } } fun calcBeaconFrequency(sensors: List<Sensor>, size: Int): Long { val range = 0..size val beacons = sensors.map { it.beacon }.toSet() val minRow = sensors.minOfOrNull { min(it.pos.y, it.beacon.y) - it.distance } ?: 0 val maxRow = sensors.maxOfOrNull { max(it.pos.y, it.beacon.y) + it.distance } ?: size val rows = max(minRow, 0)..min(maxRow, size) println("rows = $rows") for (row in rows) { val deadSpots = sensors .mapNotNull { it.deadSpots(row) } .filter { it.first in range || it.last in range } .sortedBy { it.first } val combined = joinRanges(deadSpots) .map { max(it.first, 0)..min(it.last, size) } for (index in 1..combined.lastIndex) { val a = combined[index - 1] val b = combined[index] val searchRange = (a.last + 1) until b.first for (x in searchRange) { if (x in range) { val loc = Coord(x, row) val found = !beacons.contains(loc) && sensors.filter { it.pos.y <= row + it.distance && it.pos.y >= row - it.distance }.none { it.isInRange(loc) } if (found) { return loc.x.toLong() * size.toLong() + loc.y.toLong() } } } } } return error("Hidden Beacon not found") } fun calcSolution1(input: List<String>, row: Int, print: Boolean): Int { val sensors = loadSensors(input) if (print) { printGrid(sensors) } return calcDeadSpots(sensors, row) } fun calcSolution2(input: List<String>, size: Int, print: Boolean): Long { val sensors = loadSensors(input) if (print) { printGrid(sensors) } return calcBeaconFrequency(sensors, size) } fun part1() { val testResult = calcSolution1(test, 10, true) println("Part 1 Test Answer = $testResult") check(testResult == 26) { "Expected 26 not $testResult" } val result = measureAndPrint("Part 1 Time:") { calcSolution1(input, 2000000, false) } println("Part 1 Answer = $result") check(result == 4502208) { "Expected 4502208 not $result" } } fun part2() { val testResult = measureAndPrint("Part 2 Test Time:") { calcSolution2(test, 4000000, true) } println("Part 2 Test Answer = $testResult") check(testResult == 56000011L) { "Expected 56000011 not $testResult" } val result = measureAndPrint("Part 2 Time:") { calcSolution2(input, 4000000, false) } println("Part 2 Answer = $result") check(result == 13784551204480L) { "Expected 13784551204480 not $result" } } println("Day - 15") part1() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
5,982
aoc-2022-in-kotlin
Apache License 2.0
src/Day10.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
private val CYCLE_INDEX = listOf(20, 60, 100, 140, 180, 220) class Day10(private val input: List<String>) { private val command = input.map { getCommand(it) } fun solvePart1() = getSignalStrength() private fun getSignalStrength(): Int { var registerX = 1 var sb = StringBuffer() var cycle = 0 for (index in 1.. input.size) { val currentCommand = command[index - 1] sb.append(executeCycle(++cycle, registerX)) //ADD X takes 2 cycles if (currentCommand is Command.addX) { sb.append(executeCycle(++cycle, registerX)) registerX += currentCommand.xValue } } println(sb.toString()) return 1 } fun executeCycle(cycle: Int, registerX: Int): StringBuffer { val tempBuffer = StringBuffer() tempBuffer.append(if (listOf(registerX-1, registerX, registerX+1).contains((cycle-1)%40)) "##" else "..") if (listOf(40, 80, 120, 160, 200, 240).contains(cycle)) { tempBuffer.append("\n") } return tempBuffer } } fun main() { val day = "day10_input" println(Day10(readInput(day)).solvePart1()) } fun getCommand(command: String): Command { val commandSplit = command.substringBefore(" ") return if (commandSplit == "noop") { Command.Noop } else { Command.addX(command.substringAfter(" ").toInt()) } } sealed class Command { object Noop: Command() data class addX(val xValue: Int): Command() }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
1,553
advent22
Apache License 2.0
08.kts
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
import java.util.* val scanner = Scanner(System.`in`) val instructions = scanner.nextLine() scanner.nextLine() val map = HashMap<String, Pair<String, String>>() val node = Regex("[A-Z]+") while (scanner.hasNext()) { val item = node.findAll(scanner.nextLine()).map { it.value }.toList() map.put(item[0], Pair(item[1], item[2])) } var steps = 0 var n = "AAA" while (n != "ZZZ") { if (instructions[steps % instructions.length] == 'L') n = map[n]!!.first else n = map[n]!!.second steps++ } val nn = ArrayList(map.keys.filter { it.endsWith('A') }) var steps2 = ArrayList<Int>() for (i in nn.indices) steps2.add(0) for (i in nn.indices) { while (!nn[i].endsWith('Z')) { nn[i] = if (instructions[steps2[i] % instructions.length] == 'L') map[nn[i]]!!.first else map[nn[i]]!!.second steps2[i]++ } } fun gcd(a: Long, b: Long): Long { if (b == 0L) return a return gcd(b, a % b) } fun lcm(a: Long, b: Long): Long { return a / gcd(a, b) * b } var result2: Long = 1 for (s in steps2) result2 = lcm(result2, s.toLong()) println("$steps $result2")
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
1,105
aoc2023
MIT License
src/Day01.kt
fmborghino
573,233,162
false
{"Kotlin": 60805}
/* * Hindsight notes. * - There are much more concise ways to re-express this as chained functions. */ fun main() { fun log(message: Any?) { // println(message) } fun part1(input: List<String>): Int { var elfIndex = 1 var maxElfIndex = 0 var maxCalories = 0 var calories = 0 input.forEach { if (it.isNotEmpty()) { log(it) calories += it.toInt() } else { log("Done with elf #$elfIndex with $calories calories") if (calories > maxCalories) { maxCalories = calories maxElfIndex = elfIndex } calories = 0 elfIndex++ } } log("Done with elf #$elfIndex") log("Winner is elf $maxElfIndex with $maxCalories calories") return maxCalories } fun part2(input: List<String>): Int { var elfIndex = 1 var calories = 0 val caloriesList = mutableListOf<Int>() input.forEach { if (it.isNotEmpty()) { log(it) calories += it.toInt() } else { log("Done with elf #$elfIndex with $calories calories") caloriesList.add(calories) calories = 0 elfIndex++ } } caloriesList.add(calories) log("Done with elf #$elfIndex") val totalCalories = caloriesList.sorted().takeLast(3) log("take(3) ${caloriesList.sorted().take(3).joinToString()}") log("takeLast(3) ${totalCalories.joinToString()} for a total of ${totalCalories.sum()}") return totalCalories.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test.txt") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01.txt") println(part1(input)) println(part2(input)) check(part1(input) == 68467) check(part2(input) == 203420) }
0
Kotlin
0
0
893cab0651ca0bb3bc8108ec31974654600d2bf1
2,100
aoc2022
Apache License 2.0
src/Day17.kt
felldo
572,233,925
false
{"Kotlin": 76496}
fun main() { val rocks = buildList { add(arrayOf(Pair(0, 0), Pair(0, 1), Pair(0, 2), Pair(0, 3))) add(arrayOf(Pair(0, 1), Pair(1, 0), Pair(1, 1), Pair(1, 2), Pair(2, 1))) add(arrayOf(Pair(0, 2), Pair(1, 2), Pair(2, 0), Pair(2, 1), Pair(2, 2))) add(arrayOf(Pair(0, 0), Pair(1, 0), Pair(2, 0), Pair(3, 0))) arrayOf(Pair(0, 0), Pair(0, 1), Pair(1, 0), Pair(1, 1)) } fun part1(input: List<String>): Int { val jets = input[0] val chamber = mutableListOf<Array<Boolean>>() chamber.add(Array(7) { true }) var totalMoves = 0 for (t in 0 until 2022) { val rock = rocks[t % rocks.size] var height = chamber.indexOfLast { it.contains(true) } + rock.maxOf { it.first } + 4 while (chamber.size < height + 1) { chamber.add(Array(7) { false }) } var left = 2 var falling = true while (falling) { falling = false val isLeft = jets[totalMoves++ % jets.length] == '<' if (isLeft) { if (left >= 1) { var movesLeft = true for (p in rock) { val newCoordination = Pair(height - p.first, left + p.second - 1) if (chamber[newCoordination.first][newCoordination.second]) { movesLeft = false } } if (movesLeft) { left-- } } } else { if (left + rock.maxOf { it.second } < 6) { var movesRight = true for (p in rock) { val newCoordination = Pair(height - p.first, left + p.second + 1) if (chamber[newCoordination.first][newCoordination.second]) { movesRight = false } } if (movesRight) { left++ } } } var drops = true for (p in rock) { val newCoordination = Pair(height - p.first - 1, p.second + left) if (chamber[newCoordination.first][newCoordination.second]) { drops = false } } if (drops) { height-- falling = true } } for (p in rock) { chamber[height - p.first][p.second + left] = true } } return chamber.indexOfLast { it.contains(true) } } val input = readInput("Day17") println(part1(input)) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
2,944
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/P021_AmicableNumber.kt
perihanmirkelam
291,833,878
false
null
/** * P21 - Amicable Numbers * * Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). * If d(a) = b and d(b) = a, where a ≠ b, * then a and b are an amicable pair and each of a and b are called amicable numbers. * * For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. * The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. * * Evaluate the sum of all the amicable numbers under 10000. */ fun p21() { val pairs: MutableList<Pair<Int, Int>> = mutableListOf((0 to 0)) val boundary = 10000 var n: Int; var dn: Int for (i in 1..boundary) { n = i dn = 0 for (j in 1 until n) if (n % j == 0) dn += j pairs.add(n to dn) } fun d(x: Int): Int = pairs[x].second var a: Int; var b: Int; var sum = 0 for (i in pairs) { a = i.first b = i.second if (a < boundary && b < boundary && a != b && a == d(b) && b == d(a)) sum += a } println("A21: $sum") }
0
Kotlin
1
3
a24ac440871220c87419bfd5938f80dc22a422b2
1,076
ProjectEuler
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2017/2017-03.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2017 import com.github.ferinagy.adventOfCode.Coord2D import kotlin.collections.Map import kotlin.collections.contains import kotlin.collections.filter import kotlin.collections.mutableMapOf import kotlin.collections.set import kotlin.collections.sumOf fun main() { println("Part1:") println(part1(testInput1)) println(part1(input)) println() println("Part2:") println(part2(testInput1)) println(part2(input)) } private fun part1(input: Int): Int { var counter = 2 return solve( isDone = { it == input }, getValue = { _, _ -> counter++ } ).first } private fun part2(input: Int): Int { return solve( isDone = { it >= input }, getValue = { grid, position -> position.adjacent(includeDiagonals = true).filter { it in grid }.sumOf { grid[it]!! } } ).second } private fun solve( isDone: (Int) -> Boolean, getValue: (Map<Coord2D, Int>, Coord2D) -> Int ): Pair<Int, Int> { val grid = mutableMapOf<Coord2D, Int>() val center = Coord2D(0, 0) grid[center] = 1 var direction = Coord2D(1, 0) var position = center var sideSize = 1 var sideNum = 0 var sideStep = 0 while (!isDone(grid.getOrDefault(position, 0))) { position += direction grid[position] = getValue(grid, position) sideStep++ if (sideStep == sideSize) { sideStep = 0 direction = direction.turnLeft() sideNum++ } if (sideNum == 2) { sideNum = 0 sideSize++ } } return (position.distanceTo(center)) to grid[position]!! } private fun Coord2D.turnLeft() = copy(x = y, y = -x) private const val testInput1 = 1024 private const val input = 368078
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,819
advent-of-code
MIT License
src/y2022/Day08.kt
Yg0R2
433,731,745
false
null
package y2022 import DayX import common.Grid import common.Grid.Companion.toGrid class Day08 : DayX<Int>(21, 8) { override fun part1(input: List<String>): Int { val grid = input.initializeGrid() var visibleTreesCount = 0 for (row: Int in grid.getRowIndices()) { for (column: Int in grid.getColumnIndices(row)) { if (grid.isVisibleFromEdge(row, column)) { visibleTreesCount++ } } } return visibleTreesCount } override fun part2(input: List<String>): Int { val grid = input.initializeGrid() var maxScenicScore = 0 for (row: Int in grid.getRowIndices()) { for (column: Int in grid.getColumnIndices(row)) { val scenicScore = grid.getScenicScore(row, column) if (scenicScore > maxScenicScore) { maxScenicScore = scenicScore } } } return maxScenicScore } companion object { fun Grid<Int>.getScenicScore(row: Int, column: Int): Int { val currentTree = get(row, column) return (column - 1 downTo 0).takeUntil { get(row, it) < currentTree }.count() * // LEFT IntRange(column + 1, getRowSize() - 1).takeUntil { get(row, it) < currentTree }.count() * // RIGHT (row - 1 downTo 0).takeUntil { get(it, column) < currentTree }.count() * // UP IntRange(row + 1, getColumnSize(row) - 1).takeUntil { get(it, column) < currentTree } .count() // DOWN } private fun List<String>.initializeGrid(): Grid<Int> = toGrid { it.digitToInt() } private fun Grid<Int>.isVisibleFromEdge(row: Int, column: Int): Boolean { if ((row == 0) || (row == getRowSize() - 1) || (column == 0) || (column == getColumnSize(row) - 1)) { return true } val currentTree = get(row, column) return IntRange(0, column - 1).none { get(row, it) >= currentTree } || // LEFT IntRange(column + 1, getRowSize() - 1).none { get(row, it) >= currentTree } || // RIGHT IntRange(0, row - 1).none { get(it, column) >= currentTree } || // UP IntRange(row + 1, getColumnSize(row) - 1).none { get(it, column) >= currentTree } // DOWN } private inline fun <T> Iterable<T>.takeUntil(predicate: (T) -> Boolean): List<T> { val list = mutableListOf<T>() for (item in this) { list.add(item) if (!predicate(item)) { break } } return list } } }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
2,776
advent-of-code
Apache License 2.0
app/src/test/java/com/zwq65/unity/algorithm/unionfind/LeetCode947.kt
Izzamuzzic
95,655,850
false
{"Kotlin": 449365, "Java": 17918}
package com.zwq65.unity.algorithm.unionfind import org.junit.Test /** * ================================================ * <p> * <a href="https://leetcode-cn.com/problems/most-stones-removed-with-same-row-or-column/">947. 移除最多的同行或同列石头</a>. * Created by NIRVANA on 2019/7/15. * Contact with <<EMAIL>> * ================================================ */ class LeetCode947 { @Test fun test() { val array = arrayOf(intArrayOf(0, 0), intArrayOf(0, 2), intArrayOf(1, 1), intArrayOf(2, 0), intArrayOf(2, 2)) val number = removeStones(array) print("number:$number") } private fun removeStones(stones: Array<IntArray>): Int { var N = stones.size var dsu = UF(20000) for (stone in stones) dsu.union(stone[0], stone[1] + 10000) var seen = HashSet<Int>() for (stone in stones) seen.add(dsu.find(stone[0])) return N - seen.size } class UF(size: Int) { private var parent = IntArray(size) init { //初始化:parent指向本身 for (i in 0 until size) { parent[i] = i } } fun find(x: Int): Int { return if (x == parent[x]) { x } else { parent[x] = find(parent[x]) find(parent[x]) } } fun union(x: Int, y: Int) { parent[find(x)] = parent[find(y)] } } }
0
Kotlin
0
0
98a9ad7bb298d0b0cfd314825918a683d89bb9e8
1,544
Unity
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2023/day18/day18.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day18 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val digPlan = parseDigPlan(inputFile.bufferedReader().readLines()) println("The trench can hold ${calculateTrenchVolume(buildTrenchEdge(digPlan))} cubic meters") } data class DigPlanEntry(val direction: Direction, val distance: Long) fun parseDigPlan(lines: Iterable<String>): List<DigPlanEntry> = lines .mapNotNull { line -> Regex("([UDLR]) ([0-9]+) \\(#([0-9a-fA-F]{6})\\)").find(line) } .map { match -> DigPlanEntry( direction = when (val dirStr = match.groups[1]!!.value) { "U" -> Direction.NORTH "D" -> Direction.SOUTH "L" -> Direction.WEST "R" -> Direction.EAST else -> throw IllegalArgumentException("Unexpected direction: $dirStr") }, distance = match.groups[2]!!.value.toLong(), ) } fun parseDigPlanV2(lines: Iterable<String>): List<DigPlanEntry> = lines .mapNotNull { line -> Regex("([UDLR]) ([0-9]+) \\(#([0-9a-fA-F]{6})\\)").find(line) } .map { match -> DigPlanEntry( direction = when (val lastHexDigit = match.groups[3]!!.value[5]) { '0' -> Direction.EAST '1' -> Direction.SOUTH '2' -> Direction.WEST '3' -> Direction.NORTH else -> throw IllegalArgumentException("Unexpected hex digit: $lastHexDigit") }, distance = match.groups[3]!!.value.dropLast(1).toLong(radix = 16), ) } const val TRENCH = '#' const val LEVEL_TERRAIN = '.' const val NORTH_EAST_CORNER = '7' const val NORTH_WEST_CORNER = 'F' const val SOUTH_WEST_CORNER = 'L' const val SOUTH_EAST_CORNER = 'J' const val VERTICAL_EDGE = '|' fun buildTrenchEdge(digPlan: List<DigPlanEntry>): Map<LongCoord, Char> { var currentPos = LongCoord(0, 0) var previousDirection: Direction? = null val map = mutableMapOf(currentPos to TRENCH) for ((direction, distance) in digPlan) { map[currentPos] = getCornerCharacter(previousDirection, direction) currentPos = currentPos.move(direction, distance) previousDirection = direction } map[currentPos] = getCornerCharacter(previousDirection, digPlan.first().direction) return map } private fun getCornerCharacter(previousDirection: Direction?, nextDirection: Direction) = when (previousDirection) { Direction.NORTH -> when (nextDirection) { Direction.NORTH -> throw IllegalStateException("Cannot go north -> north") Direction.SOUTH -> throw IllegalStateException("Cannot go north -> south") Direction.WEST -> NORTH_EAST_CORNER Direction.EAST -> NORTH_WEST_CORNER } Direction.SOUTH -> when (nextDirection) { Direction.NORTH -> throw IllegalStateException("Cannot go south -> north") Direction.SOUTH -> throw IllegalStateException("Cannot go south -> south") Direction.WEST -> SOUTH_EAST_CORNER Direction.EAST -> SOUTH_WEST_CORNER } Direction.WEST -> when (nextDirection) { Direction.NORTH -> SOUTH_WEST_CORNER Direction.SOUTH -> NORTH_WEST_CORNER Direction.WEST -> throw IllegalStateException("Cannot go west -> west") Direction.EAST -> throw IllegalStateException("Cannot go west -> east") } Direction.EAST -> when (nextDirection) { Direction.NORTH -> SOUTH_EAST_CORNER Direction.SOUTH -> NORTH_EAST_CORNER Direction.WEST -> throw IllegalStateException("Cannot go east -> west") Direction.EAST -> throw IllegalStateException("Cannot go east -> east") } null -> nextDirection.char } fun calculateTrenchVolume(trenchEdge: Map<LongCoord, Char>, debug: Boolean = false): Long { var size = 0L val coords = trenchEdge.keys.sortByYX() val groupedCoords = coords.groupBy { it.y } var previousY = coords.first().y val verticals = mutableSetOf<Long>() for ((y, cornersInLine) in groupedCoords.entries.sortedBy { it.key }) { if (debug) print("y = $y size = $size\n") val yDiff = y - previousY if (yDiff > 1) { val skippedLines = yDiff - 1 val volumeInLine = sumEvenPairDifferences(verticals) val count = skippedLines * volumeInLine if (debug) println(" skipped $skippedLines of volume $volumeInLine = $count") size += count } val line: List<Pair<Long, Char>> = cornersInLine .map { it.x to (trenchEdge[it] ?: throw IllegalStateException("No corner found for $it")) } .plus( verticals .filter { x -> cornersInLine.none { it.x == x } } .map { x -> x to VERTICAL_EDGE } ) .sortedBy { it.first } var isInside = false var previousCorner: Char? = null var previousX = line.first().first - 1 if (debug) println( (coords.minOf { it.x }..coords.maxOf { it.x }) .map { x -> line.firstOrNull { it.first == x }?.second ?: LEVEL_TERRAIN } .joinToString("") { it.toString() } ) for ((x, char) in line) { val xDiff = x - previousX val count = when { isVerticalEdge(char) -> { val wasInside = isInside isInside = !isInside if (wasInside) xDiff else 1 } isHorizontalEdge(char) -> throw IllegalStateException("Should never encounter horizontal edge but did at ($x,$y)") isEastCornerSameAsWest(char, previousCorner) -> { previousCorner = char xDiff } isEastCornerDifferentThanWest(char, previousCorner) -> { isInside = !isInside previousCorner = char xDiff } isCorner(char) -> { previousCorner = char if (isInside) xDiff else 1 } isLevelTerrain(char) -> throw IllegalStateException("Should never encounter level terrain but did at ($x,$y)") else -> throw IllegalArgumentException("Unexpected character: $char") } size += count if (debug) print(" $char @ x = $previousX -> $x = $count inside = $isInside\n") when (char) { NORTH_WEST_CORNER, NORTH_EAST_CORNER -> verticals.add(x) SOUTH_EAST_CORNER, SOUTH_WEST_CORNER -> verticals.remove(x) } previousX = x } if (debug) println() previousY = y } return size } internal fun sumEvenPairDifferences(numbers: Set<Long>): Long = numbers.asSequence() .sorted() .zipWithNext() .withIndex() .filter { it.index % 2 == 0 } .sumOf { it.value.second - it.value.first + 1 } private fun isLevelTerrain(char: Char) = char == LEVEL_TERRAIN private fun isVerticalEdge(char: Char) = char == Direction.NORTH.char || char == Direction.SOUTH.char || char == VERTICAL_EDGE private fun isHorizontalEdge(char: Char) = char == Direction.WEST.char || char == Direction.EAST.char private fun isCorner(char: Char) = char == NORTH_WEST_CORNER || char == NORTH_EAST_CORNER || char == SOUTH_EAST_CORNER || char == SOUTH_WEST_CORNER private fun isEastCornerSameAsWest(char: Char, previousCorner: Char?) = (char == NORTH_EAST_CORNER && previousCorner == NORTH_WEST_CORNER) || (char == SOUTH_EAST_CORNER && previousCorner == SOUTH_WEST_CORNER) private fun isEastCornerDifferentThanWest(char: Char, previousCorner: Char?) = (char == NORTH_EAST_CORNER && previousCorner == SOUTH_WEST_CORNER) || (char == SOUTH_EAST_CORNER && previousCorner == NORTH_WEST_CORNER)
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
8,463
advent-of-code
MIT License
src/main/kotlin/days/Day4.kt
sicruse
434,002,213
false
{"Kotlin": 29921}
package days class Day4 : Day(4) { private val plays: List<Int> by lazy { inputList.first().split(",").map { it.toInt() } } private val boards: List<Board> by lazy { inputString // split the file at blank lines .split("\\n\\n".toRegex()) // skip the first record .drop(1) .map { it -> Board(it) } } class Board(text: String) { private val body: Array<Array<Int>> private var index: MutableSet<Int> private val rowMatchCount = IntArray(5) private val colMatchCount = IntArray(5) private var won: Boolean = false init { body = bodyFromText(text.split(":\n").last()) index = body.flatMap { it.toSet() }.toMutableSet() } companion object { fun bodyFromText(text: String): Array<Array<Int>> = text .split("\\n".toRegex()) .map { it .replace(" "," ") .trim() .split(" ") .map { it.toInt() } .toTypedArray() }.toTypedArray() } fun match(number: Int): Pair<Int, Int> { val row = body.indexOfFirst { it.contains(number) } val col = body[row].indexOfFirst { it == number } return Pair(row, col) } fun score(number: Int): Int? { if (won) return null else if (index.contains(number)) { val (row, col) = match(number) index.remove(number) rowMatchCount[row]++ colMatchCount[col]++ if (rowMatchCount.contains(5) || colMatchCount.contains(5)) { won = true return number * index.fold(0) { acc, num -> acc + num } } } return null } } override fun partOne(): Any { for (number in plays) { val score = boards.fold(0) { acc, board -> val win = board.score(number) if (win != null) acc + win else acc } if (score > 0) return score } return 0 } override fun partTwo(): Any { var winningScore = 0 for (number in plays) { val score = boards.fold(0) { acc, board -> val win = board.score(number) if (win != null) acc + win else acc } if (score > 0) winningScore = score } return winningScore } }
0
Kotlin
0
0
172babe6ee67a86a7893f8c9c381c5ce8e61908e
2,750
aoc-kotlin-2021
Creative Commons Zero v1.0 Universal
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day22.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year21 import com.grappenmaker.aoc.Point3D import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.rangeTo import com.grappenmaker.aoc.volumeLong fun PuzzleSet.day22() = puzzle(day = 22) { // This took me way too long to come up with // My initial idea of cutting ended up too slow, since after you cut a region once, // you need to cut all of those new regions, and so on, for all the OFF instructions... // Yeah, that is slow... it grows exponentially data class Step(val positive: Boolean, val xRange: IntRange, val yRange: IntRange, val zRange: IntRange) val originalSteps = inputLines.map { l -> val (on, coords) = l.split(" ") val (xr, yr, zr) = coords.split(",").map { val (s, e) = it.drop(2).split("..").map(String::toInt) s..e } Step(on == "on", xr, yr, zr) } fun IntRange.overlap(other: IntRange) = (maxOf(first, other.first)..minOf(last, other.last)).takeIf { !it.isEmpty() } fun Step.overlap(other: Step) = xRange.overlap(other.xRange)?.let { x -> yRange.overlap(other.yRange)?.let { y -> zRange.overlap(other.zRange)?.let { Step(!positive, x, y, it) } } } fun solve(steps: List<Step>): String { val known = mutableListOf<Step>() var score = 0L val update = { (pos, x, y, z): Step -> score += (Point3D(x.first, y.first, z.first)..Point3D(x.last, y.last, z.last)) .volumeLong.let { if (pos) it else -it } } steps.forEach { curr -> known += known.mapNotNull { e -> e.overlap(curr)?.also(update) } if (curr.positive) known += curr.also(update) } return score.s() } val partialRange = -50..50 partOne = solve(originalSteps.mapNotNull { it.copy( xRange = it.xRange.overlap(partialRange) ?: return@mapNotNull null, yRange = it.yRange.overlap(partialRange) ?: return@mapNotNull null, zRange = it.zRange.overlap(partialRange) ?: return@mapNotNull null ) }) partTwo = solve(originalSteps) }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,159
advent-of-code
The Unlicense
src/iii_conventions/MyDate.kt
omegaphoenix
115,461,312
false
null
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { private val daysInWeek = 7 override fun compareTo(other: MyDate) = when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } operator fun plus(interval: TimeInterval) = when (interval) { TimeInterval.DAY -> this.nextDay() TimeInterval.WEEK -> this.nextDayHelper(daysInWeek) else -> MyDate(year + 1, month, dayOfMonth) } private fun nextDayHelper(n: Int): MyDate = when { n <= 0 -> this else -> this.nextDay().nextDayHelper(n - 1) } operator fun plus(interval: RepeatedTimeInterval) = when (interval.ti) { TimeInterval.DAY -> this.nextDayHelper(interval.n) TimeInterval.WEEK -> this.nextDayHelper(daysInWeek * interval.n) else -> MyDate(year + interval.n, month, dayOfMonth) } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) enum class TimeInterval { DAY, WEEK, YEAR } operator fun TimeInterval.times(n: Int) = RepeatedTimeInterval(this, n) class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> { operator fun contains(d: MyDate) = start <= d && endInclusive >= d override operator fun iterator() : Iterator<MyDate> { return DateIterator(start, endInclusive) } } class DateIterator(var date: MyDate, val end: MyDate) : Iterator<MyDate> { override operator fun next(): MyDate { val prev = date date = date.nextDay() return prev } override operator fun hasNext() = date <= end } class RepeatedTimeInterval(val ti: TimeInterval, val n: Int)
0
Kotlin
0
0
bfb21969455b154ab078b2d9a43683ae8298085c
1,816
kotlin-koans
MIT License
src/main/kotlin/g0801_0900/s0803_bricks_falling_when_hit/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0803_bricks_falling_when_hit // #Hard #Array #Matrix #Union_Find #2023_03_16_Time_742_ms_(100.00%)_Space_53.4_MB_(100.00%) class Solution { private val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) fun hitBricks(grid: Array<IntArray>, hits: Array<IntArray>): IntArray { val cols = grid[0].size for (hit in hits) { val x = hit[0] val y = hit[1] grid[x][y]-- } val row = 0 for (col in 0 until cols) { dfs(row, col, grid) } val res = IntArray(hits.size) for (i in hits.indices.reversed()) { val x = hits[i][0] val y = hits[i][1] grid[x][y]++ if (grid[x][y] == 1 && isConnectedToRoof(x, y, grid)) { res[i] = dfs(x, y, grid) - 1 } } return res } private fun dfs(i: Int, j: Int, grid: Array<IntArray>): Int { if (i < 0 || i >= grid.size || j < 0 || j >= grid[0].size || grid[i][j] != 1) { return 0 } grid[i][j] = 2 return ( dfs(i + 1, j, grid) + dfs(i - 1, j, grid) + dfs(i, j + 1, grid) + dfs(i, j - 1, grid) + 1 ) } private fun isConnectedToRoof(i: Int, j: Int, grid: Array<IntArray>): Boolean { if (i == 0) { return true } for (d in dirs) { val x = i + d[0] val y = j + d[1] if (x >= 0 && x < grid.size && y >= 0 && y < grid[0].size && grid[x][y] == 2) { return true } } return false } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,732
LeetCode-in-Kotlin
MIT License
src/main/kotlin/offer/31.kt
Eynnzerr
621,254,277
false
null
package offer import java.util.LinkedList class Solution31 { fun validateStackSequences(pushed: IntArray, popped: IntArray): Boolean { // 核心思路:构造辅助栈 val stack = LinkedList<Int>() var pushedCount = 0 for (poppedNum in popped) { if (stack.isEmpty() || stack.peek() != poppedNum) { // 若当前待弹出数字不在栈顶,则将pushed数组中一直压人辅助栈,直到当前待弹出数字压在栈顶 // 若当前可用数字已全部入栈,则说明压栈弹栈序列无法对应 if (pushedCount == pushed.size) return false while (stack.peek() != poppedNum && pushedCount <= pushed.size) { stack.push(pushed[pushedCount++]) } stack.pop() } else { // 在栈顶,直接弹出 stack.pop() } } return true } fun validateStackSequences2(pushed: IntArray, popped: IntArray): Boolean { // 力扣题解大佬的做法,与上面做法不同之处在于让pushed入栈 val stack = LinkedList<Int>() var i = 0 pushed.forEach { stack.push(it) while (stack.isNotEmpty() && stack.peek() == popped[i]) { stack.pop() i ++ } } return stack.isEmpty() } } fun main() { val solution = Solution31() print(solution.validateStackSequences2(intArrayOf(1,2,3,4,5), intArrayOf(4,5,3,2,1))) }
0
Kotlin
0
0
0327df84200444e1e4ef4b7d7a9f8779e8d7443f
1,574
leetcode-kotlin
MIT License
kotlin/src/com/daily/algothrim/leetcode/WordPattern.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 290. 单词规律 * * 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 * * 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 * * 示例1: * * 输入: pattern = "abba", str = "dog cat cat dog" * 输出: true * 示例 2: * * 输入:pattern = "abba", str = "dog cat cat fish" * 输出: false * 示例 3: * * 输入: pattern = "aaaa", str = "dog cat cat dog" * 输出: false * 示例 4: * * 输入: pattern = "abba", str = "dog dog dog dog" * 输出: false * 说明: * 你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。     * */ class WordPattern { companion object { @JvmStatic fun main(args: Array<String>) { println(WordPattern().solution("abba", "dog cat cat dog")) println(WordPattern().solution("abba", "dog cat cat fish")) println(WordPattern().solution("aaaa", "dog cat cat dog")) println(WordPattern().solution("abba", "dog dog dog dog")) } } fun solution(pattern: String, s: String): Boolean { val sList = s.split(" ") if (pattern.length != sList.size) return false val pMap = hashMapOf<Char, String>() val sMap = hashMapOf<String, Char>() pattern.forEachIndexed { index, c -> val pValue = pMap[c] val sValue = sMap[sList[index]] if (pValue == null && sValue == null) { pMap[c] = sList[index] sMap[sList[index]] = c } else if (pValue != sList[index]) { return false } } return true } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,842
daily_algorithm
Apache License 2.0
src/medium/_583DeleteOperationForTwoStrings.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package medium class _583DeleteOperationForTwoStrings { class Solution { fun minDistance(word1: String, word2: String): Int { val n = word1.length val m = word2.length val dp = Array(n + 1) { IntArray(m + 1) } for (i in 0..n) dp[i][0] = i for (j in 0..m) dp[0][j] = j for (i in 1..n) { for (j in 1..m) { dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1) if (word1[i - 1] == word2[j - 1]) { dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i][j]) } } } return dp[n][m] } } class BestSolution { fun minDistance(s1: String, s2: String): Int { val cs1 = s1.toCharArray() val cs2 = s2.toCharArray() val n = s1.length val m = s2.length val f = Array(n + 1) { IntArray(m + 1) } for (i in 0..n) f[i][0] = i for (j in 0..m) f[0][j] = j for (i in 1..n) { for (j in 1..m) { f[i][j] = Math.min(f[i - 1][j] + 1, f[i][j - 1] + 1) if (cs1[i - 1] == cs2[j - 1]) f[i][j] = Math.min(f[i][j], f[i - 1][j - 1]) } } return f[n][m] } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
1,368
AlgorithmsProject
Apache License 2.0
src/main/kotlin/days/Day5.kt
nuudles
316,314,995
false
null
package days class Day5 : Day(5) { fun seatId(row: Int, col: Int) = row * 8 + col fun seat(pattern: String): Pair<Int, Int> { var rows = 0..127 var cols = 0..7 pattern .forEach { char -> when (char) { 'F' -> rows = rows.first..(rows.last - (rows.last - rows.first + 1) / 2) 'B' -> rows = (rows.first + (rows.last - rows.first + 1) / 2)..rows.last 'L' -> cols = cols.first..(cols.last - (cols.last - cols.first + 1) / 2) 'R' -> cols = (cols.first + (cols.last - cols.first + 1) / 2)..cols.last else -> Unit } } return rows.last to cols.last } override fun partOne() = inputList .map { pattern -> seat(pattern).let { seatId(it.first, it.second) } } .maxOrNull() ?: 0 override fun partTwo() = inputList .map { pattern -> seat(pattern).let { seatId(it.first, it.second) } } .fold(setOf<Int>()) { set, id -> set + id } .let { set -> val min = set.minOrNull() ?: 0 val max = set.maxOrNull() ?: 0 (min..max) .fold(setOf<Int>()) { rangeSet, i -> rangeSet + i } .subtract(set) .first() } }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
1,416
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/de/tek/adventofcode/y2022/util/math/CubicalComplex.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.util.math import kotlin.math.abs class ElementaryCube(val intervals: List<IntRange>) : Comparable<ElementaryCube> { init { if (intervals.isEmpty()) throw IllegalArgumentException("Interval list must not be empty.") if (intervals.any { it.last - it.first > 1 }) { throw IllegalArgumentException("All sides of a cube must have length 1. Given was $intervals.") } } constructor(vararg intervals: IntRange) : this(intervals.toList()) val dimension = intervals.count { it.last - it.first > 0 } fun boundary(): CubicalComplex { var sign = -1 val terms = mutableListOf<Term<ElementaryCube>>() for ((index, interval) in intervals.withIndex()) { val beforeIndex = intervals.subList(0, index) val afterIndex = if (index + 1 < intervals.size) { intervals.subList(index + 1, intervals.size) } else { emptyList() } terms += Term( sign, ElementaryCube(beforeIndex + listOf(IntRange(interval.first, interval.first)) + afterIndex) ) terms += Term( -sign, ElementaryCube(beforeIndex + listOf(IntRange(interval.last, interval.last)) + afterIndex) ) sign *= -1 } return CubicalComplex.from(terms) } override fun compareTo(other: ElementaryCube): Int { val dimensionDifference = this.dimension - other.dimension if (dimensionDifference != 0) return dimensionDifference val intervalDifferences = intervals.zip(other.intervals).map { (thisInterval, otherInterval) -> Pair(thisInterval.first - otherInterval.first, thisInterval.last - otherInterval.last) } return intervalDifferences.map { it.first }.firstOrNull { it != 0 } ?: intervalDifferences.map { it.second }.firstOrNull { it != 0 } ?: (this.intervals.size - other.intervals.size) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ElementaryCube) return false if (intervals != other.intervals) return false return true } override fun hashCode(): Int { return intervals.hashCode() } override fun toString(): String { val stringRepresentation = intervals.joinToString("x") { "[${it.first},${it.last}]" } return "ElementaryCube(intervals=$stringRepresentation, dimension=$dimension)" } companion object { fun atMinimumCorner(minCorner: Array<Int>) = ElementaryCube(minCorner.map { IntRange(it, it + 1) }) } } data class Term<T>(val coefficient: Int, val element: T) operator fun <T> Int.times(term: Term<T>) = term.copy(coefficient = this * term.coefficient) class CubicalComplex private constructor(val terms: List<Term<ElementaryCube>>) { operator fun plus(other: CubicalComplex): CubicalComplex { if (this == Zero) return other if (other == Zero) return this return from(terms + other.terms) } fun size(): Int = terms.sumOf { abs(it.coefficient) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CubicalComplex) return false if (simplify(terms) != simplify(other.terms)) return false return true } override fun hashCode(): Int { return terms.hashCode() } companion object { val Zero = CubicalComplex(emptyList()) fun from(vararg terms: Term<ElementaryCube>) = from(terms.asList()) fun from(terms: List<Term<ElementaryCube>>): CubicalComplex { if (terms.map { it.element.dimension }.distinct().count() > 1) { throw IllegalArgumentException("All elementary cubes must have the same dimension") } val simplified = simplify(terms) return if (simplified.isEmpty()) { Zero } else { CubicalComplex(simplified) } } private fun simplify(terms: List<Term<ElementaryCube>>): List<Term<ElementaryCube>> = terms.groupBy({ it.element }) { it.coefficient } .mapValues { (_, coefficients) -> coefficients.sum() } .map { (element, coefficientSum) -> Term(coefficientSum, element) } .filter { it.coefficient != 0 } .sortedBy { it.element } } } operator fun Int.times(complex: CubicalComplex) = CubicalComplex.from(complex.terms.map { this * it })
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
4,632
advent-of-code-2022
Apache License 2.0
src/main/kotlin/adventofcode/year2023/Day04Scratchcards.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2023 import adventofcode.Puzzle import adventofcode.PuzzleInput import kotlin.math.pow class Day04Scratchcards(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val scratchcards by lazy { input.lines().map(Scratchcard::invoke) } override fun partOne() = scratchcards.sumOf(Scratchcard::points) override fun partTwo(): Int { val map = scratchcards.map(Scratchcard::id).associateWith { 1 }.toMutableMap() scratchcards.forEach { scratchcard -> scratchcard.cardsWon().forEach { wonCard -> map[wonCard] = map[wonCard]!! + map[scratchcard.id]!! } } return map.values.sum() } companion object { private val CARD_REGEX = """Card\s+(\d+): ([\d\s]+) \| ([\d\s]+)""".toRegex() private data class Scratchcard( val id: Int, val winningNumbers: Set<Int>, val cardNumbers: Set<Int> ) { val matchingNumbers = cardNumbers.intersect(winningNumbers) fun points() = 2.0.pow(matchingNumbers.size.minus(1)).toInt() fun cardsWon() = (id + 1..id + matchingNumbers.size).toList() companion object { operator fun invoke(input: String): Scratchcard { val (id, winningNumbers, cardNumbers) = CARD_REGEX.find(input)!!.destructured return Scratchcard( id.toInt(), winningNumbers.split(" ").mapNotNull(String::toIntOrNull).toSet(), cardNumbers.split(" ").mapNotNull(String::toIntOrNull).toSet() ) } } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,717
AdventOfCode
MIT License
src/test/kotlin/be/brammeerten/y2023/Day11Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2023 import be.brammeerten.CL import be.brammeerten.readFile import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class Day11Test { @Test fun `part 1`() { val lines = readFile("2023/day11/exampleInput.txt"); // val lines = readFile("2023/day11/input.txt"); val map = createUniverse(lines) .expand() // .print(); val sum = map.pairs .asSequence() .mapIndexed { i, value -> val w = Math.abs(value.first.x - value.second.x) val h = Math.abs(value.first.y - value.second.y) w + h } .sum() assertThat(sum).isEqualTo(374); // assertThat(sum).isEqualTo(1000000); } @Test fun `part 2`() { // val lines = readFile("2023/day11/exampleInput.txt"); val lines = readFile("2023/day11/input.txt"); val map = createUniverse(lines) // .print() // .expand(1) // .expand(10-1) // .expand(100-1) .expand(1000000-1) // .print(); val sum = map.pairs .asSequence() .mapIndexed { i, value -> val w = Math.abs(value.first.x - value.second.x) val h = Math.abs(value.first.y - value.second.y) w + h } .sum() // assertThat(sum).isEqualTo(374); // assertThat(sum).isEqualTo(1030); // assertThat(sum).isEqualTo(8410); 710674907809 assertThat(sum).isEqualTo(710674907809) } fun createUniverse(rows: List<String>): Universe { val w = rows[0].length; val h = rows.size val galaxies: MutableList<CL> = mutableListOf() for (x in 0 until w) { for (y in 0 until h) { if (rows[y][x] == '#') galaxies.add(CL(x.toLong(), y.toLong())) } } return Universe(galaxies, w.toLong(), h.toLong()) } class Universe(val galaxies: List<CL>, val w: Long, val h: Long) { val pairs: MutableList<Pair<CL, CL>> = mutableListOf() init { for (i in galaxies.indices) { for (j in (i+1) until galaxies.size) { pairs.add(galaxies[i] to galaxies[j]) } } } fun expand(n: Int = 1): Universe { var newGalaxies = galaxies var newWidth = w var newHeight = h for (x in 0 until w) { if (galaxies.count { it.x == x } == 0) { val x2 = x + (newWidth - w) newGalaxies = newGalaxies.map { if (it.x >= x2) CL(it.x+n, it.y) else it } newWidth += n } } for (y in 0 until h) { if (galaxies.count { it.y == y } == 0) { val y2 = y + (newHeight - h) newGalaxies = newGalaxies.map { if (it.y >= y2) CL(it.x, it.y+n) else it } newHeight += n } } return Universe(newGalaxies, newWidth, newHeight) } fun print(): Universe { for (y in 0 until h) { for (x in 0 until w) { if (galaxies.contains(CL(x, y))) print("#") else print(".") } println() } println("\n") return this } } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
3,589
Advent-of-Code
MIT License
src/Day14.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
fun main() { fun part1(input: List<String>): Int { val rocks = inputToRocks(input) //find the bottom val bottomY = rocks.maxBy { it.second }.second var intoTheAbyss = false val sand = rocks.toMutableSet() while(!intoTheAbyss) { var sandX = 500 var sandY = 0 //sand particle starts falling var cameAtRest = false while(!cameAtRest and !intoTheAbyss) { //hits support from straight down if (Pair(sandX, sandY + 1) in sand) { //try to go down and left if(Pair(sandX - 1, sandY + 1) in sand) { //hits support from down and left if(Pair(sandX + 1, sandY + 1) in sand) { //hits support from down and right cameAtRest = true sand.add(Pair(sandX, sandY)) } else { //go down and right sandX += 1 sandY += 1 } } else { //go down and left sandX -= 1 sandY += 1 } } else { //keep on falling straight down sandY += 1 } if(sandY >= bottomY ) { intoTheAbyss = true } } } return sand.size - rocks.size } fun part2(input: List<String>): Int { val rocks = inputToRocks(input) //find the bottom val bottomY = rocks.maxBy { it.second }.second + 2 //union is very slow, so use only one set val sand = rocks.toMutableSet() //the source is not blocked by sand while(Pair(500, 0) !in sand) { var sandX = 500 var sandY = 0 //sand particle starts falling var cameAtRest = false while(!cameAtRest) { //hits support from straight down if (Pair(sandX, sandY + 1) in sand || (sandY + 1 == bottomY)) { //try to go down and left if(Pair(sandX - 1, sandY + 1) in sand || (sandY + 1 == bottomY)) { //hits support from down and left if(Pair(sandX + 1, sandY + 1) in sand || (sandY + 1 == bottomY)) { //hits support from down and right cameAtRest = true sand.add(Pair(sandX, sandY)) } else { //go down and right sandX += 1 sandY += 1 } } else { //go down and left sandX -= 1 sandY += 1 } } else { //keep on falling straight down sandY += 1 } } } return sand.size - rocks.size } val testInput = readLines("Day14_test") val input = readLines("Day14") check(part1(testInput) == 24) check(part2(testInput) == 93) println(part1(input)) println(part2(input)) } fun inputToRocks(input: List<String>): Set<Pair<Int, Int>> { return input.flatMap { it.split(" -> ").windowed(2).flatMap { r -> pathBetween(r[0], r[1]) } }.toSet() } fun pathBetween(from: String, to: String): List<Pair<Int, Int>> { return if (from == to) emptyList() else { val fromX = from.split(",")[0].toInt() //TODO define own extension similar to fun <T> List<T>.split() = Pair(take(1), drop(1)) val fromY = from.split(",")[1].toInt() val toX = to.split(",")[0].toInt() val toY = to.split(",")[1].toInt() // // some smartness here from Fleet, change to fromX == toX and it will warn the value is always 0 // val becomesAirPocket = if (fromY == toY) (fromX - toX).absoluteValue - 2 else 0 return if (fromX == toX) { if (fromY < toY) { (fromY..toY).map { Pair(fromX, it) } } else { (toY..fromY).map { Pair(fromX, it) } } } else { if (fromX < toX) { (fromX..toX).map { Pair(it, fromY) } } else { (toX..fromX).map { Pair(it, fromY) } } } } }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
4,788
advent-of-code-kotlin-2022
Apache License 2.0
y2023/src/main/kotlin/adventofcode/y2023/Day20.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution import adventofcode.util.math.lcm fun main() { Day20.solve() } object Day20 : AdventSolution(2023, 20, "Pulse Propagation") { override fun solvePartOne(input: String): Long { val modules = parse(input) var lowPulses = 0L var highPulses = 0L val unprocessed = ArrayDeque<Signal>() repeat(1000) { unprocessed.add(Signal("button", "broadcaster", false)) while (unprocessed.isNotEmpty()) { val signal = unprocessed.removeFirst() if (signal.highPulse) highPulses++ else lowPulses++ unprocessed += modules[signal.target]?.processSignal(signal).orEmpty() } } return lowPulses * highPulses } override fun solvePartTwo(input: String): Long { val modules = parse(input) //input analysis shows 4 conjunctions connected to a single conjunction before rx //the conjunction will fire when all connected conjunctions are high simultaneously //they each have a different, regular period. val moduleBeforeSink = modules.values.filterIsInstance<Conjunction>().single { it.outputs == listOf("rx") } val periodOfInputModules = mutableMapOf<String, Long>() generateSequence(1L, Long::inc) .takeWhile { periodOfInputModules.size != moduleBeforeSink.inputs.size } .forEach { buttonPress -> val unprocessed = ArrayDeque<Signal>() unprocessed.add(Signal("button", "broadcaster", false)) while (unprocessed.isNotEmpty()) { val signal = unprocessed.removeFirst() unprocessed += modules[signal.target]?.processSignal(signal).orEmpty() if (signal.highPulse && signal.target == moduleBeforeSink.name) { periodOfInputModules[signal.source] = buttonPress } } } return periodOfInputModules.values.reduce(::lcm) } } private fun parse(input: String): Map<String, Module> { val modules = input.lines().map { line -> val name = line.substringBefore(" ").replace("%", "").replace("&", "") val outputs = line.substringAfter("-> ").split(", ") when (line[0]) { '%' -> Flipflop(name, outputs, false) '&' -> Conjunction(name, outputs) else -> Broadcaster(name, outputs) } } modules.filterIsInstance<Conjunction>().forEach { conjunction -> modules.filter { conjunction.name in it.outputs }.forEach { input -> conjunction.connectInput(input.name) } } return modules.associateBy { it.name } } private sealed class Module(val name: String, val outputs: List<String>) { fun processSignal(inputSignal: Signal) = emitHighPulse(inputSignal)?.let { highPulse -> outputs.map { target -> Signal(name, target, highPulse) } }.orEmpty() protected abstract fun emitHighPulse(inputSignal: Signal): Boolean? } private class Broadcaster(name: String, outputs: List<String>) : Module(name, outputs) { override fun emitHighPulse(inputSignal: Signal) = inputSignal.highPulse } private class Flipflop(name: String, outputs: List<String>, var active: Boolean = false) : Module(name, outputs) { override fun emitHighPulse(inputSignal: Signal) = when { inputSignal.highPulse -> null else -> !active.also { active = !active } } } private class Conjunction( name: String, outputs: List<String>, val inputs: MutableMap<String, Boolean> = mutableMapOf() ) : Module(name, outputs) { override fun emitHighPulse(inputSignal: Signal): Boolean { inputs[inputSignal.source] = inputSignal.highPulse return inputs.any { !it.value } } fun connectInput(inputModule: String) { inputs[inputModule] = false } } private data class Signal(val source: String, val target: String, val highPulse: Boolean)
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
4,059
advent-of-code
MIT License
src/Day03.kt
jalex19100
574,686,993
false
{"Kotlin": 19795}
fun main() { val letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray() // index + 1 fun part1(input: List<String>): Int { var sum = 0 input.forEach { line -> val firstHalf = line.substring(0, line.length / 2).toCharArray() val secondHalf = line.substring(line.length / 2).toCharArray() val commonElementSet = firstHalf.toSet().intersect(secondHalf.toSet()) val commonElementPriority = letters.indexOf(commonElementSet.first()) + 1 sum += commonElementPriority } return sum } // TODO: AIIYYEEE more redundancy - cleanup fun part2(input: List<String>): Int { var sum = 0 input.chunked(3).forEach { oneChunk -> var commonElementSet = oneChunk.first().toSet() oneChunk.forEach { line -> commonElementSet = commonElementSet.intersect(line.toSet()) } val commonElementPriority = letters.indexOf(commonElementSet.first()) + 1 sum += commonElementPriority } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a50639447a2ef3f6fc9548f0d89cc643266c1b74
1,390
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/q51_100/q61_70/Solution70.kt
korilin
348,462,546
false
null
package q51_100.q61_70 /** * https://leetcode-cn.com/problems/climbing-stairs/ */ class Solution70 { /** * f(x) = f(x1) + f(x2) * * f(x1) = 最后一步为 1 个台阶的个数 = f(x - 1) * f(x2) = 最后一步为 2 个台阶的个数 = f(x - 2) * * f(x) = f(x-1) + f(x-2) * * 矩阵快速幂 * * M^n * [1, 1].h = [f(n + 1), f(n)].h * * M^n = [f(n), f(n-1)] */ fun climbStairs(n: Int): Int { val m = arrayOf( arrayOf(1, 1), arrayOf(1, 0) ) var un = n val r = arrayOf( arrayOf(1, 0), arrayOf(0, 1) ) while (un != 0) { if (un.and(1) == 1) matrix(m, r, r) matrix(m, m, m) un = un shr 1 } return r[0][0] } private fun matrix(x: Array<Array<Int>>, y: Array<Array<Int>>, save: Array<Array<Int>>) { val v1 = x[0][0] * y[0][0] + x[0][1] * y[1][0] val v2 = x[0][0] * y[0][1] + x[0][1] * y[1][1] val v3 = x[1][0] * y[0][0] + x[1][1] * y[1][0] val v4 = x[1][0] * y[0][1] + x[1][1] * y[1][1] save[0][0] = v1 save[0][1] = v2 save[1][0] = v3 save[1][1] = v4 } }
0
Kotlin
0
1
1ce05efeaf34536fff5fa6226bdcfd28247b2660
1,249
leetcode_kt_solution
MIT License
src/day10/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day10 import day06.main import readInput data class Instruction(val time: Int, val change: Int) fun main() { fun parse(input: List<String>) = input.map { if (it == "noop") { Instruction(1, 0) } else { Instruction(2, it.split(" ")[1].toInt()) } } fun registerValues(input: List<Instruction>) = input.runningFold(listOf(1)) { register, (cycles, change) -> val registerValue = register.last() buildList { repeat(cycles - 1) { add(registerValue) } add(registerValue + change) } }.flatten() fun part1(input: List<Instruction>) = registerValues(input).let { registerValues -> listOf(20, 60, 100, 140, 180, 220).sumOf { cycle -> cycle * registerValues[cycle - 1] } } fun part2(input: List<Instruction>) = registerValues(input).chunked(40).joinToString("\n") { spritePositions -> spritePositions.mapIndexed{ crt, sprite -> if (crt in sprite - 1..sprite + 1) "██" else " " }.joinToString("") } val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
1,252
AOC2022
Apache License 2.0
src/day10/Day10.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day10 import readInput import kotlin.math.abs fun main() { val input = readInput(parent = "src/day10", name = "Day10_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartTwo(input: List<String>): String { var allLines = "" var currLine = "#" var c = 1 var x = 1 for (l in input) { if (c % 40 == 0) { allLines += "$currLine\n" currLine = "" } currLine += draw(c, x) if (l.startsWith("addx")) { c++ if (c % 40 == 0) { allLines += "$currLine\n" currLine = "" } x += l.split(' ')[1].toInt() currLine += draw(c, x) } c++ } return allLines } private fun draw(c: Int, x: Int) = if (abs(c % 40 - x) <= 1) { "#" } else { "." } private fun solvePartOne(input: List<String>): Int { var signalStrengthSum = 0 var c = 1 var x = 1 for (l in input) { signalStrengthSum += calc(c, x) if (l.startsWith("addx")) { c++ signalStrengthSum += calc(c, x) x += l.split(' ')[1].toInt() } c++ } return signalStrengthSum } private fun calc(c: Int, x: Int) = if ((c - 20) % 40 == 0) { c * x } else { 0 }
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
1,346
advent-of-code-2022
Apache License 2.0
kotlin_practice/src/main/java/dev/vengateshm/kotlin_practice/programs/AnagramSubStringSearchHashMapImpl.kt
vengateshm
670,054,614
false
{"Kotlin": 996301, "Java": 26595}
package dev.vengateshm.kotlin_practice.programs fun main() { // println(findAnagramsPatternsStartIndicesInString("", "abc").toString()) // println(findAnagramsPatternsStartIndicesInString("abc", "abca").toString()) println(findAnagramsPatternsStartIndicesInString("abczzbcabcadeb", "abc").toString()) // println(findAnagramsPatternsStartIndicesInString("abacab", "ab").toString()) } fun findAnagramsPatternsStartIndicesInString(str: String, pattern: String): List<Int>? { // Handle corner cases if (isInvalid(str, pattern)) { println("Invalid string or pattern") return null } if (pattern.length > str.length) { println("Pattern is larger than string") return null } val windowSize = pattern.length val strLength = str.length val patternCharCountMap = mutableMapOf<Char, Int>() val stringCharCountMap = mutableMapOf<Char, Int>() val indices = mutableListOf<Int>() // Generate count map for first window in str and pattern for (i in 0 until windowSize) { generateWindowCharCountMap(pattern[i], patternCharCountMap) generateWindowCharCountMap(str[i], stringCharCountMap) } // Start at the end of the first window for (windowRightBound in windowSize until strLength) { if (compareMap(patternCharCountMap, stringCharCountMap)) { indices.add(windowRightBound - windowSize) } // Remove first character in the window val oldCharIndex = windowRightBound - windowSize val oldChar = str[oldCharIndex] var oldCharCount = stringCharCountMap[oldChar]!! if (oldCharCount == 1) { stringCharCountMap.remove(oldChar) } else { oldCharCount-- stringCharCountMap[oldChar] = oldCharCount } // Add the new char to the window generateWindowCharCountMap(str[windowRightBound], stringCharCountMap) } // At this point last window comparison remains // so compare one last time if (compareMap(patternCharCountMap, stringCharCountMap)) { indices.add(strLength - windowSize) } return indices } fun generateWindowCharCountMap(char: Char, map: MutableMap<Char, Int>) { var count = map[char] if (count == null) { count = 0; } count++ map[char] = count } fun isInvalid(str: String?, pattern: String?): Boolean { return str.isNullOrEmpty() || pattern.isNullOrEmpty() } fun compareMap(patternMap: Map<Char, Int>, strMap: Map<Char, Int>): Boolean { for (entry in patternMap) { val char = entry.key val count = entry.value if (strMap[char] == null || strMap[char] != count) { return false } } return true }
0
Kotlin
0
0
40d2c85b09fd2ea22c004bd784bf6b79ccaaf034
2,757
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
solutions/aockt/y2015/Y2015D07.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2015 import io.github.jadarma.aockt.core.Solution object Y2015D07 : Solution { // Regular expressions for parsing some language tokens. private val variableRegex = Regex("""\b[a-z]+\b""") private val constantRegex = Regex("""\b\d+\b""") private val unary = Regex("""^([A-Z]+) (\d+)$""") private val binary = Regex("""^(\d+) ([A-Z]+) (\d+)$""") /** * Evaluates a valid expression built with the limited instruction set, or throws if invalid syntax. * Does not accept variables, only constant values. */ private fun evaluate(expression: String): UShort { constantRegex.matchEntire(expression)?.run { return value.toUShort() } unary.matchEntire(expression)?.run { val (operator, valueString) = destructured val value = valueString.toUShort() return when (operator) { "NOT" -> value.inv() else -> throw IllegalArgumentException("Invalid unary operator: $operator") } } binary.matchEntire(expression)?.run { val (leftString, operator, rightString) = destructured val left = leftString.toUShort() val right = rightString.toUShort() return when (operator) { "AND" -> left and right "OR" -> left or right "LSHIFT" -> left.toInt().shl(right.toInt()).toUShort() "RSHIFT" -> left.toInt().shr(right.toInt()).toUShort() else -> throw IllegalArgumentException("Invalid binary operator: $operator") } } throw IllegalArgumentException("Invalid expression: $expression") } /** * Takes some [instructions], and builds and evaluates the state of its wires. * Returns a map of each wire label to its signal value. */ private fun evalCircuit(instructions: List<String>): Map<String, UShort> { val state = mutableMapOf<String, UShort>() val evaluationQueue = instructions .map { it.split(" -> ") } .map { it[0] to it[1] } .let(::ArrayDeque) while (evaluationQueue.isNotEmpty()) { val instruction = evaluationQueue.removeFirst() var allInputsAvailable = true val lhs = variableRegex.replace(instruction.first) { when (val stateValue = state[it.value]) { null -> "null".also { allInputsAvailable = false } else -> stateValue.toString() } } if (!allInputsAvailable) { evaluationQueue.addLast(instruction) continue } state[instruction.second] = evaluate(lhs) } return state } override fun partOne(input: String) = evalCircuit(input.lines()).getValue("a") override fun partTwo(input: String): UShort { val a = partOne(input) val overriddenInput = input.lineSequence().map { if (it.endsWith(" -> b")) "$a -> b" else it }.toList() return evalCircuit(overriddenInput).getValue("a") } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
3,172
advent-of-code-kotlin-solutions
The Unlicense
y2015/src/main/kotlin/adventofcode/y2015/Day12.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2015 import adventofcode.io.AdventSolution import java.io.StreamTokenizer import java.io.StringReader object Day12 : AdventSolution(2015, 12, "JSAbacusFramework.io") { override fun solvePartOne(input: String) = traverse(input.asJson()).toString() override fun solvePartTwo(input: String) = traverseNonRed(input.asJson()).toString() private fun String.asJson() = parse(tokenize(this)) private fun traverse(node: Any): Int = when (node) { is Int -> node is List<*> -> traverseAndSum(node, this::traverse) is Map<*, *> -> traverseAndSum(node.values, this::traverse) else -> 0 } private fun traverseNonRed(node: Any): Int = when { node is Int -> node node is List<*> -> traverseAndSum(node, this::traverseNonRed) node is Map<*, *> && !node.containsValue("red") -> traverseAndSum(node.values, this::traverseNonRed) else -> 0 } private inline fun traverseAndSum(node: Iterable<*>, traverse: (Any) -> Int) = node.filterNotNull().sumOf { traverse(it) } } private enum class Token { ArrayBegin, ArrayEnd, ObjectBegin, ObjectEnd, Separator, Comma } private fun tokenize(str: String): Iterator<Any> = iterator { val reader = StringReader(str) val tokenizer = StreamTokenizer(reader) while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { val tokenValue: Any = when (tokenizer.ttype) { StreamTokenizer.TT_NUMBER -> tokenizer.nval.toInt() '"'.code -> tokenizer.sval '['.code -> Token.ArrayBegin ']'.code -> Token.ArrayEnd '{'.code -> Token.ObjectBegin '}'.code -> Token.ObjectEnd ':'.code -> Token.Separator ','.code -> Token.Comma else -> throw IllegalArgumentException() } yield(tokenValue) } } private fun parse(iter: Iterator<Any>): Any = iter.next().let { token -> when (token) { Token.ArrayBegin -> parseArray(iter) Token.ObjectBegin -> parseObject(iter) is Int -> token is String -> token else -> throw IllegalArgumentException() } } private fun parseArray(iter: Iterator<Any>): List<Any> = mutableListOf<Any>().apply { do { this.add(parse(iter)) } while (iter.next() == Token.Comma) } private fun parseObject(iter: Iterator<Any>): Map<String, Any> = mutableMapOf<String, Any>().apply { do { val k = iter.next() as String assert(iter.next() == Token.Separator) val v = parse(iter) this[k] = v } while (iter.next() == Token.Comma) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,421
advent-of-code
MIT License
src/main/kotlin/github/walkmansit/aoc2020/Day22.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 import java.util.* class Day22(val input: String) : DayAoc<Int, Int> { class Game private constructor(private val deckA: Collection<Int>, private val deckB: Collection<Int>) { fun getScore(): Int { val deck1dq: Deque<Int> = ArrayDeque(deckA) val deck2dq: Deque<Int> = ArrayDeque(deckB) while (deck1dq.isNotEmpty() && deck2dq.isNotEmpty()) { val a = deck1dq.pop() val b = deck2dq.pop() if (a > b) { deck1dq.addLast(a) deck1dq.addLast(b) } else { deck2dq.addLast(b) deck2dq.addLast(a) } } return if (deck1dq.isNotEmpty()) calcScore(deck1dq) else calcScore(deck2dq) } private fun calcScore(deck: Deque<Int>): Int { var sum = 0 for ((i, v) in deck.withIndex()) { sum += v * (deck.size - i) } return sum } private fun copyNFirst(deque: Deque<Int>, n: Int): Deque<Int> { val result = ArrayDeque<Int>() for (i in 0 until n) { result.add(deque.elementAt(i)) } return result } private fun isFirstWin(first: Deque<Int>, second: Deque<Int>, calScore: Boolean = false): Pair<Boolean, Int> { val cache: MutableSet<String> = mutableSetOf() while (first.isNotEmpty() && second.isNotEmpty()) { val key = "${first.joinToString(",")} ${second.joinToString(",")}" if (cache.contains(key)) return true to (if (calScore) calcScore(first) else 0) val a = first.pop() val b = second.pop() var firstWinRound = false firstWinRound = if (first.size >= a && second.size >= b) isFirstWin(copyNFirst(first, a), copyNFirst(second, b)).first else a > b if (firstWinRound) { first.addLast(a) first.addLast(b) } else { second.addLast(b) second.addLast(a) } cache.add(key) } return if (first.isEmpty()) { false to calcScore(second) } else { true to calcScore(first) } } fun getScoreRecurs(): Int { val deck1dq: Deque<Int> = ArrayDeque(deckA) val deck2dq: Deque<Int> = ArrayDeque(deckB) return isFirstWin(deck1dq, deck2dq, true).second } companion object { fun fromInput(input: String): Game { val parts = input.split("\n\n") val deck1 = parts[0].substring(10, parts[0].length).split("\n").map { it.toInt() } val deck2 = parts[1].substring(10, parts[1].length).split("\n").map { it.toInt() } return Game(deck1, deck2) } } } override fun getResultPartOne(): Int { return Game.fromInput(input).getScore() } override fun getResultPartTwo(): Int { return Game.fromInput(input).getScoreRecurs() } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
3,332
AdventOfCode2020
MIT License
src/main/kotlin/AvailableMeetingSlotsInCalendar.kt
nmicra
262,980,033
false
null
import java.time.LocalTime val person1_meetings = listOf("09:00-09:30", "13:00-14:00", "17:20-18:00") // Scheduled meetings for Person1 val person2_meetings = listOf( "13:30-14:30", "17:00-17:30") // Scheduled meetings for Person2 val restrictions_person1 = "08:00,19:00" // Person1 cannot accept meetings before 8:00 & after 19:00 val restrictions_person2 = "08:30,18:30" // Person2 cannot accept meetings before 8:00 & after 19:00 val findMeetingSlot : Long = 40 // minutes val step : Long = 10 // minutes /** * Find all possibilities for a meeting with the duration of $findMeetingSlot minutes between Person1 & Person2 * This meeting should not overlap with already existing meetings or specified restrictions. */ fun main() { val lstResults = mutableListOf<String>() val allMeetings = parseStringListsToLocalTime(person1_meetings).plus(parseStringListsToLocalTime(person2_meetings)) var (begin, end) = determineLowerUpperRestrictions(restrictions_person1,restrictions_person2) while (begin.plusMinutes(findMeetingSlot).isBefore(end)){ if (allMeetings.none { isOverLap(it.first,it.second,begin, begin.plusMinutes(findMeetingSlot))}){ lstResults.add("$begin - ${begin.plusMinutes(findMeetingSlot)}") } begin = begin.plusMinutes(step) } println(lstResults) } /** * returns true when startTime1-endTime1 is overlaps with startTime2-endTime2 */ fun isOverLap(start1 : LocalTime, end1 : LocalTime, start2 : LocalTime, end2 : LocalTime) : Boolean{ if((start1.isAfter(start2) && start1.isBefore(end2)) || (end1.isAfter(start2) && end1.isBefore(end2)) || start1.isBefore(start2) && end1.isAfter(end2) || start2.isBefore(start1) && end2.isAfter(end1)){ return true } return false } fun parseStringListsToLocalTime(list : List<String>) : List<Pair<LocalTime,LocalTime>> { return list.map { val (left,right) = it.split("-") Pair(LocalTime.parse(left), LocalTime.parse(right))}.toList() } fun determineLowerUpperRestrictions(restrictions_person1 : String, restrictions_person2 : String) : Pair<LocalTime,LocalTime>{ val (left1,right1) = restrictions_person1.split(",") val (left2,right2) = restrictions_person2.split(",") val lowerBound = when{ LocalTime.parse(left1).isBefore(LocalTime.parse(left2)) -> LocalTime.parse(left2) else -> LocalTime.parse(left1) } val upperBound = when { LocalTime.parse(right1).isBefore(LocalTime.parse(right2)) -> LocalTime.parse(right1) else -> LocalTime.parse(right2) } return Pair(lowerBound,upperBound) }
0
Kotlin
0
0
4bf80f01af6c4a08221131878b7d53e2826db241
2,609
kotlin_practice
Apache License 2.0
src/main/kotlin/icfp2019/Brain.kt
randomsamples
189,507,360
true
{"JavaScript": 797310, "Kotlin": 89529, "CSS": 9434, "HTML": 5859}
package icfp2019 import icfp2019.analyzers.ConservativeDistanceAnalyzer import icfp2019.core.DistanceEstimate import icfp2019.core.Strategy import icfp2019.core.applyAction import icfp2019.model.Action import icfp2019.model.GameState import icfp2019.model.Problem import icfp2019.model.RobotId fun strategySequence( initialGameState: GameState, strategy: Strategy, robotId: RobotId, initialAction: Action = Action.DoNothing ): Sequence<Pair<GameState, Action>> { return generateSequence( seed = initialGameState to initialAction, nextFunction = { (gameState, _) -> if (gameState.isGameComplete()) null else { val nextAction = strategy.compute(gameState)(robotId, gameState) val nextState = applyAction(gameState, robotId, nextAction) nextState to nextAction } } ).drop(1) // skip the initial state } data class BrainScore( val robotId: RobotId, val gameState: GameState, val action: Action, val distanceEstimate: DistanceEstimate, val strategy: Strategy ) fun Sequence<Pair<GameState, Action>>.score( robotId: RobotId, strategy: Strategy ): BrainScore { // grab the first and last game state in this simulation path val (initial, final) = map { it to it.first } .reduce { (initial, _), (_, final) -> initial to final } // from the final position we will estimate the number of // steps required to completely wrap the remainder of the mine val point = final.robotState.getValue(robotId).currentPosition val gameState = initial.first val conservativeDistance = ConservativeDistanceAnalyzer.analyze(gameState)(robotId, final)(point) // return the initial game state, if this path is the winner // we can use this to avoid duplicate action evaluation return BrainScore( robotId, initial.first, initial.second, conservativeDistance.estimate, strategy ) } fun brainStep( initialGameState: GameState, strategies: Iterable<Strategy>, maximumSteps: Int ): Pair<GameState, Map<RobotId, Action>> { // one time step consists of advancing each worker wrapper by N moves // this will determine the order in which to advance robots by running // all robot states through all strategies, picking the the winning // robot/state pair and resuming until the stack of robots is empty // the list of robots can change over time steps, get a fresh copy each iteration var gameState = initialGameState val actions = mutableMapOf<RobotId, Action>() val workingSet = gameState.robotState.keys.toMutableSet() while (!gameState.isGameComplete() && workingSet.isNotEmpty()) { // pick the minimum across all robot/strategy pairs val winner = workingSet .flatMap { robotId -> strategies .map { strategy -> strategySequence(gameState, strategy, robotId) .take(maximumSteps) .score(robotId, strategy) } } val winner0 = winner.minBy { it.distanceEstimate }!! // we have a winner, remove it from the working set for this time step workingSet.remove(winner0.robotId) // record the winning action and update the running state actions[winner0.robotId] = winner0.action gameState = winner0.gameState } return gameState to actions } fun brain( problem: Problem, strategies: Iterable<Strategy>, maximumSteps: Int ): Solution { var gameState = GameState(problem) val actions = mutableMapOf<RobotId, List<Action>>() while (!gameState.isGameComplete()) { val (newState, newActions) = brainStep(gameState, strategies, maximumSteps) gameState = newState newActions.forEach { (robotId, action) -> actions.merge(robotId, listOf(action)) { left, right -> left.plus(right) } } } return Solution(problem, actions.toMap()) }
0
JavaScript
0
0
afcf5123ffb72ac10cfa6b0772574d9826f15e41
4,098
icfp-2019
The Unlicense
src/Day01.kt
Olivki
573,156,936
false
{"Kotlin": 11297}
fun main() { fun part1(input: List<String>) = buildList { val inventory = hashSetOf<Int>() for (line in input) { if (line.isNotBlank()) { inventory += line.toInt() } else { add(inventory.sum()) inventory.clear() } } if (inventory.isNotEmpty()) add(inventory.sum()) } fun part2(input: List<String>) = part1(input) .sortedDescending() .take(3) val testInput = readTestInput("Day01") // p1 check(part1(testInput) == listOf(6_000, 4_000, 11_000, 24_000, 10_000)) check(part1(testInput).max() == 24_000) // p2 check(part2(testInput) == listOf(24_000, 11_000, 10_000)) check(part2(testInput).sum() == 45_000) val input = readInput("Day01") println(part1(input).max()) println(part2(input).sum()) }
0
Kotlin
0
1
51c408f62589eada3d8454740c9f6fc378e2d09b
879
aoc-2022
Apache License 2.0
modules/fathom/src/main/kotlin/silentorb/mythic/fathom/surfacing/old/DuplicateContours.kt
silentorb
227,508,449
false
null
package silentorb.mythic.fathom.surfacing.old import silentorb.mythic.fathom.surfacing.Contours import kotlin.math.abs tailrec fun groupDuplicates(tolerance: Float, contours: Contours, duplicates: List<Contours>): List<Contours> { return if (contours.none()) duplicates else { val next = contours.first() val remaining = contours.drop(1) val matches = remaining.filter { it.position.distance(next.position) < tolerance } val nextDuplicates = if (matches.any()) duplicates.plusElement(listOf(next).plus(matches)) else duplicates val nextContours = remaining.minus(matches) groupDuplicates(tolerance, nextContours, nextDuplicates) } } fun groupDuplicates(tolerance: Float, contours: Contours) = groupDuplicates(tolerance, contours, listOf()) data class DuplicateResult( val main: Contours, val pivots: Contours ) // There are two kinds of duplicates: pure duplicates and pivot duplicates. // Pivot duplicates contain a mix of directions and are intersections between multiple lines. // Pivot direction is unreliable so pivots shouldn't be used as the start of the line but can // be used as the end of a line. // Pure duplicates have identical facing and should be merged into a single entry. // Pure duplicates are candidates for the start of a line. fun removeDuplicates(contours: Contours, groups: List<Contours>): DuplicateResult { val (pureDuplicates, pivots) = groups.partition { group -> val first = group.first() val others = group.drop(1) others.all { other -> abs(first.direction.dot(other.direction)) > 0.82f } } val shouldBeRemoved = pivots.flatten().plus(pureDuplicates.flatMap { it.drop(1) }) return DuplicateResult( main = contours.minus(shouldBeRemoved), pivots = pivots.map { it.first() } ) } fun removeDuplicates(tolerance: Float, contours: Contours): DuplicateResult { val groups = groupDuplicates(tolerance, contours) return removeDuplicates(contours, groups) }
0
Kotlin
0
2
74462fcba9e7805dddec1bfcb3431665df7d0dee
1,998
mythic-kotlin
MIT License
src/main/kotlin/days/Day7.kt
jgrgt
433,952,606
false
{"Kotlin": 113705}
package days import kotlin.math.abs class Day7 : Day(7) { override fun runPartOne(lines: List<String>): Any { val horizontalPositions = lines[0].split(",").map { it.trim().toInt() } val median = horizontalPositions.median() return horizontalPositions.sumOf { abs(it - median) } } override fun runPartTwo(lines: List<String>): Any { val horizontalPositions = lines[0].split(",").map { it.trim().toInt() } val min = horizontalPositions.minOrNull()!! val max = horizontalPositions.maxOrNull()!! val costs = (min..max).map { target -> calculateCost(target, horizontalPositions) } return costs.minOrNull()!! } private fun calculateCost(target: Int, horizontalPositions: List<Int>): Int { return horizontalPositions.sumOf { pos -> cost(abs(target - pos)) } } private fun cost(steps: Int): Int { if (steps == 0) { return 0 } return steps + cost(steps - 1) } } fun List<Int>.median(): Int { val sorted = this.sorted() // simplified, does not average out if 2 options return sorted[this.size / 2] }
0
Kotlin
0
0
6231e2092314ece3f993d5acf862965ba67db44f
1,188
aoc2021
Creative Commons Zero v1.0 Universal
src/Day25/Day25.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
fun List<List<Char>>.print() { for (row in this) { for (e in row) { print(e) } println() } } fun main() { fun preprocess(input: List<String>): List<List<Char>> { return input.map { it.toList() } } fun doStep(input: List<List<Char>>): List<List<Char>> { val yLength = input.size val xLength = input[0].size val intermediate = input.map { it.toMutableList() }.toMutableList() for ((y, row) in input.withIndex()) { for ((x, e) in row.withIndex()) { if (e == '>') { if (input[y][(x + 1) % xLength] == '.') { intermediate[y][x] = '.' intermediate[y][(x + 1) % xLength] = '>' } } } } val intermediate2 = intermediate.map { it.toMutableList() }.toMutableList() for ((y, row) in input.withIndex()) { for ((x, e) in row.withIndex()) { if (e == 'v') { if (intermediate[(y + 1) % yLength][x] == '.') { intermediate2[y][x] = '.' intermediate2[(y + 1) % yLength][x] = 'v' } } } } return intermediate2 } fun part1(input: List<List<Char>>): Int { var stepCount = 1 var last = input var actual = doStep(input) while (last != actual) { last = actual actual = doStep(actual) stepCount++ } return stepCount } val testInput = preprocess(readInput(25, true)) val input = preprocess(readInput(25)) check(part1(testInput) == 58) println(part1(input)) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
1,773
advent-of-code-2021
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DungeonGame.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 174. Dungeon Game * @see <a href="https://leetcode.com/problems/dungeon-game">Source</a> */ fun interface DungeonGame { fun calculateMinimumHP(dungeon: Array<IntArray>): Int } class DungeonGameDP : DungeonGame { override fun calculateMinimumHP(dungeon: Array<IntArray>): Int { val m: Int = dungeon.size val n: Int = dungeon[0].size val dp = IntArray(n + 1) dp[n] = 1 for (i in m - 1 downTo 0) { for (j in n - 1 downTo 0) { val health: Int = if (i == m - 1) { dp[j + 1] - dungeon[i][j] } else if (j == n - 1) { dp[j] - dungeon[i][j] } else { min(dp[j + 1], dp[j]) - dungeon[i][j] } dp[j] = if (health <= 0) { 1 } else { health } } } return dp[0] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,629
kotlab
Apache License 2.0
src/Day01.kt
eleung4
574,590,563
false
{"Kotlin": 7285}
fun main() { fun part1(input: List<String>): Int { return input.size } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println(part1(testInput)) // println((part1(testInput) // val input = readInput("Day01") // println(part1(input)) // println(part2(input)) val input = readInput("Day01") println(calsPerElf(input)) } fun calsPerElf(input: List<String>) : Int { var now= 0 var greatest = 0 val array = ArrayList<Int>() for(line in input) { if(line!="") { now +=line.toInt() array.add(now) } else { if(now>greatest) { greatest = now now = 0 } now = 0 } } if(now > greatest) { greatest = now } return array.map {it }.sortedDescending().take(3).sum() }
0
Kotlin
0
0
9013be242f7c2a13f73b297eee9be60655b531ac
1,011
AdventOfCode
Apache License 2.0
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day14/Matrix.kt
Gentleman1983
737,309,232
false
{"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319}
package de.havox_design.aoc2023.day14 data class Matrix(val matrix: MutableList<CharArray>) { private val ICON_ROUND_STONE = 'O' private val ICON_SQUARE_STONE = '#' fun cycle(cycles: Int = 1): Matrix = apply { repeat(cycles) { rollNorth() .rollWest() .rollSouth() .rollEast() } } fun rollNorth(): Matrix = apply { matrix .first() .indices .forEach { columnIndex -> matrix .indices .joinToString("") { rowIndex -> matrix[rowIndex][columnIndex].toString() } .split(ICON_SQUARE_STONE) .joinToString(ICON_SQUARE_STONE.toString()) { it .toCharArray() .sortedDescending() .joinToString("") } .forEachIndexed { rowIndex, c -> matrix[rowIndex][columnIndex] = c } } } fun rollSouth(): Matrix = apply { matrix .first() .indices .forEach { columnIndex -> matrix .indices .joinToString("") { rowIndex -> matrix[rowIndex][columnIndex].toString() } .split(ICON_SQUARE_STONE) .joinToString(ICON_SQUARE_STONE.toString()) { it .toCharArray() .sorted() .joinToString("") } .forEachIndexed { rowIndex, c -> matrix[rowIndex][columnIndex] = c } } } fun rollWest(): Matrix = apply { matrix .forEachIndexed { rowIndex, row -> matrix[rowIndex] = row .joinToString("") .split(ICON_SQUARE_STONE) .joinToString(ICON_SQUARE_STONE.toString()) { it .toCharArray() .sortedDescending() .joinToString("") } .toCharArray() } } fun rollEast(): Matrix = apply { matrix .forEachIndexed { rowIndex, row -> matrix[rowIndex] = row .joinToString("") .split(ICON_SQUARE_STONE) .joinToString(ICON_SQUARE_STONE.toString()) { it .toCharArray() .sorted() .joinToString("") } .toCharArray() } } fun northLoad(): Int = matrix .first() .indices .sumOf { columnIndex -> matrix.indices .sumOf { rowIndex -> when (ICON_ROUND_STONE) { matrix[rowIndex][columnIndex] -> matrix.size - rowIndex else -> 0 } } } override fun toString(): String = matrix .joinToString("\n") { line -> line.joinToString("") } } fun Matrix(input: List<String>): Matrix = input .map(String::toCharArray) .toMutableList() .let(::Matrix)
4
Kotlin
0
1
35ce3f13415f6bb515bd510a1f540ebd0c3afb04
3,965
advent-of-code
Apache License 2.0
src/Day02.kt
erikthered
572,804,470
false
{"Kotlin": 36722}
fun main() { fun part1(input: List<String>): Int { var score = 0 for(line in input) { val opponent = OpponentMove.valueOf(line[0].toString()) val player = PlayerMove.valueOf(line[2].toString()) score += player.points score += determineOutcome(opponent, player).points } return score } fun part2(input: List<String>): Int { var score = 0 for(line in input) { val opponent = OpponentMove.valueOf(line[0].toString()) val desiredOutcome = when(line[2]) { 'X' -> Outcome.LOSS 'Y' -> Outcome.DRAW 'Z' -> Outcome.WIN else -> throw IllegalArgumentException() } val player = determinePlay(opponent, desiredOutcome) score += player.points score += desiredOutcome.points } return score } val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun determineOutcome(op: OpponentMove, pl: PlayerMove): Outcome { return when(op) { OpponentMove.A -> { when(pl) { PlayerMove.X -> Outcome.DRAW PlayerMove.Y -> Outcome.WIN PlayerMove.Z -> Outcome.LOSS } } OpponentMove.B -> { when(pl) { PlayerMove.X -> Outcome.LOSS PlayerMove.Y -> Outcome.DRAW PlayerMove.Z -> Outcome.WIN } } OpponentMove.C -> { when(pl) { PlayerMove.X -> Outcome.WIN PlayerMove.Y -> Outcome.LOSS PlayerMove.Z -> Outcome.DRAW } } } } fun determinePlay(op: OpponentMove, out: Outcome): PlayerMove { return when(op) { OpponentMove.A -> { when(out) { Outcome.WIN -> PlayerMove.Y Outcome.DRAW -> PlayerMove.X Outcome.LOSS -> PlayerMove.Z } } OpponentMove.B -> { when(out) { Outcome.WIN -> PlayerMove.Z Outcome.DRAW -> PlayerMove.Y Outcome.LOSS -> PlayerMove.X } } OpponentMove.C -> { when(out) { Outcome.WIN -> PlayerMove.X Outcome.DRAW -> PlayerMove.Z Outcome.LOSS -> PlayerMove.Y } } } } enum class OpponentMove { A, B, C } enum class PlayerMove(val points: Int) { X(1), Y(2), Z(3) } enum class Outcome(val points: Int) { WIN(6), DRAW(3), LOSS(0) }
0
Kotlin
0
0
3946827754a449cbe2a9e3e249a0db06fdc3995d
2,790
aoc-2022-kotlin
Apache License 2.0
src/com/kotlin/pocs/predicates/Predicates.kt
serbanghita
253,706,661
false
null
package com.kotlin.pocs.predicates fun main(args: Array<String>): Unit { // val n = listOf(1,2,3,4,5,6,7,8); // val pred = { value: Int -> value > 5 } // // println(n.all(pred)) // println(n.any(pred)) // println(n.count { it > 5 }) // // println(n.find(pred)) val players = listOf( Player(1, "AAA", listOf(Point(1,1), Point(1,2))), Player(2, "BBB", listOf(Point(1,1), Point(11,22))), Player(3, "CCC", listOf(Point(1,1), Point(111,222))) ) val p1 = players .asSequence() .filter { println("filter($it)") it.id > 1 } .map { println("map($it)"); "${it.id} + ${it.name}" } // val p2 = players // //.asSequence() // .flatMap { it -> it.points } // .distinct() // println(p1) for(player in p1) { println(player); } // println(p2) /** filter(com.kotlin.pocs.predicates.Player@7eda2dbb) filter(com.kotlin.pocs.predicates.Player@6576fe71) filter(com.kotlin.pocs.predicates.Player@76fb509a) map(com.kotlin.pocs.predicates.Player@6576fe71) map(com.kotlin.pocs.predicates.Player@76fb509a) 2 + BBB 3 + CCC */ /** kotlin.sequences.TransformingSequence@2b71fc7e filter(com.kotlin.pocs.predicates.Player@4b85612c) filter(com.kotlin.pocs.predicates.Player@277050dc) map(com.kotlin.pocs.predicates.Player@277050dc) 2 + BBB filter(com.kotlin.pocs.predicates.Player@5c29bfd) map(com.kotlin.pocs.predicates.Player@5c29bfd) 3 + CCC */ } class Player(var id: Int = 0, var name: String = "", var points: List<Point>) { } data class Point(var x: Int = 0, var y: Int = 0) { }
0
Kotlin
0
0
bca562981c731ab5c3fca4519a1af5f67fe8b754
1,890
kotlin-pocs
MIT License
ctci/arrays_and_strings/_01_is_unique/IsUnique.kt
vishal-sehgal
730,172,606
false
{"Kotlin": 8936}
package ctci.arrays_and_strings._01_is_unique /** * #1.1 * * Is Unique: Implement an algorithm to determine if a string has all unique characters. * What if you can not use additional data structures? */ fun main() { val string1 = "vishal" val string2 = "sehgal" val string3 = "linkedin" val string4 = "google" println("String: $string1 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string1)}") println("String: $string2 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string2)}") println("String: $string3 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string3)}") println("String: $string4 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string4)}") println() println("String: $string1 has all unique characters: ${IsUnique().hasUniqueCharactersBest(string1)}") println("String: $string2 has all unique characters: ${IsUnique().hasUniqueCharactersBest(string2)}") println("String: $string3 has all unique characters: ${IsUnique().hasUniqueCharactersBest(string3)}") println("String: $string4 has all unique characters: ${IsUnique().hasUniqueCharactersBetter(string4)}") } class IsUnique { /** * Determines whether a given string has all unique characters. * * Time complexity: O(n), where n is the length of input string. * * Here's a breakdown of the time complexity: * * string.toSet(): This converts the string to a set, which involves iterating through each * character in the string to build the set. In the worst case, this operation has a time complexity of O(n), * where n is the length of the string. * * string.length == string.toSet().size: This checks if the length of the original string is equal * to the size of the set. The size operation on a set is typically a constant-time operation. * * Therefore, the dominant factor in determining the time complexity is the conversion of the string * to a set, resulting in a total time complexity of O(n), where n is the length of the input string. * The function's runtime scales linearly with the size of the input. * * * @param string The input string to be checked for unique characters. * @return `true` if all characters in the string are unique, `false` otherwise. */ fun hasUniqueCharactersBest(string: String) = string.length == string.toSet().size /** * Determines whether a given string has all unique characters. * * Time complexity: O(n), where n is the number of characters in the string. * * @param string The input string to be checked for unique characters. * @return `true` if all characters in the string are unique, `false` otherwise. */ fun hasUniqueCharactersBetter(string: String): Boolean { //Assuming ASCII character set (8-bit) //The string can not have all unique characters if it's length is greater than 128 if (string.length > 128) { return false } val charSet = BooleanArray(128) for (char in string) { val index = char.code if (charSet[index]) { return false } charSet[index] = true } return true // All char are unique. } }
0
Kotlin
0
0
f83e929dfef941fbd8150c3ebc7c7c6fee60148b
3,360
kotlin-coding-interview
MIT License
src/main/kotlin/com/chriswk/aoc/advent2021/Day17.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.Pos import com.chriswk.aoc.util.report import com.chriswk.aoc.util.reportNano import kotlin.math.sign import kotlin.system.measureNanoTime import kotlin.system.measureTimeMillis class Day17: AdventDay(2021, 17) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day17() reportNano { day.part1() } report { day.part2() } val avgPart1 = (0.until(10)).map { measureNanoTime { day.part1() } }.average() val avgPart2 = (0.until(10)).map { measureTimeMillis { day.part2() } }.average() println("Part 1 average over 10 runs: $avgPart1 ns") println("Part 2 average over 10 runs: $avgPart2 ms") } val targetRegex = """target area: x=(-?\d+)\.\.(-?\d+), y=(-?\d+)..(-?\d+)""".toRegex() } data class Probe(val currentPos: Pos, val velocity: Pos) data class TargetArea(val minX: Int, val maxX: Int, val minY: Int, val maxY: Int) { operator fun contains(point: Pair<Int, Int>) = point.first in minX..maxX && point.second in minY..maxY } data class Velocity(val x: Int, val y: Int) { fun willBeWithin(target: TargetArea): Boolean { val seqX = seqX().takeWhile { (posX, _) -> posX <= target.maxX }.map { it.first } val seqY = seqY().takeWhile { (posY, _) -> posY >= target.minY }.map { it.first } return (seqX zip seqY).any { it in target } } private fun seqX() = generateSequence(0 to x) { (posX, velX) -> posX + velX to (velX - velX.sign) } private fun seqY() = generateSequence(0 to y) { (posY, velY) -> posY + velY to velY - 1 } } val gravity: Pos = Pos(0, -1) fun target(input: String): TargetArea { val (startX, endX, startY, endY) = targetRegex.find(input)!!.destructured val xes = listOf(startX.toInt(), endX.toInt()) val ys = listOf(startY.toInt(), endY.toInt()) return TargetArea(xes.minOf { it }, xes.maxOf { it }, ys.minOf { it }, ys.maxOf { it }) } val inputTarget = target(inputAsString) fun Int.gaussSum() = this * (this + 1) / 2 fun part1(): Int { return (- inputTarget.minY - 1).gaussSum() } fun part2(): Int { val minY = inputTarget.minY val maxY = -inputTarget.minY - 1 val minX = (1..inputTarget.minX).first { it.gaussSum() >= inputTarget.minX } val maxX = inputTarget.maxX return (minX..maxX).sumOf { x -> (minY..maxY).count { y -> Velocity(x, y).willBeWithin(inputTarget) } } } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,816
adventofcode
MIT License
codeforces/src/main/kotlin/contest1911/H.kt
austin226
729,634,548
false
{"Kotlin": 23837}
// https://codeforces.com/contest/1911/problem/H private fun String.splitWhitespace() = split("\\s+".toRegex()) private fun <T> List<T>.counts(): Map<T, Int> = this.groupingBy { it }.eachCount() private fun <T : Comparable<T>> List<T>.isStrictlyDecreasing(): Boolean = (size <= 1) || (1 until size).all { i -> get(i) < get(i - 1) } private fun <T : Comparable<T>> List<T>.isStrictlyIncreasing(): Boolean = (size <= 1) || (1 until size).all { i -> get(i) > get(i - 1) } /** Return 0 for each index whose member in a belongs to the increasing sequence. * 1 otherwise. null if not possible. */ fun findIncrSeqMembers(a: List<Int>, n: Int): List<Int>? { val res = MutableList(n) { 0 } var incrMax = Int.MIN_VALUE var decrMin = Int.MAX_VALUE if (n > 1 && a[0] >= a[1]) { res[0] = 1 decrMin = res[0] // TODO extend this using a while loop. Take all decreasing numbers into decr until we hit something that has to go into incr. // TODO that probably won't cover many cases... } for (k in a) { if (k < decrMin) { decrMin = k } else if (k > incrMax) { incrMax = k } else { return null } } return res } fun main() { val n = readln().toInt() val a = readln().splitWhitespace().map { it.toInt() } // If there are >2 of any input, print NO findIncrSeqMembers(a, n)?.let { println("YES") println(it.joinToString(" ")) return } println("NO") }
0
Kotlin
0
0
4377021827ffcf8e920343adf61a93c88c56d8aa
1,528
codeforces-kt
MIT License
src/main/kotlin/dev/bogwalk/batch7/Problem77.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch7 import dev.bogwalk.util.maths.primeNumbers /** * Problem 77: Prime Summations * * https://projecteuler.net/problem=77 * * Goal: Count the number of ways that N can be written as the sum of 1 or more primes. * * Constraints: 2 <= N <= 1000 * * e.g.: N = 5 * count = 2 -> {5, 3+2} * N = 10 * count = 5 -> {7+3, 5+5, 5+3+2, 3+3+2+2, 2+2+2+2+2} */ class PrimeSummations { /** * Project Euler specific implementation that requests the first integer that can be written * as the sum of primes in over 5000 different ways. */ fun firstPrimeSumCombo(): Int { var limit = 0 var result = -1 while (result == -1) { limit += 50 val allCounts = allPrimeSumCombos(limit) result = allCounts.indexOfFirst { it > 5000 } } return result } /** * Solution is identical to the bottom-up approach that found the number of ways a total could * be achieved, either using coins of different values (Batch 3 - Problem 31) or using * combinations of lesser value positive integers (Batch 7 - Problem 76). * * @return LongArray of prime partitions of all N <= limit, with index == N. */ fun allPrimeSumCombos(n: Int): LongArray { val primeCombosBySum = LongArray(n + 1).apply { this[0] = 1L } val primes = primeNumbers(n) for (prime in primes) { for (i in prime..n) { primeCombosBySum[i] += primeCombosBySum[i - prime] } } return primeCombosBySum } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
1,609
project-euler-kotlin
MIT License
year2019/day01/part2/src/main/kotlin/com/curtislb/adventofcode/year2019/day01/part2/Year2019Day01Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence. Apparently, you forgot to include additional fuel for the fuel you just added. Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing really hard, which has no mass and is outside the scope of this calculation. So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example: - A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so the total fuel required is still just 2. - At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966. - The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346. What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.) */ package com.curtislb.adventofcode.year2019.day01.part2 import com.curtislb.adventofcode.year2019.day01.fuel.calculateTotalFuel import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2019, day 1, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { var totalFuel = 0 inputPath.toFile().forEachLine { totalFuel += calculateTotalFuel(it.trim().toInt()) } return totalFuel } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,317
AdventOfCode
MIT License
src/Day02.kt
burtz
573,411,717
false
{"Kotlin": 10999}
enum class Moves(val points: Int) { Rock(1), Paper(2), Scissors(3) } enum class Result(val points: Int) { Win(6), Draw(3), Lose(0) } fun main() { // Rules // Opponents input: Rock A, Paper B, Scissors C // My input : Rock X (1 point), Paper Y (2 points), Scissors Z (3 points) // 0 for loss, 3 for draw, 6 for win val movesMap = mapOf("A" to Moves.Rock, "B" to Moves.Paper, "C" to Moves.Scissors, "X" to Moves.Rock, "Y" to Moves.Paper, "Z" to Moves.Scissors) fun winner(myMove:Moves?,oppMove:Moves?) : Int { if(myMove == Moves.Rock){ if(oppMove == Moves.Scissors) return Result.Win.points if(oppMove == Moves.Rock) return Result.Draw.points if(oppMove == Moves.Paper) return Result.Lose.points} if(myMove == Moves.Paper){ if(oppMove == Moves.Rock) return Result.Win.points if(oppMove == Moves.Paper) return Result.Draw.points if(oppMove == Moves.Scissors) return Result.Lose.points} if(myMove == Moves.Scissors){ if(oppMove == Moves.Paper) return Result.Win.points if(oppMove == Moves.Scissors) return Result.Draw.points if(oppMove == Moves.Rock) return Result.Lose.points} println("Error") return 0 } fun forced(myMove:String,oppMove:Moves?) : Int { if(oppMove == Moves.Rock){ if(myMove == "X") return Result.Lose.points + Moves.Scissors.points if(myMove == "Y") return Result.Draw.points + Moves.Rock.points if(myMove == "Z") return Result.Win.points + Moves.Paper.points} if(oppMove == Moves.Paper){ if(myMove == "X") return Result.Lose.points + Moves.Rock.points if(myMove == "Y") return Result.Draw.points + Moves.Paper.points if(myMove == "Z") return Result.Win.points + Moves.Scissors.points } if(oppMove == Moves.Scissors){ if(myMove == "X") return Result.Lose.points + Moves.Paper.points if(myMove == "Y") return Result.Draw.points + Moves.Scissors.points if(myMove == "Z") return Result.Win.points + Moves.Rock.points } println("Error") return 0 } fun part1(input: List<String>): Int { var currentScore = 0 input.forEach{ val myMove = movesMap[it[2].toString()] val oppoMove = movesMap[it[0].toString()] currentScore += (winner(myMove,oppoMove) + (myMove?.points ?:0 )) } return currentScore } fun part2(input: List<String>): Int { var currentScore = 0 input.forEach{ val myMove = it[2].toString() val oppoMove = movesMap[it[0].toString()] //println(myMove.toString() + " " + oppoMove.toString() + " " + myMove?.points + " " + winner(myMove,oppoMove)) currentScore += forced(myMove,oppoMove) } return currentScore } // 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
daac7f91e1069d1490e905ffe7b7f11b5935af06
3,250
adventOfCode2022
Apache License 2.0
src/main/kotlin/com/mobiento/aoc/Day03.kt
markburk
572,970,459
false
{"Kotlin": 22252}
package com.mobiento.aoc class Day03 { private val priority: Map<Char, Int> = hashMapOf<Char, Int>().apply { var priority = 0 for (c in 'a' .. 'z') { this[c] = ++priority } for (c in 'A' .. 'Z') { this[c] = ++priority } } fun part1(input: List<String>): Int { return input.sumOf { line -> getPriority(findCommonItem(getFirstCompartmentItems(line), getSecondCompartmentItems(line))) } } fun getFirstCompartmentItems(contents: String): String { return contents.substring(0, contents.length / 2) } fun getSecondCompartmentItems(contents: String): String { return contents.substring(contents.length / 2) } fun findCommonItem(firstItems: String, secondItems: String): Char { return firstItems.toSet().intersect(secondItems.toSet()).firstOrNull() ?: ' ' } fun getPriority(letter: Char): Int { return priority[letter] ?: 0 } fun part2(input: List<String>): Int { return input.windowed(3, 3).sumOf { getPriority(findCommonItem(it[0], it[1], it[2])) } } fun findCommonItem(first: String, second: String, third: String): Char { return first.toSet().intersect(second.toSet()).intersect(third.toSet()).firstOrNull() ?: ' ' } }
0
Kotlin
0
0
d28656b4d54c506a01252caf6b493e4f7f97e896
1,348
potential-lamp
Apache License 2.0
src/main/kotlin/com/colinodell/advent2021/Day21.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 import java.util.Stack import kotlin.math.max import kotlin.math.min class Day21(private val player1Start: Int, private val player2Start: Int) { val universesPerRoll = arrayOf(0, 0, 0, 1, 3, 6, 7, 6, 3, 1) fun solvePart1(): Int { var game = Game(Player(player1Start), Player(player2Start)) val dice = DeterministicDice() while (game.winningScore() < 1000) { game = game.nextTurn(dice.roll(3)) } return dice.timesRolled * game.losingScore() } fun solvePart2(): Long { val games = Stack<Game>() games.push(Game(Player(player1Start), Player(player2Start))) var winCountPlayer1 = 0L var winCountPlayer2 = 0L while (!games.empty()) { val game = games.pop() for (rolled in 3..9) { val nextGame = game.nextTurn(rolled) if (nextGame.winningScore() < 21) { games.push(nextGame) continue } if (nextGame.player1Wins()) { winCountPlayer1 += nextGame.universes } else { winCountPlayer2 += nextGame.universes } } } return max(winCountPlayer1, winCountPlayer2) } private inner class Player(val position: Int, val score: Int = 0) { fun move(rolled: Int): Player = (((position + rolled - 1) % 10) + 1).let { pos -> Player(pos, score + pos) } } private inner class Game(val player1: Player, val player2: Player, val player1Turn: Boolean = true, val universes: Long = 1) { fun nextTurn(rolled: Int): Game { val newUniverses = if (rolled < universesPerRoll.size) { universes * universesPerRoll[rolled] } else { universes } return if (player1Turn) { Game(player1.move(rolled), player2, false, newUniverses) } else { Game(player1, player2.move(rolled), true, newUniverses) } } fun winningScore() = max(player1.score, player2.score) fun losingScore() = min(player1.score, player2.score) fun player1Wins() = player1.score > player2.score } private class DeterministicDice() { var timesRolled: Int = 0 fun roll(times: Int) = (0 until times).sumOf { ++timesRolled } } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
2,455
advent-2021
Apache License 2.0
src/Day06.kt
b0n541
571,797,079
false
{"Kotlin": 17810}
fun main() { fun String.findMarker(length: Int) = this.indexOf( this.windowed(length, 1) .first { substring -> substring.toSet().size == length }) + length fun part1(input: List<String>): List<Int> { return input.map { it.findMarker(4) } } fun part2(input: List<String>): List<Int> { return input.map { it.findMarker(14) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") val input = readInput("Day06") val resultTest1 = part1(testInput) println("Test 1: $resultTest1") check(resultTest1 == listOf(7, 5, 6, 10, 11)) val resultPart1 = part1(input) println("Part 1: $resultPart1") check(resultPart1 == listOf(1134)) val resultTest2 = part2(testInput) println("Test 2: $resultTest2") check(resultTest2 == listOf(19, 23, 23, 29, 26)) val resultPart2 = part2(input) println("Part 2: $resultPart2") check(resultPart2 == listOf(2263)) }
0
Kotlin
0
0
d451f1aee157fd4d47958dab8a0928a45beb10cf
1,016
advent-of-code-2022
Apache License 2.0
problems/src/main/kotlin/org/fundamentals/fp/euler/EulerProblem03.kt
jabrena
171,358,482
false
{"HTML": 788595, "Java": 339834, "Kotlin": 16414, "Gherkin": 1092}
package org.fundamentals.fp.euler /** * Largest prime factor * https://projecteuler.net/problem=3 * * The prime factors of 13195 are 5, 7, 13 and 29. * * What is the largest prime factor of the number 600851475143 ? * * Scenario 13195 * * Given primeFactor * When 13195 * Then 29 [5, 7, 13, 29] * * Scenario 600851475143 * * Given primeFactor * When 600851475143 * Then ? */ fun KotlinSolution03(limit : Long) : Long { return limit.primeFactors().max()!! } /** * Checks if this number is a multiple of the provided number _(eg. this % other == 0)_. * * _Reference: [http://mathworld.wolfram.com/Multiple.html]_ * * @return true if the receiver is a multiple of the provided number */ infix fun Long.isMultipleOf(other: Long) = this % other == 0L /** * Returns the square root of the receiver _(eg. from Math.sqrt)_. * * _Reference: [http://mathworld.wolfram.com/SquareRoot.html]_ * * @return the square root of the receiver */ fun Double.squareRoot() = Math.sqrt(this) /** * @see [Double.squareRoot] */ fun Double.sqrt() = this.squareRoot() /** * Returns the integer part of the receiver _(eg. removes the decimal part)_. * * Example: `10.25 becomes 10` * * _Reference: [http://mathworld.wolfram.com/FloorFunction.html]_ * * @return the integer part of the receiver */ fun Double.floor() = this.toLong() /** * @see [Double.squareRoot] */ fun Long.sqrt() = this.toDouble().sqrt() /** * Checks if the receiver number is a prime number _(eg. only divisors are 1 and itself)_. * * _Reference: [http://mathworld.wolfram.com/PrimeNumber.html]_ * * @return true if the receiver number is a prime */ fun Long.isPrime() = this > 1 && (2..this.sqrt().floor()).all { !(this isMultipleOf it) } /** * Returns a List containing all prime factors of the receiver numbers _(eg. factorization of receiver into its consituent primes)_. * * _Reference: [http://mathworld.wolfram.com/PrimeFactor.html]_ * * @return a List containing all prime factors of the receiver number */ fun Long.primeFactors(): List<Long> = if (isPrime()) listOf(this) else { val nextPrimeFactor = (2..this.sqrt().floor()).find { this isMultipleOf it && it.isPrime() } if (nextPrimeFactor == null) emptyList() else listOf(nextPrimeFactor) + (this / nextPrimeFactor).primeFactors() }
3
HTML
3
8
c722696e1c7130527f2c4952cc37bb3a6c70e374
2,317
functional-rosetta-stone
Apache License 2.0
src/main/kotlin/nl/jackploeg/aoc/_2022/calendar/day12/Day12.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2022.calendar.day12 import javax.inject.Inject import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile class Day12 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(filename: String) = shortestPath(filename) fun partTwo(filename: String) = shortestPath(filename, true) fun shortestPath(fileName: String, stopAtA: Boolean = false): Int { val input = readStringFile(fileName) val grid: ArrayList<ArrayList<Cell>> = ArrayList() var start = Cell(-1, -1, '@', -1) var end = Cell(-1, -1, '@', -1) var gridWidth = 0 fun checkCell(y: Int, x: Int, compareCell: Cell, deque: ArrayDeque<Cell>) { if (x in 0 until gridWidth && y in 0 until grid.size) { val cell = grid[y][x] if (cell.distanceToEnd == -1 && (cell.level >= compareCell.level - 1) ) { cell.distanceToEnd = compareCell.distanceToEnd + 1 deque.add(cell) } } } // init grid for ((row, line) in input.withIndex()) { if (gridWidth == 0) gridWidth = line.length val cells = line.toCharArray() val lineCells: ArrayList<Cell> = ArrayList() for ((index, char) in cells.withIndex()) { when (char) { 'S' -> { val cell = Cell(index, row, 'a', -1) start = cell lineCells.add(cell) } 'E' -> { val cell = Cell(index, row, 'z', -1) end = cell lineCells.add(cell) } else -> { val cell = Cell(index, row, char, -1) lineCells.add(cell) } } } grid.add(lineCells) } // calc distanceToEnd to end val visitedCells: ArrayDeque<Cell> = ArrayDeque() visitedCells.add(end) end.distanceToEnd = 0 var pathLength = -1 while (!visitedCells.isEmpty()) { val cell = visitedCells.removeFirst() if (cell == start || (cell.level == 'a' && stopAtA)) { pathLength = cell.distanceToEnd break } checkCell(cell.y - 1, cell.x, cell, visitedCells) checkCell(cell.y + 1, cell.x, cell, visitedCells) checkCell(cell.y, cell.x - 1, cell, visitedCells) checkCell(cell.y, cell.x + 1, cell, visitedCells) } return pathLength } data class Cell(val x: Int, val y: Int, val level: Char, var distanceToEnd: Int) }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
2,924
advent-of-code
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem2090/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2090 /** * LeetCode page: [2090. K Radius Subarray Averages](https://leetcode.com/problems/k-radius-subarray-averages/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the size of nums; */ fun getAverages(nums: IntArray, k: Int): IntArray { if (k == 0) { return nums.clone() } val lessKRadiusAverage = -1 val result = IntArray(nums.size) { lessKRadiusAverage } val validCenterIndices = k until (nums.size - k) if (validCenterIndices.isEmpty()) { return result } // Apply sliding window technique val windowSize = k * 2 + 1 var windowSum = nums.sum(0 until windowSize) result[k] = quotient(windowSum, windowSize) for (centerIndex in (k + 1) until (nums.size - k)) { windowSum = windowSum - nums[centerIndex - k - 1] + nums[centerIndex + k] result[centerIndex] = quotient(windowSum, windowSize) } return result } private fun IntArray.sum(indexRange: IntRange): Long { return indexRange.fold(0L) { acc: Long, index: Int -> acc + this[index] } } private fun quotient(dividend: Long, divisor: Int): Int { return (dividend / divisor).toInt() } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,326
hj-leetcode-kotlin
Apache License 2.0
2021/src/day12/Solution.kt
vadimsemenov
437,677,116
false
{"Kotlin": 56211, "Rust": 37295}
package day12 import java.nio.file.Files import java.nio.file.Paths fun main() { fun buildGraph(lines: Input): Map<String, List<String>> = buildMap<String, MutableList<String>> { for (line in lines) { val (v, w) = line.split("-") val vList = getOrPut(v) { mutableListOf() } val wList = getOrPut(w) { mutableListOf() } vList.add(w) wList.add(v) } } fun dfs(vertex: String, graph: Map<String, List<String>>, visited: Set<String>, visitedTwice: Boolean): Int { if (vertex == "end") return 1 var sum = 0 for (next in graph[vertex]!!) { if (next !in visited) { val nextVisited = if (next.first().isLowerCase()) visited + next else visited sum += dfs(next, graph, nextVisited, visitedTwice) } else if (next != "start" && !visitedTwice) { sum += dfs(next, graph, visited, true) } } return sum } fun part1(lines: Input): Int { val graph = buildGraph(lines) return dfs("start", graph, setOf("start"), true) } fun part2(lines: Input): Int { val graph = buildGraph(lines) return dfs("start", graph, setOf("start"), false) } check(part1(readInput("test-input.txt")) == 226) check(part2(readInput("test-input.txt")) == 3509) println(part1(readInput("input.txt"))) println(part2(readInput("input.txt"))) } private fun readInput(s: String): Input { return Files.newBufferedReader(Paths.get("src/day12/$s")).readLines() } private typealias Input = List<String>
0
Kotlin
0
0
8f31d39d1a94c862f88278f22430e620b424bd68
1,496
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ImplementTrie.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT interface Trie { fun insert(word: String) fun search(word: String): Boolean fun startsWith(prefix: String): Boolean } class TrieArray : Trie { private val root = TrieNode() override fun insert(word: String) { var node: TrieNode? = root for (ch in word) { if (node?.containsKey(ch) != true) { node?.put(ch, TrieNode()) } node = node?.get(ch) } node?.isEnd = true } override fun search(word: String): Boolean { val node = searchPrefix(word) return node != null && node.isEnd } override fun startsWith(prefix: String): Boolean { val node = searchPrefix(prefix) return node != null } private fun searchPrefix(word: String): TrieNode? { var node: TrieNode? = root for (ch in word) { if (node?.containsKey(ch) == true) { node = node.get(ch) } else { return null } } return node } data class TrieNode(var isEnd: Boolean = false) { private val links: Array<TrieNode?> = Array(ALPHABET_LETTERS_COUNT) { null } fun containsKey(ch: Char): Boolean { return links[ch - 'a'] != null } fun get(ch: Char): TrieNode? { return links[ch - 'a'] } fun put(ch: Char, node: TrieNode?) { links[ch - 'a'] = node } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TrieNode return links.contentEquals(other.links) } override fun hashCode(): Int { return links.contentHashCode() } } } class TrieHashMap : Trie { private val head = TrieNode() /** * Inserts a word into the trie */ override fun insert(word: String) { var node: TrieNode? = head for (ch in word.toCharArray()) { if (node?.charToNode?.containsKey(ch)?.not() == true) { node.charToNode[ch] = TrieNode() } node = node?.charToNode?.get(ch) } node?.isEnd = true } /** * Returns if the word is in the trie */ override fun search(word: String): Boolean { var node = head for (ch in word.toCharArray()) { if (node.charToNode.containsKey(ch).not()) { return false } node = node.charToNode[ch] ?: return false } return node.isEnd } /** * Returns if there is any word in the trie that starts with the given prefix */ override fun startsWith(prefix: String): Boolean { var node = head for (ch in prefix.toCharArray()) { if (node.charToNode.containsKey(ch).not()) { return false } node = node.charToNode[ch] ?: return false } return true } data class TrieNode(val charToNode: MutableMap<Char, TrieNode> = HashMap(), var isEnd: Boolean = false) }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,854
kotlab
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem438/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem438 /** * LeetCode page: [438. Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/); */ class Solution { /* Complexity: * Time O(|s|) and Space O(1); */ fun findAnagrams(s: String, p: String): List<Int> { if (s.length < p.length) return emptyList() val startIndicesOfAnagrams = mutableListOf<Int>() val anagramCharCount = getCountOfEachChar(p) val windowCharCount = getCountOfEachChar(s, p.indices) var numMatchedChars = (0 until 26).count { windowCharCount[it] == anagramCharCount[it] } if (numMatchedChars == 26) startIndicesOfAnagrams.add(0) for (index in p.length until s.length) { val popCountIndex = s[index - p.length] - 'a' windowCharCount[popCountIndex]-- when (windowCharCount[popCountIndex]) { anagramCharCount[popCountIndex] -> numMatchedChars++ anagramCharCount[popCountIndex] - 1 -> numMatchedChars-- } val pushCountIndex = s[index] - 'a' windowCharCount[pushCountIndex]++ when (windowCharCount[pushCountIndex]) { anagramCharCount[pushCountIndex] -> numMatchedChars++ anagramCharCount[pushCountIndex] + 1 -> numMatchedChars-- } if (numMatchedChars == 26) { val windowStartIndex = index - p.length + 1 startIndicesOfAnagrams.add(windowStartIndex) } } return startIndicesOfAnagrams } private fun getCountOfEachChar(lowercase: String, indexRange: IntRange = lowercase.indices): IntArray { val charCount = IntArray(26) for (index in indexRange) { charCount[lowercase[index] - 'a']++ } return charCount } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,864
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2016/Day07.kt
tginsberg
74,924,040
false
null
/* * Copyright (c) 2016 by <NAME> */ package com.ginsberg.advent2016 /** * Advent of Code - Day 7: December 7, 2016 * * From http://adventofcode.com/2016/day/7 * */ class Day07(private val input: List<String>) { /** * How many IPs in your puzzle input support TLS? */ fun solvePart1(): Int = input.count { supportsTls(it) } /** * How many IPs in your puzzle input support SSL? */ fun solvePart2(): Int = input.count { supportsSsl(it) } private fun supportsTls(address: String): Boolean { val parts = toDelimitedParts(address) return parts.any { isAbba(it) } && parts.none { isHypernet(it) } } // I'm sure there is a better way to do this with Regex. private fun isAbba(part: String): Boolean = (0 until part.length-3) .filter { i -> part[i] == part[i+3] && part[i+1] == part[i+2] && part[i] != part[i+1] } .isNotEmpty() private fun isHypernet(part: String): Boolean = part.startsWith("[") && part.endsWith("]") && isAbba(part) private fun toDelimitedParts(address: String): List<String> = address.split(Regex("(?=\\[)|(?<=\\])")) private fun supportsSsl(address: String): Boolean { val parts = toDelimitedParts(address) val abas = parts .filter { !it.startsWith("[") } .fold(emptySet<String>()) { carry, next -> gatherAbas(next) + carry } val babs = parts .filter { it.startsWith("[") } .fold(emptySet<String>()) { carry, next -> gatherBabs(next) + carry } return abas.filter { babs.contains(it) }.isNotEmpty() } // I'm sure there is a better way to do this with Regex and capture groups. private fun gatherAbas(input: String): Set<String> = (0 until input.length-2) .map { i -> input.substring(i, i+3) } .filter { it[0] == it[2] && it[0] != it[1] } .toSet() private fun gatherBabs(input:String): Set<String> = gatherAbas(input).map { babToAba(it) }.toSet() private fun babToAba(input: String): String = listOf(input[1], input[0], input[1]).joinToString(separator = "") }
0
Kotlin
0
3
a486b60e1c0f76242b95dd37b51dfa1d50e6b321
2,259
advent-2016-kotlin
MIT License
src/Day01.kt
cnietoc
572,880,374
false
{"Kotlin": 15990}
fun main() { fun calculateElvesCalories(input: List<String>): MutableList<Long> { val elvesCalories = mutableListOf<Long>() var index = 0 input.forEach { if (it.isBlank()) { index++ } else { if (elvesCalories.getOrNull(index) == null) { elvesCalories.add(index, 0L) } elvesCalories[index] = elvesCalories[index] + it.toLong() } } return elvesCalories } fun part1(input: List<String>): Long { val elvesCalories = calculateElvesCalories(input) return elvesCalories.max() } fun part2(input: List<String>): Long { val elvesCalories = calculateElvesCalories(input) return elvesCalories.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000L) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bbd8e81751b96b37d9fe48a54e5f4b3a0bab5da3
1,083
aoc-2022
Apache License 2.0
kotlin/graphs/spanningtree/PrimHeap.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.spanningtree // https://en.wikipedia.org/wiki/Prim%27s_algorithm in O(E*log(V)) object PrimHeap { fun mst(edges: Array<List<Edge>?>, pred: IntArray): Long { val n = edges.size Arrays.fill(pred, -1) val used = BooleanArray(n) val prio = IntArray(n) Arrays.fill(prio, Integer.MAX_VALUE) prio[0] = 0 val q: PriorityQueue<Long> = PriorityQueue() q.add(0L) var res: Long = 0 while (!q.isEmpty()) { val cur: Long = q.poll() val u = cur.toInt() if (used[u]) continue used[u] = true res += cur ushr 32 for (e in edges[u]!!) { val v = e.t if (!used[v] && prio[v] > e.cost) { prio[v] = e.cost pred[v] = u q.add((prio[v].toLong() shl 32) + v) } } } return res } // Usage example fun main(args: Array<String?>?) { val cost = arrayOf(intArrayOf(0, 1, 2), intArrayOf(1, 0, 3), intArrayOf(2, 3, 0)) val n = cost.size val edges: Array<List<Edge>?> = arrayOfNulls(n) for (i in 0 until n) { edges[i] = ArrayList() for (j in 0 until n) { if (cost[i][j] != 0) { edges[i].add(Edge(j, cost[i][j])) } } } val pred = IntArray(n) System.out.println(mst(edges, pred)) } class Edge(var t: Int, var cost: Int) }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,558
codelibrary
The Unlicense
archive/524/solve.kt
daniellionel01
435,306,139
false
null
/* === #524 First Sort II - Project Euler === Consider the following algorithm for sorting a list: 1. Starting from the beginning of the list, check each pair of adjacent elements in turn. 2. If the elements are out of order: a. Move the smallest element of the pair at the beginning of the list. b. Restart the process from step 1. 3. If all pairs are in order, stop.For example, the list { 4 1 3 2 } is sorted as follows: 4 1 3 2 (4 and 1 are out of order so move 1 to the front of the list) 1 4 3 2 (4 and 3 are out of order so move 3 to the front of the list) 3 1 4 2 (3 and 1 are out of order so move 1 to the front of the list) 1 3 4 2 (4 and 2 are out of order so move 2 to the front of the list) 2 1 3 4 (2 and 1 are out of order so move 1 to the front of the list) 1 2 3 4 (The list is now sorted)Let F(L) be the number of times step 2a is executed to sort list L. For example, F({ 4 1 3 2 }) = 5. We can list all permutations P of the integers {1, 2, ..., n} in lexicographical order, and assign to each permutation an index In(P) from 1 to n! corresponding to its position in the list. Let Q(n, k) = min(In(P)) for F(P) = k, the index of the first permutation requiring exactly k steps to sort with First Sort. If there is no permutation for which F(P) = k, then Q(n, k) is undefined. For n = 4 we have: PI4(P)F(P){1, 2, 3, 4}10Q(4, 0) = 1{1, 2, 4, 3}24Q(4, 4) = 2{1, 3, 2, 4}32Q(4, 2) = 3{1, 3, 4, 2}42{1, 4, 2, 3}56Q(4, 6) = 5{1, 4, 3, 2}64{2, 1, 3, 4}71Q(4, 1) = 7{2, 1, 4, 3}85Q(4, 5) = 8{2, 3, 1, 4}91{2, 3, 4, 1}101{2, 4, 1, 3}115{2, 4, 3, 1}123Q(4, 3) = 12{3, 1, 2, 4}133{3, 1, 4, 2}143{3, 2, 1, 4}152{3, 2, 4, 1}162{3, 4, 1, 2}173{3, 4, 2, 1}182{4, 1, 2, 3}197Q(4, 7) = 19{4, 1, 3, 2}205{4, 2, 1, 3}216{4, 2, 3, 1}224{4, 3, 1, 2}234{4, 3, 2, 1}243Let R(k) = min(Q(n, k)) over all n for which Q(n, k) is defined. Find R(1212). Difficulty rating: 75% */ fun solve(x: Int): Int { return x*2; } fun main() { val a = solve(10); println("solution: $a"); }
0
Kotlin
0
1
1ad6a549a0a420ac04906cfa86d99d8c612056f6
1,985
euler
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/EliminateMaxNumOfMonsters.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue /** * 1921. Eliminate Maximum Number of Monsters * @see <a href="https://leetcode.com/problems/eliminate-maximum-number-of-monsters">Source</a> */ fun interface EliminateMaxNumOfMonsters { operator fun invoke(dist: IntArray, speed: IntArray): Int } sealed interface EliminateMaximumStrategy { /** * Approach 1: Sort By Arrival Time */ data object Sort : EliminateMaxNumOfMonsters, EliminateMaximumStrategy { override fun invoke(dist: IntArray, speed: IntArray): Int { val arrival = DoubleArray(dist.size) for (i in dist.indices) { arrival[i] = dist[i].toDouble() / speed[i] } arrival.sort() var ans = 0 for (i in arrival.indices) { if (arrival[i] <= i) { break } ans++ } return ans } } /** * Approach 2: Heap */ data object Heap : EliminateMaxNumOfMonsters, EliminateMaximumStrategy { override fun invoke(dist: IntArray, speed: IntArray): Int { val heap: PriorityQueue<Double> = PriorityQueue() for (i in dist.indices) { heap.add(dist[i].toDouble() / speed[i]) } var ans = 0 while (heap.isNotEmpty()) { if (heap.remove() <= ans) { break } ans++ } return ans } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,177
kotlab
Apache License 2.0
code/data_structures/SparseMinTable.kt
hakiobo
397,069,173
false
null
private class SparseMinTable(val nums: IntArray) { val n = nums.size val table = Array( ((n shl 2) - 1).takeHighestOneBit().countTrailingZeroBits() ) { IntArray(n) } init { for (x in 0 until n) { table[0][x] = x } for (bit in 1 until table.size) { val pow = 1 shl bit for (x in 0..n - pow) { val a = table[bit - 1][x] val b = table[bit - 1][x + (pow shr 1)] if (nums[a] <= nums[b]) { table[bit][x] = a } else { table[bit][x] = b } } } } fun getMinRange(start: Int, end: Int): Int { return if (start <= end) { val dif = end - start + 1 val high = dif.takeHighestOneBit() val bit = high.countTrailingZeroBits() if (high == dif) { table[bit][start] } else { val a = table[bit][start] val b = table[bit][end - high + 1] if (nums[a] <= nums[b]) a else b } } else { -1 } } }
0
Kotlin
1
2
f862cc5e7fb6a81715d6ea8ccf7fb08833a58173
1,220
Kotlinaughts
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2022/Day18.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.math.max import kotlin.math.min import kotlin.test.assertEquals object Day18 : AbstractDay() { @Test fun part1Test() { assertEquals(64, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(4310, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(58, compute2(testInput)) } @Test fun part2Puzzle() { assertEquals(2466, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { var surfaceArea = 0 val blocks = mutableSetOf<Block>() input .map { Block.of(it) } .forEach { block -> val connectedBlocks = block.adjacentBlocks .count { blocks.contains(it) } surfaceArea -= connectedBlocks surfaceArea += 6 - connectedBlocks blocks.add(block) } return surfaceArea } private fun compute2(input: List<String>): Int { val container = Container() input .map { Block.of(it) } .forEach { container.include(it) } return container.determineSurfaceCount() } private class Container { private val rocks: MutableSet<Block> = mutableSetOf() private var minPos = Block(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE) private var maxPos = Block(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE) fun include(block: Block) { rocks.add(block) adjustTo(block) } private fun adjustTo(block: Block) { // container should include a padding of 1 hence the 1 correction minPos = Block( x = min(minPos.x, block.x - 1), y = min(minPos.y, block.y - 1), z = min(minPos.z, block.z - 1), ) maxPos = Block( x = max(maxPos.x, block.x + 1), y = max(maxPos.y, block.y + 1), z = max(maxPos.z, block.z + 1), ) } fun determineSurfaceCount(): Int { var surfaceCount = 0 val queue = mutableListOf<Block>() val water = mutableSetOf<Block>() queue.add(minPos) while (queue.isNotEmpty()) { val currentWater = queue.removeFirst() val blocksNextToWater = currentWater.adjacentBlocks .filter { isInBounds(it) } .count { rocks.contains(it) } surfaceCount += blocksNextToWater currentWater .adjacentBlocks .filter { isInBounds(it) } .filterNot { rocks.contains(it) } .forEach { adjacentWater -> if (!water.contains(adjacentWater)) { water.add(adjacentWater) queue.add(adjacentWater) } } } return surfaceCount } private fun isInBounds(block: Block): Boolean { val xInbound = minPos.x <= block.x && block.x <= maxPos.x val yInbound = minPos.y <= block.y && block.y <= maxPos.y val zInbound = minPos.z <= block.z && block.z <= maxPos.z return xInbound && yInbound && zInbound } } data class Block( val x: Int, val y: Int, val z: Int, ) { val adjacentBlocks: List<Block> get() { return listOf( copy(x = x + 1), copy(x = x - 1), copy(y = y + 1), copy(y = y - 1), copy(z = z + 1), copy(z = z - 1), ) } companion object { fun of(s: String): Block { return s.split(",").let { (x, y, z) -> Block(x.toInt(), y.toInt(), z.toInt()) } } } } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
4,159
aoc
Apache License 2.0
src/main/kotlin/day5.kt
Gitvert
433,947,508
false
{"Kotlin": 82286}
const val SIZE = 1000 fun day5() { val lines: List<String> = readFile("day05.txt") day5part1(lines) day5part2(lines) } fun day5part1(lines: List<String>) { val answer = findAnswer(lines, false) println("5a: $answer") } fun day5part2(lines: List<String>) { val answer = findAnswer(lines, true) println("5b: $answer") } fun findAnswer(lines: List<String>, considerDiagonal: Boolean): Int { val lineSegments: MutableList<LineSegment> = mutableListOf() val oceanFloor = initOceanFloor() lines.forEach { lineSegments.add(inputToLineSegment(it.split(" -> "))) } val horizontalAndVerticalLineSegments = lineSegments.filter { it.start.x == it.end.x || it.start.y == it.end.y } horizontalAndVerticalLineSegments.forEach { lineSegment -> getCoordinatesFromHorizontalAndVerticalLineSegment(lineSegment).forEach { coordinate -> oceanFloor.matrix[coordinate.x][coordinate.y]++ } } if (considerDiagonal) { val diagonalLineSegments = lineSegments.filter { it.start.x != it.end.x && it.start.y != it.end.y } diagonalLineSegments.forEach { lineSegment -> getCoordinatesFromDiagonalLineSegment(lineSegment).forEach { coordinate -> oceanFloor.matrix[coordinate.x][coordinate.y]++ } } } return findOverlaps(oceanFloor) } fun inputToLineSegment(inputs: List<String>): LineSegment { val startList = inputs[0].split(",").map{ Integer.valueOf(it) } val endList = inputs[1].split(",").map{ Integer.valueOf(it) } return LineSegment( Coordinate(startList[0], startList[1]), Coordinate(endList[0], endList[1]) ) } fun initOceanFloor(): OceanFloor { return OceanFloor(Array(SIZE) { IntArray(SIZE) { 0 } }) } fun getCoordinatesFromHorizontalAndVerticalLineSegment(lineSegment: LineSegment): List<Coordinate> { val coordinates: MutableList<Coordinate> = mutableListOf() var orderedLineSegment = lineSegment if (lineSegment.start.x > lineSegment.end.x || lineSegment.start.y > lineSegment.end.y) { orderedLineSegment = LineSegment( Coordinate(lineSegment.end.x, lineSegment.end.y), Coordinate(lineSegment.start.x, lineSegment.start.y), ) } if (orderedLineSegment.start.x == orderedLineSegment.end.x) { for (i in orderedLineSegment.start.y..orderedLineSegment.end.y) { coordinates.add(Coordinate(orderedLineSegment.start.x, i)) } } else { for (i in orderedLineSegment.start.x..orderedLineSegment.end.x) { coordinates.add(Coordinate(i, orderedLineSegment.start.y)) } } return coordinates } fun getCoordinatesFromDiagonalLineSegment(lineSegment: LineSegment): List<Coordinate> { val coordinates: MutableList<Coordinate> = mutableListOf() var orderedLineSegment = lineSegment if (lineSegment.start.x > lineSegment.end.x) { orderedLineSegment = LineSegment( Coordinate(lineSegment.end.x, lineSegment.end.y), Coordinate(lineSegment.start.x, lineSegment.start.y), ) } val steps = orderedLineSegment.end.x - orderedLineSegment.start.x if (orderedLineSegment.start.y > orderedLineSegment.end.y) { for (i in 0..steps) { coordinates.add(Coordinate(orderedLineSegment.start.x + i, orderedLineSegment.start.y - i)) } } else { for (i in 0..steps) { coordinates.add(Coordinate(orderedLineSegment.start.x + i, orderedLineSegment.start.y + i)) } } return coordinates } fun findOverlaps(oceanFloor: OceanFloor): Int { var answer = 0 for (i in 0 until SIZE) { for (j in 0 until SIZE) { if (oceanFloor.matrix[i][j] > 1) { answer++ } } } return answer } data class Coordinate(val x: Int, val y: Int) data class LineSegment(val start: Coordinate, val end: Coordinate) data class OceanFloor(val matrix: Array<IntArray>)
0
Kotlin
0
0
02484bd3bcb921094bc83368843773f7912fe757
4,016
advent_of_code_2021
MIT License
src/main/kotlin/g2101_2200/s2106_maximum_fruits_harvested_after_at_most_k_steps/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2106_maximum_fruits_harvested_after_at_most_k_steps // #Hard #Array #Binary_Search #Prefix_Sum #Sliding_Window // #2023_06_25_Time_816_ms_(100.00%)_Space_107.6_MB_(100.00%) class Solution { fun maxTotalFruits(fruits: Array<IntArray>, startPos: Int, k: Int): Int { var res = 0 var sum = 0 var left = 0 for (right in fruits.indices) { sum += fruits[right][1] while (left <= right && !isValidRange(fruits[left][0], fruits[right][0], startPos, k)) { sum -= fruits[left++][1] } res = Math.max(sum, res) } return res } private fun isValidRange(leftPos: Int, rightPos: Int, startPos: Int, k: Int): Boolean { val result: Boolean result = if (rightPos <= startPos) { startPos - leftPos <= k } else if (leftPos >= startPos) { rightPos - startPos <= k } else { val left = startPos - leftPos val right = rightPos - startPos if (left <= right) left * 2 + right <= k else right * 2 + left <= k } return result } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,159
LeetCode-in-Kotlin
MIT License
aoc-2023/src/main/kotlin/aoc/aoc16.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.* val testInput = """ .|...\.... |.-.\..... .....|-... ........|. .......... .........\ ..../.\\.. .-.-/..|.. .|....-|.\ ..//.|.... """.parselines class LaserMaze(val lines: CharGrid) { fun at(c: Coord) = lines.getOrNull(c.y)?.getOrNull(c.x) fun at(x: Int, y: Int) = lines.getOrNull(y)?.getOrNull(x) } // part 1 fun List<String>.part1(print: Boolean, initPos: Coord = Coord(-1, 0), initDir: Coord = Coord(1, 0)): Int { val maze = LaserMaze(this) val accumulated = mutableSetOf<Pair<Coord, Coord>>() var lastAccumulated = setOf<Pair<Coord, Coord>>() var paths = setOf(initPos to initDir) while (paths.isNotEmpty() && (lastAccumulated.isEmpty() || lastAccumulated != accumulated)) { lastAccumulated = accumulated.toSet() val nextPaths = mutableSetOf<Pair<Coord, Coord>>() paths.forEach { val nxt = it.first + it.second val spc = maze.at(nxt) when { spc == null -> { } // out of maze, ignore spc == '.' -> { nextPaths += nxt to it.second } spc == '|' && it.second.x == 0 -> { nextPaths += nxt to it.second } spc == '-' && it.second.y == 0 -> { nextPaths += nxt to it.second } spc == '|' -> { nextPaths += nxt to DOWN nextPaths += nxt to UP } spc == '-' -> { nextPaths += nxt to RIGHT nextPaths += nxt to LEFT } spc == '/' -> { nextPaths += nxt to Coord(-it.second.y, -it.second.x) } spc == '\\' -> { nextPaths += nxt to Coord(it.second.y, it.second.x) } } } val newPaths = nextPaths - accumulated accumulated.addAll(newPaths) paths = newPaths // print maze if (print) { println("-".repeat(maze.lines[0].length)) maze.lines.forEachIndexed { y, row -> val rowWithPaths = row.indices.map { x -> val coord = Coord(x, y) val acc = accumulated.filter { it.first == coord }.map { it.second } if (acc.isEmpty() || maze.at(coord) != '.') maze.at(coord) else if (acc.size == 1) { when (acc.first()) { DOWN -> 'v' UP -> '^' RIGHT -> '>' LEFT -> '<' else -> throw Exception("bad path") } } else acc.size.toString()[0] } println(rowWithPaths.joinToString("")) } } } if (print) println("-".repeat(maze.lines[0].length)) return accumulated.map { it.first }.toSet().size } // part 2 fun List<String>.part2(): Int { val maze = LaserMaze(this) val max1 = maze.lines.yrange.maxOf { y -> print("..") maxOf( part1(false, Coord(-1, y), RIGHT), part1(false, Coord(maze.lines.xrange.last + 1, y), LEFT) ) } println("half done") val max2 = maze.lines.xrange.maxOf { x -> print("..") maxOf( part1(false, Coord(x, -1), DOWN), part1(false, Coord(x, maze.lines.yrange.last + 1), UP) ) } println("done") return maxOf(max1, max2) } // calculate answers val day = 16 val input = getDayInput(day, 2023) val testResult = testInput.part1(true).also { it.print } val testResult2 = testInput.part2().also { it.print } val answer1 = input.part1(false).also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
4,091
advent-of-code
Apache License 2.0
src/Day09.kt
dustinlewis
572,792,391
false
{"Kotlin": 29162}
import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { // starting position counts as visited val tailVisits = mutableSetOf<Position>() var headPosition = Position(0, 0) var tailPosition = Position(0, 0) tailVisits.add(tailPosition) val moves = input.map { val split = it.split(" ") Pair(split[0], split[1].toInt()) } //println(moves) moves.forEach { (direction, count) -> for (i in 1..count) { when (direction) { "L" -> { headPosition = Position(headPosition.first - 1, headPosition.second) tailPosition = getNewTailPosition(headPosition, tailPosition) tailVisits.add(tailPosition) } "R" -> { headPosition = Position(headPosition.first + 1, headPosition.second) tailPosition = getNewTailPosition(headPosition, tailPosition) tailVisits.add(tailPosition) } "U" -> { headPosition = Position(headPosition.first, headPosition.second + 1) tailPosition = getNewTailPosition(headPosition, tailPosition) tailVisits.add(tailPosition) } "D" -> { headPosition = Position(headPosition.first, headPosition.second - 1) tailPosition = getNewTailPosition(headPosition, tailPosition) tailVisits.add(tailPosition) } } } } return tailVisits.count() } fun part2(input: List<String>): Int { // starting position counts as visited val tailVisits = mutableSetOf<Position>() val startPosition = Position(0, 0) val positions = (0..9).associateWith { startPosition }.toMutableMap() //println(positions) tailVisits.add(startPosition) val moves = input.map { val split = it.split(" ") Pair(split[0], split[1].toInt()) } //println(moves) moves.forEach { (direction, count) -> for (c in 1..count) { when (direction) { "L" -> { val headPosition = positions[0]!! positions[0] = Position(headPosition.first - 1, headPosition.second) for(i in 1..9) { positions[i] = getNewTailPosition(positions[i - 1]!!, positions[i]!!) } tailVisits.add(positions[9]!!) } "R" -> { val headPosition = positions[0]!! positions[0] = Position(headPosition.first + 1, headPosition.second) for(i in 1..9) { positions[i] = getNewTailPosition(positions[i - 1]!!, positions[i]!!) } tailVisits.add(positions[9]!!) } "U" -> { val headPosition = positions[0]!! positions[0] = Position(headPosition.first, headPosition.second + 1) for(i in 1..9) { positions[i] = getNewTailPosition(positions[i - 1]!!, positions[i]!!) } tailVisits.add(positions[9]!!) } "D" -> { val headPosition = positions[0]!! positions[0] = Position(headPosition.first, headPosition.second - 1) for(i in 1..9) { positions[i] = getNewTailPosition(positions[i - 1]!!, positions[i]!!) } tailVisits.add(positions[9]!!) } } // println(positions) // // print the Day09test2 grid after each move // var bridge = "" // for(r in 4 downTo 0) { // for(c in 0..5) { // val rope = positions.toList().find { it.second == Pair(c, r) } // bridge += rope?.first?.toString() ?: "." // } // } // bridge.windowed(6, 6).forEach(::println) } } return tailVisits.count() } val input = readInput("Day09") println(part1(input)) println(part2(input)) } // Row, Column typealias Position = Pair<Int, Int> fun getNewTailPosition(head: Position, tail: Position): Position { val xDiff = abs(head.first - tail.first) val yDiff = abs(head.second - tail.second) if(xDiff > 1 && yDiff > 1) { return Position( if(head.first < tail.first) tail.first - 1 else tail.first + 1, if(head.second < tail.second) tail.second - 1 else tail.second + 1 ) } if(xDiff > 1) { return Position( if(head.first < tail.first) tail.first - 1 else tail.first + 1, head.second ) } if(yDiff > 1) { return Position( head.first, if(head.second < tail.second) tail.second - 1 else tail.second + 1 ) } return tail }
0
Kotlin
0
0
c8d1c9f374c2013c49b449f41c7ee60c64ef6cff
5,494
aoc-2022-in-kotlin
Apache License 2.0
src/chapter5/section2/TrieSTIterative.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section2 import chapter5.section1.Alphabet import edu.princeton.cs.algs4.Queue import edu.princeton.cs.algs4.Stack /** * 基于单词查找树的符号表(非递归实现) */ open class TrieSTIterative<V : Any>(protected val alphabet: Alphabet) : StringST<V> { protected inner class Node { val next = arrayOfNulls<Node>(alphabet.R()) var value: V? = null fun nextNum(): Int { var i = 0 next.forEach { if (it != null) i++ } return i } } protected val root = Node() protected var size = 0 override fun put(key: String, value: V) { var node = root for (i in key.indices) { val index = alphabet.toIndex(key[i]) var nextNode = node.next[index] if (nextNode == null) { nextNode = Node() node.next[index] = nextNode } node = nextNode } if (node.value == null) size++ node.value = value } override fun get(key: String): V? { var node = root for (i in key.indices) { val index = alphabet.toIndex(key[i]) val nextNode = node.next[index] ?: return null node = nextNode } return node.value } override fun delete(key: String) { val parents = arrayOfNulls<Node>(key.length) var node = root for (i in key.indices) { parents[i] = node val index = alphabet.toIndex(key[i]) val nextNode = node.next[index] ?: throw NoSuchElementException() node = nextNode } if (node.value == null) throw NoSuchElementException() node.value = null size-- for (i in parents.size - 1 downTo 0) { if (node.value == null && node.nextNum() == 0) { val index = alphabet.toIndex(key[i]) parents[i]!!.next[index] = null node = parents[i]!! } else { break } } } override fun contains(key: String): Boolean { return get(key) != null } override fun isEmpty(): Boolean { return size == 0 } override fun size(): Int { return size } override fun keys(): Iterable<String> { val queue = Queue<String>() // 树的非递归前序遍历 val nodeStack = Stack<Node>() val keyStack = Stack<String>() nodeStack.push(root) keyStack.push("") while (!nodeStack.isEmpty) { val node = nodeStack.pop() val key = keyStack.pop() if (node.value != null) { queue.enqueue(key) } for (i in alphabet.R() - 1 downTo 0) { if (node.next[i] != null) { nodeStack.push(node.next[i]) keyStack.push(key + alphabet.toChar(i)) } } } return queue } override fun longestPrefixOf(s: String): String? { var node = root var longestKey: String? = if (node.value == null) null else "" for (i in s.indices) { val index = alphabet.toIndex(s[i]) val nextNode = node.next[index] ?: break if (nextNode.value != null) { longestKey = s.substring(0, i + 1) } node = nextNode } return longestKey } override fun keysWithPrefix(s: String): Iterable<String> { val queue = Queue<String>() // get()方法中的代码 var node = root for (i in s.indices) { val index = alphabet.toIndex(s[i]) val nextNode = node.next[index] ?: return queue node = nextNode } // keys()方法中的代码,只是初始值不同 val nodeStack = Stack<Node>() val keyStack = Stack<String>() nodeStack.push(node) // 这里从node结点开始遍历 keyStack.push(s) // 这里起始值是s while (!nodeStack.isEmpty) { val topNode = nodeStack.pop() val key = keyStack.pop() if (topNode.value != null) { queue.enqueue(key) } for (i in alphabet.R() - 1 downTo 0) { if (topNode.next[i] != null) { nodeStack.push(topNode.next[i]) keyStack.push(key + alphabet.toChar(i)) } } } return queue } override fun keysThatMatch(s: String): Iterable<String> { val queue = Queue<String>() // 树的广度优先遍历(遍历时筛选) val nodeQueue = Queue<Node>() val keyQueue = Queue<String>() nodeQueue.enqueue(root) keyQueue.enqueue("") for (char in s) { // count为树每层符合条件的结点数 val count = nodeQueue.size() // 遍历过程中会继续向nodeQueue中添加数据,不能用!nodeQueue.isEmpty()判断 repeat(count) { val node = nodeQueue.dequeue() val key = keyQueue.dequeue() if (char == '.') { for (j in 0 until alphabet.R()) { val nextNode = node.next[j] ?: continue nodeQueue.enqueue(nextNode) keyQueue.enqueue(key + alphabet.toChar(j)) } } else { val nextNode = node.next[alphabet.toIndex(char)] if (nextNode != null) { nodeQueue.enqueue(nextNode) keyQueue.enqueue(key + char) } } } } while (!nodeQueue.isEmpty) { val node = nodeQueue.dequeue() val key = keyQueue.dequeue() if (node.value != null) { queue.enqueue(key) } } return queue } } fun main() { testStringST { TrieSTIterative(Alphabet.EXTENDED_ASCII) } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
6,145
Algorithms-4th-Edition-in-Kotlin
MIT License
advent08/src/Registers.kt
mike10004
113,916,865
false
{"JavaScript": 102872, "C": 9916, "Python": 9458, "Java": 6985, "Go": 3689, "Kotlin": 2536, "Shell": 534}
import java.io.File import java.io.FileReader import java.util.stream.Stream fun main(args: Array<String>) { FileReader(File("./input.txt")).buffered().use { main(it.lines()) } } fun doExample() { val lines = listOf( "b inc 5 if a > 1", "a inc 1 if b < 5", "c dec -10 if a >= 1", "c inc -20 if c == 10" ) main(lines.stream()) } fun main(instructionLines: Stream<String>) { val registers = HashMap<String, Int>() var overallMax = Int.MIN_VALUE instructionLines.forEach({ line -> parseInstruction(line).perform(registers) val currentMax = registers.values.max() ?: Int.MIN_VALUE if (currentMax > overallMax) { overallMax = currentMax } }) println(registers) val maxValue = registers.values.max() println("current max value is $maxValue") println("overall max value seen is $overallMax") } enum class Operator(val token : String) { GT(">"), LT("<"), GTE(">="), LTE("<="), EQ("=="), NE("!=") } fun parseOperator(token: String) : Operator { Operator.values() .filter { token == it.token } .forEach { return it } throw IllegalArgumentException("token does not represent an operator: " + token); } class Condition( val label : String, val operator : Operator, val reference : Int ) { fun evaluate(registers: Map<String, Int>) : Boolean { val query = registers.getOrDefault(label, 0) return when (operator) { Operator.GT -> query > reference Operator.GTE -> query >= reference Operator.LT -> query < reference Operator.LTE -> query <= reference Operator.EQ -> query == reference Operator.NE -> query != reference } } } class Instruction( val target: String, val delta: Int, val condition : Condition ) { fun perform(registers: MutableMap<String, Int>) { var value = registers.getOrDefault(target, 0) if (condition.evaluate(registers)) { value += delta } registers.put(target, value) } } fun parseInstruction(line: String): Instruction { val tokens = line.split(Regex("\\s+")) val delta = tokens[2].toInt() * (if ("inc" == tokens[1]) 1 else -1) val condition = Condition(tokens[4], parseOperator(tokens[5]), tokens[6].toInt()) return Instruction(tokens[0], delta, condition) }
0
JavaScript
0
0
977c5c16c90e612447d0842c197d90d35c7e63f7
2,536
adventofcode2017
MIT License
src/main/kotlin/adventofcode/day19/Blueprint.kt
jwcarman
573,183,719
false
{"Kotlin": 183494}
/* * Copyright (c) 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 adventofcode.day19 import adventofcode.util.removeAll import adventofcode.util.search.bnb.BranchAndBound import kotlin.math.max data class Blueprint(val id: Int, val catalog: Map<Currency, Currency>) { val maxCosts = catalog.values.fold(Currency()) { acc, cost -> Currency( max(acc.ore, cost.ore), max(acc.clay, cost.clay), max(acc.obsidian, cost.obsidian) ) } fun calculateMaximum(minutes: Int): Int { val answer = BranchAndBound.maximumSearch( OreCollectionSearchNode( minutes, Currency(), Currency(ore = 1), this ), -1 ) return answer.value() } fun affordable(balance: Currency): List<Pair<Currency, Currency>> { val affordable = catalog .filter { (_, cost) -> balance.exceeds(cost) } .map { (robots, cost) -> Pair(cost, robots) } return affordable } fun qualityLevel(minutes: Int): Int { val maximum = calculateMaximum(minutes) val answer = id * maximum return answer } companion object { fun parseBlueprint(input: String): Blueprint { val splits = input.removeAll( "Blueprint ", ": Each ore robot costs", " ore. Each clay robot costs", " ore. Each obsidian robot costs", " ore and", " clay. Each geode robot costs", " obsidian." ).split(' ') return Blueprint( splits[0].toInt(), mapOf( Currency(ore = 1) to Currency(ore = splits[1].toInt()), Currency(clay = 1) to Currency(ore = splits[2].toInt()), Currency(obsidian = 1) to Currency(ore = splits[3].toInt(), clay = splits[4].toInt()), Currency(geode = 1) to Currency(ore = splits[5].toInt(), obsidian = splits[6].toInt()) ) ) } } }
0
Kotlin
0
0
d6be890aa20c4b9478a23fced3bcbabbc60c32e0
2,660
adventofcode2022
Apache License 2.0
src/Day01.kt
Feketerig
571,677,145
false
{"Kotlin": 14818}
fun main() { fun readCalories(input: List<String>): List<Int>{ val calories = mutableListOf<Int>() var calorie = 0 input.forEach {line -> if (line.isEmpty()){ calories.add(calorie) calorie = 0 }else{ calorie += line.toInt() } } calories.add(calorie) return calories } fun part1(input: List<String>): Int { val calories = readCalories(input) return calories.max() } fun part2(input: List<String>): Int { val calories = readCalories(input) return calories.sortedDescending().subList(0,3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test_input") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c65e4022120610d930293788d9584d20b81bc4d7
979
Advent-of-Code-2022
Apache License 2.0
src/2/2667.kt
xCrypt0r
287,291,199
false
null
/** * 2667. 단지번호붙이기 * * 작성자: <NAME> * 언어: Kotlin (JVM) * 사용 메모리: 20,200 KB * 소요 시간: 176 ms * 해결 날짜: 2020년 9월 29일 */ import java.util.Scanner fun main() { val scanner = Scanner(System.`in`) val mapSize = scanner.nextLine().toInt() val map = Array(mapSize) { scanner.nextLine().toCharArray().map { it.toString().toInt() }.toIntArray() } scanner.close() val complexes = searchEngine(map, mapSize) println(complexes) if (complexes > 0) { val houseCount = searchHouses(map, complexes).sorted() for (i in houseCount.indices) { println(houseCount[i]) } } else { println(0) } } fun searchEngine(map: Array<IntArray>, mapSize: Int): Int { var complexId = 2 var complexes = 0 for (i in map.indices) { for (j in map[i].indices) { if (map[i][j] == 1) { searchMap(map, i, j, mapSize, complexId) complexes++ complexId++ } } } return complexes } fun searchMap(map: Array<IntArray>, i: Int, j: Int, mapSize: Int, complexId: Int) { if (i in 0 until mapSize && j in 0 until mapSize && map[i][j] == 1 ) { map[i][j] = complexId searchMap(map, i - 1, j, mapSize, complexId) searchMap(map, i + 1, j, mapSize, complexId) searchMap(map, i, j - 1, mapSize, complexId) searchMap(map, i, j + 1, mapSize, complexId) } else { return } } fun searchHouses(map: Array<IntArray>, complexes: Int): IntArray { val houseCount = IntArray(complexes) for (i in map.indices) { for (j in map[i].indices) { if (map[i][j] >= 2) { houseCount[map[i][j] - 2]++ } } } return houseCount }
5
C++
9
13
7d858d557dbbde6603fe4e8af2891c2b0e1940c0
1,865
Baekjoon
MIT License
src/day05/Day05Answer2.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day05 import readString /** * Answers from [Advent of Code 2022 Day 5 | Kotlin](https://youtu.be/lKq6r5Nt8Yo) */ val input = readString("day05").split("\n\n") fun main() { val (initialStackDescription, instructions) = input val initialStacks = initialStackDescription.lines().dropLast(1).reversed().map { it.toCrates() } val workingStacks = List(9) { ArrayDeque<Char>() } for (row in initialStacks) { for ((idx, char) in row.withIndex()) { if (char == null) continue workingStacks[idx].addLast(char) } } val part1WorkingStacks = workingStacks.map { ArrayDeque(it) } val part2WorkingStacks = workingStacks.map { ArrayDeque(it) } instructions.lines().forEach { it.toInstruction().executeAsPart1(part1WorkingStacks) } println(part1WorkingStacks.joinToString("") { "${it.last()}" }) // BZLVHBWQF instructions.lines().forEach { it.toInstruction().executeAsPart2(part2WorkingStacks) } println(part2WorkingStacks.joinToString("") { "${it.last()}" }) // TDGJQTZSL } fun String.toCrates(): List<Char?> { return ("$this ").chunked(4) { // parse string of shape '[X] ' if (it[1].isLetter()) it[1] else null } } fun String.toInstruction(): Instruction { val words = split(" ") val count = words[1].toInt() val from = words[3].toInt() val to = words[5].toInt() return Instruction(count, from, to) } data class Instruction(val count: Int, val from: Int, val to: Int) { fun executeAsPart1(stacks: List<ArrayDeque<Char>>) { val fromStack = stacks[from - 1] val toStack = stacks[to - 1] repeat(count) { val inCraneClaw = fromStack.removeLast() toStack.addLast(inCraneClaw) } } fun executeAsPart2(stacks: List<ArrayDeque<Char>>) { val fromStack = stacks[from - 1] val toStack = stacks[to - 1] val inCraneClaw = fromStack.takeLast(count) repeat(count) { fromStack.removeLast() } for (crate in inCraneClaw) { toStack.addLast(crate) } } }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
2,107
advent-of-code-2022
Apache License 2.0
src/Day05.kt
phoenixli
574,035,552
false
{"Kotlin": 29419}
fun main() { fun part1(input: List<String>): String { val crateStacks = populateCrates() input.subList(10, input.size).forEach{ performMove(it, crateStacks) } var result = "" for (stack in crateStacks) { result += stack.removeLast() } return result } fun part2(input: List<String>): String { val crateStacks = populateCrates() input.subList(10, input.size).forEach{ performUpdatedMove(it, crateStacks) } var result = "" for (stack in crateStacks) { result += stack.removeLast() } return result } val input = readInput("Day05") println(part1(input)) println(part2(input)) } fun printCrates(crateStacks: List<ArrayDeque<Char>>) { crateStacks.forEach { println(it) } } fun populateCrates(): List<ArrayDeque<Char>> { val crates = mutableListOf<ArrayDeque<Char>>() crates.add(ArrayDeque(listOf('D', 'B', 'J', 'V'))) crates.add(ArrayDeque(listOf('P', 'V', 'B', 'W', 'R', 'D', 'F'))) crates.add(ArrayDeque(listOf('R', 'G', 'F', 'L', 'D', 'C', 'W', 'Q'))) crates.add(ArrayDeque(listOf('W', 'J', 'P', 'M', 'L', 'N', 'D', 'B'))) crates.add(ArrayDeque(listOf('H', 'N', 'B', 'P', 'C', 'S', 'Q'))) crates.add(ArrayDeque(listOf('R', 'D', 'B', 'S', 'N', 'G'))) crates.add(ArrayDeque(listOf('Z', 'B', 'P', 'M', 'Q', 'F', 'S', 'H'))) crates.add(ArrayDeque(listOf('W', 'L', 'F'))) crates.add(ArrayDeque(listOf('S', 'V', 'F', 'M', 'R'))) return crates } fun performMove(input: String, crates: List<ArrayDeque<Char>>) { val inputs = input.split(" ") val numCrates = inputs[1].toInt() val src = inputs[3].toInt() - 1 val dst = inputs[5].toInt() -1 for (i in 1..numCrates) { val crate = crates[src].removeLast() crates[dst].addLast(crate) } } fun performUpdatedMove(input: String, crates: List<ArrayDeque<Char>>) { val inputs = input.split(" ") val numCrates = inputs[1].toInt() val src = inputs[3].toInt() - 1 val dst = inputs[5].toInt() -1 val tmpCrates = ArrayDeque<Char>() for (i in 1..numCrates) { tmpCrates.addLast(crates[src].removeLast()) } for (i in 1..numCrates) { crates[dst].addLast(tmpCrates.removeLast()) } }
0
Kotlin
0
0
5f993c7b3c3f518d4ea926a792767a1381349d75
2,355
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/io/github/thanosfisherman/bayes/BayesClassifier.kt
ThanosFisherman
154,952,306
false
null
package io.github.thanosfisherman.bayes import kotlin.math.ln /** * Simple Naive Bayes Classifier in Kotlin * * @author <NAME> * * Helpful References: * * * https://monkeylearn.com/blog/practical-explanation-naive-bayes-classifier/ * * https://stats.stackexchange.com/questions/274251/why-do-we-need-laplace-smoothing-in-naive-bayes-while-logarithm-may-resolve-the * * https://stats.stackexchange.com/questions/105602/example-of-how-the-log-sum-exp-trick-works-in-naive-bayes * * https://github.com/thomasnield/bayes_email_spam * * https://github.com/Tradeshift/blayze */ class BayesClassifier<C : Any> { private var inputs: MutableList<Input<C>> = mutableListOf() private val logPriori: Map<C, Double> by lazy { inputs.map { it.category }.groupingBy { it }.eachCount().mapValues { entry -> ln(entry.value / inputs.size.toDouble()) } } private val allWordsCount by lazy { inputs.asSequence().flatMap { it.features.asSequence() }.distinct().count() } private val featureCounter by lazy { val feat = mutableMapOf<C, Int>() for (a in inputs) feat.merge(a.category, a.features.size, Int::plus) feat } fun train(input: Input<C>) { inputs.add(input) } fun train(inputs: MutableList<Input<C>>) { this.inputs = inputs } fun predict(input: String): Map<C, Double> { val mapPredict = mutableMapOf<String, Map<C, Int>>() for (w in input.splitWords().distinct().toList()) { val categoriesCounter = mutableMapOf<C, Int>() for (i in inputs) { if (w in i.features) categoriesCounter.merge(i.category, 1, Int::plus) else categoriesCounter.merge(i.category, 0, Int::plus) mapPredict[w] = categoriesCounter } } val resultsMap = mutableMapOf<C, Double>() for (key in mapPredict) { for ((cat, count) in key.value) { val math = ln((count.toDouble() + 1.0) / (featureCounter.getOrDefault(cat, 0).toDouble() + allWordsCount.toDouble())) resultsMap.merge(cat, math, Double::plus) } } val maps = mutableListOf<Map<C, Double>>() maps.add(logPriori) maps.add(resultsMap) return normalize(sumMaps(maps)) } private fun sumMaps(maps: List<Map<C, Double>>): Map<C, Double> { val sum = mutableMapOf<C, Double>() for (map in maps) { for ((key, value) in map) { val current = sum.getOrDefault(key, 0.0) sum[key] = current + value } } return sum } private fun normalize(suggestions: Map<C, Double>): Map<C, Double> { val max: Double = suggestions.maxBy { it.value }?.value ?: 0.0 val vals = suggestions.mapValues { Math.exp(it.value - max) } val norm = vals.values.sum() return vals.mapValues { it.value / norm } } } data class Input<C>(val text: String, val category: C) { val features = text.splitWords().distinct().toList() } fun String.splitWords(): Sequence<String> { val stopWords = javaClass.getResource("/english-stop-words.txt") ?.readText()?.split("\n")?.toSet() ?: setOf() return split(Regex("\\s")).asSequence() .map { it.replace(Regex("[^A-Za-z]"), "").toLowerCase() } .filter { it !in stopWords } .filter { it.isNotEmpty() } }
0
Kotlin
2
3
95a73070cc6a647b297034ad1f2500c0cbec02d9
3,497
kaive-bayes
Apache License 2.0
src/main/kotlin/day4.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.Input import shared.toInts import kotlin.math.pow fun main() { val input = Input.day(4) println(day4A(input)) println(day4B(input)) } fun day4A(input: Input): Int { return input.lines.sumOf { card -> val (winning, yours) = card.split(':')[1].split('|').map(String::toInts) val match = winning.intersect(yours.toSet()).size val points = if(match == 0) 0 else 2.toDouble().pow(match - 1) points.toInt() } } fun day4B(input: Input): Int { val cards = MutableList(input.lines.size) { 1 } input.lines.forEachIndexed { index, card -> val (winning, yours) = card.split(':')[1].split('|').map(String::toInts) val match = winning.intersect(yours.toSet()).size repeat(match) { cards[index + it + 1] += cards[index] } } return cards.sum() }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
859
AdventOfCode2023
MIT License
src/day06/Day06.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day06 import readLines fun main() { fun find_marker(input: String, distinctCharCount: Int): Int { var charSet = HashSet<Char>() var count = 0 var left = 0 for ((index, char) in input.withIndex()) { if (charSet.contains(char)) { while (input[left] != char) { charSet.remove(input[left]) left += 1 count -= 1 } charSet.remove(input[left]) left += 1 count -= 1 } charSet.add(char) count += 1 if (count == distinctCharCount) { return index + 1 } } return -1 } fun find_marker_enhanced(input: String, distinctCharCount: Int): Int { val marker = input.toCharArray().toList() .windowed(4, 1, false) .first { window -> window.toSet().size == 4 } .joinToString(""); return input.indexOf(marker) + distinctCharCount } println(find_marker(readLines("day06/test")[0], 4)) println(find_marker(readLines("day06/input")[0], 4)) println(find_marker(readLines("day06/test")[0], 14)) println(find_marker(readLines("day06/input")[0], 14)) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
1,299
aoc2022
Apache License 2.0
src/main/kotlin/dev/kosmx/aoc23/garden/VirtualMemory.kt
KosmX
726,056,762
false
{"Kotlin": 32011}
package dev.kosmx.aoc23.garden import java.io.File import java.math.BigInteger import kotlin.math.abs typealias Offset = Pair<OpenEndRange<BigInteger>, BigInteger> val OpenEndRange<BigInteger>.size: BigInteger get() = endExclusive - start val Offset.destination: OpenEndRange<BigInteger> get() = (first.start + second) ..< (first.endExclusive + second) fun List<Offset>.binarySearch(i: BigInteger) = binarySearch { (range, _) -> if (i in range) { 0 } else { range.start.compareTo(i) } } operator fun List<OpenEndRange<BigInteger>>.contains(item: BigInteger): Boolean { val idx = binarySearch { range -> if (item in range) { 0 } else { range.start.compareTo(item) } } return this.getOrNull(idx)?.contains(item) ?: false } fun min(a: BigInteger, b: BigInteger): BigInteger = if (a < b) a else b class RangeMapping(ranges: List<Offset> = listOf()) { val rangesList: List<Offset> init { rangesList = ranges.sortedBy { it.first.start } } operator fun get(i: BigInteger): BigInteger { val r = this.rangesList.binarySearch(i) return if (r >= 0) { i + rangesList[r].second } else i } override fun toString(): String { return "RangeMapping(rangesList=$rangesList)" } // one step of simplify operator fun plus(rhs: RangeMapping): RangeMapping { val newRanges = mutableListOf<Offset>() val newRangesB = rhs.rangesList.toMutableList() for (range in rangesList) { val currentRange = range.destination var current = currentRange.start var targetRangeIdx = abs(newRangesB.binarySearch(current)) while (current < currentRange.endExclusive && targetRangeIdx < newRangesB.size) { val dest = newRangesB[targetRangeIdx] if (current in dest.first) { // two ranges intersect, cut both range // cut destination range if necessary if (current > dest.first.start) { newRangesB.add(targetRangeIdx, dest.first.start ..< current to dest.second) targetRangeIdx++ } val newEnd = min(currentRange.endExclusive, dest.first.endExclusive) newRanges += current-range.second ..< newEnd-range.second to range.second + dest.second current = newEnd if (newEnd < dest.first.endExclusive) { newRangesB[targetRangeIdx] = newEnd ..< dest.first.endExclusive to dest.second targetRangeIdx++ } else { newRangesB.removeAt(targetRangeIdx) } } else { val newEnd = min(currentRange.endExclusive, dest.first.start) newRanges += current-range.second ..< newEnd-range.second to range.second current = newEnd } } if (current < range.first.endExclusive) { newRanges += current-range.second ..< range.first.endExclusive to range.second } } newRanges.removeIf { it.first.isEmpty() } run { var i = 0 while (i < newRangesB.size) { val r = newRangesB[i] val pos = abs(newRanges.binarySearch(r.first.start)) if (r.first.isEmpty() || newRanges.size > pos && newRanges[pos].first.start < r.first.endExclusive) { // there is some intersection // new r range start after the other range if (r.first.isEmpty() || r.first.start >= newRanges[pos].first.start) { if (r.first.isEmpty() || r.first.endExclusive <= newRanges[pos].first.endExclusive) { newRangesB.removeAt(i) // just throw it away } else { newRangesB[i] = newRanges[pos].first.endExclusive ..< r.first.endExclusive to r.second // trim it } } else { // the current range starts before the other, we cut it always newRangesB[i] = r.first.start ..< newRanges[pos].first.start to r.second // this range is okay // add the following part, next iteration can handle it. newRangesB.add(i + 1, newRanges[pos].first.start ..< r.first.endExclusive to r.second) i++ } } else { i++ } } } newRanges += newRangesB // now, these shouldn't intersect // make it sorted newRanges.sortBy { it.first.start } // optimise this mess var i = 0 while (i < newRanges.size - 1) { val current = newRanges[i] val next by lazy { newRanges[i + 1] } when { current.second == BigInteger.ZERO || current.first.isEmpty() -> { newRanges.removeAt(i) } current.first.endExclusive == next.first.start && current.second == next.second -> { newRanges[i] = current.first.start ..< next.first.endExclusive to current.second newRanges.removeAt(i + 1) } else -> i++ } } return RangeMapping(newRanges) } } fun main() { val lines = File("mapping.txt").readLines().filter { it.isNotBlank() } val seeds = mutableListOf<BigInteger>() val conversionSequence = mutableListOf<RangeMapping>() // parse seeds seeds += lines[0].split(" ").drop(1).map { BigInteger(it) } val p = Regex("^(?<from>\\w+)-to-(?<to>\\w+) map:$") var i = 1 while (lines.size > i) { val rangeList = mutableListOf<Pair<OpenEndRange<BigInteger>, BigInteger>>() while (lines.size > i && !p.matches(lines[i])) { val l = lines[i].split(" ").map { BigInteger(it) } rangeList += (l[1] ..< (l[1] + l[2])) to l[0] - l[1] i++ } if (rangeList.isNotEmpty()) { conversionSequence += RangeMapping(rangeList) } i++ } println(conversionSequence) val min = seeds.map { conversionSequence[it] }.toList().min() println("The lowest number Id is $min") val range = conversionSequence.simplify() val seedRanges = lines[0].split(" ").asSequence().drop(1).map { BigInteger(it) }.windowed(2, 2).map { (start, len) -> start ..< start + len }.sortedBy { it.start }.toList() var minSeed = range[seedRanges[0].start] (range.rangesList.asSequence().map { it.first.start } + seedRanges.asSequence().map { it.start }).filter { it in seedRanges }.forEach { val new = conversionSequence[it] if (new < minSeed) { minSeed = new } } println("Part2: $minSeed") } // This is the key for Part2 // Something is still not okay, but I don't care right now fun List<RangeMapping>.simplify(): RangeMapping = fold(RangeMapping()) { acc, rangeMapping -> acc + rangeMapping } operator fun List<RangeMapping>.get(i: BigInteger, debug: Boolean = false): BigInteger { if (debug) print(i) return fold(i) {acc, rangeMapping -> rangeMapping[acc].also { if(debug) print(" -> $it") } }.also { if (debug) println() } }
0
Kotlin
0
0
ad01ab8e9b8782d15928a7475bbbc5f69b2416c2
7,581
advent-of-code23
MIT License
src/Day06.kt
rod41732
728,131,475
false
{"Kotlin": 26028}
/** * You can edit, run, and share this code. * play.kotlinlang.org */ fun main() { fun getNumbers(line: String): List<Int> { return Regex("\\d+").findAll(line).map { it.value.toInt() }.toList() } fun getWaysToBeat(time: Int, record: Long): Int { (1L..time.toLong()).forEach { holdDuration -> if (holdDuration * (time - holdDuration) > record) { return ((time - holdDuration) - holdDuration + 1).toInt() } } return 0 } fun part1(input: List<String>): Int { val times = getNumbers(input[0]) val record = getNumbers(input[1]) return times.zip(record).map { (time, record) -> getWaysToBeat(time, record.toLong()) }.product() } fun parseNumber2(line: String): Long { return Regex("\\d+").findAll(line).map { it.value }.joinToString("").toLong() } fun part2(input: List<String>): Int { val time = parseNumber2(input[0]) val record = parseNumber2(input[1]) return getWaysToBeat(time.toInt(), record) } val testInput = readInput("Day06_test") assertEqual(part1(testInput), 288) assertEqual(part2(testInput), 71503) val input = readInput("Day06") println("Part1: ${part1(input)}") println("Part2: ${part2(input)}") }
0
Kotlin
0
0
05a308a539c8a3f2683b11a3a0d97a7a78c4ffac
1,333
aoc-23
Apache License 2.0