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/dev/bogwalk/batch8/Problem85.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch8 import kotlin.math.abs import kotlin.math.sqrt /** * Problem 85: Counting Rectangles * * https://projecteuler.net/problem=85 * * Goal: Find the area of a grid (made up of 1x1 squares) that can contain a number of rectangles * closest to T. If multiple such areas exist, output the one with the largest area. * * Constraints: 1 <= T <= 2e6 * * For reference, a 3x2 grid contains 18 rectangles: {6 1x1 squares, 4 2x1 rectangles, 2 3x1 * rectangles, 3 2x1 rectangles, 2 2x2 squares, and the 3x2 rectangle itself} * * e.g.: T = 2 * 1x1 grid (A = 1) has 1 rectangle (delta = 1) * both 2x1 and 1x2 grids (A = 2) have 3 rectangles (delta = 1) * ans = 2 */ class CountingRectangles { /** * The count of contained rectangles is calculated based on the sequence of triangle numbers * (T_n) being equivalent to the contained count for every smaller nx1 grid, such that: * * A(x, y) -> T_x * T_y = x(x + 1)/2 * y(y + 1)/2 * = xy(x + 1)(y + 1)/4 * * Since the area A is linked to the resulting count, and assuming that x is the smaller * side of the grid, x cannot exceed sqrt(A) as one of the sides must be smaller than this * value to produce a valid A. * * For every x below this limit, y is iterated over until a resulting rectangles count * exceeds [target]. Every resulting count is checked to see if it has a smaller delta * than the stored best. */ fun findClosestContainingArea(target: Int): Int { var closest = Int.MAX_VALUE to 0 // delta to area for (x in 1..sqrt(1.0 * target).toInt()) { var y = x var count = 0 while (count < target) { count = x * y * (x + 1) * (y + 1) / 4 val area = x * y val delta = abs(target - count) if (delta <= closest.first && closest.second <= area) { closest = delta to area } y++ } // if x^2 is already exceeding the target, any larger x will immediately do so too if (y - 1 == x) break } return closest.second } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,242
project-euler-kotlin
MIT License
kotlin/udemy_course/src/main/kotlin/random/RandomQuestions.kt
pradyotprksh
385,586,594
false
{"Kotlin": 1973871, "Dart": 1066884, "Python": 313491, "Swift": 147167, "C++": 113494, "CMake": 94132, "Go": 45704, "HTML": 21089, "Ruby": 12424, "Rust": 8550, "C": 7125, "Makefile": 1480, "Shell": 817, "JavaScript": 781, "CSS": 588, "Objective-C": 380, "Dockerfile": 32}
package random class RandomQuestions { fun solveRandomQuestions() { println("Solving random questions") println(youWillAllConform(listOf("F", "B", "B", "F", "B", "F", "F", "B", "B", "B", "F"))) println(theBestTimeToParty(listOf(6, 7, 10, 10, 8, 9, 6), listOf(7, 9, 11, 12, 10, 11, 8))) println( theBestTimeToPartyFast( listOf( Pair(6, 7), Pair(7, 9), Pair(10, 11), Pair(10, 12), Pair(8, 10), Pair(9, 11), Pair(6, 8) ) ) ) println( minimumWaiterRequired( listOf( Pair(8.0, 9.10), Pair(8.40, 12.0), Pair(8.50, 11.20), Pair(10.0, 11.30), Pair(16.0, 19.0), Pair(19.0, 20.0) ) ) ) } // https://www.youtube.com/watch?v=zDHhHPZm2rc private fun minimumWaiterRequired(intervals: List<Pair<Double, Double>>): Int { val times = mutableListOf<Pair<Double, String>>() for (i in intervals) { times.add(Pair(i.first, "ARRIVAL")) times.add(Pair(i.second, "DEPARTURE")) } times.sortBy { it.first } var cCount = 0 var waiterCount = 0 for (t in times) { if (t.second == "ARRIVAL") { ++cCount } else { --cCount } if (cCount > waiterCount) { waiterCount = cCount } } return waiterCount } private fun theBestTimeToPartyFast(intervals: List<Pair<Int, Int>>): Int { val times = mutableListOf<Pair<Int, String>>() for (i in intervals) { times.add(Pair(i.first, "ARRIVAL")) times.add(Pair(i.second, "DEPARTURE")) } times.sortBy { it.first } var cCount = 0 var maxCount = 0 var time = times.first().first for (t in times) { if (t.second == "ARRIVAL") { ++cCount } else { --cCount } if (cCount > maxCount) { maxCount = cCount time = t.first } } return time } private fun theBestTimeToParty(arr: List<Int>, dep: List<Int>): Int { var maxCovered = 0 var maxList = listOf<Pair<Int, Int>>() for (a in arr) { var tempMax = 0 val tempList = mutableListOf<Pair<Int, Int>>() for (i in arr.indices) { if (a in arr[i] until dep[i]) { ++tempMax tempList.add(Pair(arr[i], dep[i])) } } if (tempMax > maxCovered) { maxCovered = tempMax maxList = tempList } } println(maxList) return maxList.first().first } private fun youWillAllConform(caps: List<String>): Int { val tempCaps = caps + listOf("END") val forwardCaps = mutableListOf<Pair<Int, Int>>() val backwardCaps = mutableListOf<Pair<Int, Int>>() var firstIndex = 0 for (i in 1 until tempCaps.size) { if (tempCaps[i - 1] != tempCaps[i]) { if (tempCaps[i - 1] == "F") { forwardCaps.add(Pair(firstIndex, i - 1)) } else { backwardCaps.add(Pair(firstIndex, i - 1)) } firstIndex = i } } println("Forward: $forwardCaps Backward: $backwardCaps") return if (forwardCaps.size < backwardCaps.size) forwardCaps.size else backwardCaps.size } }
0
Kotlin
10
17
2520dc56fc407f97564ed9f7c086292803d5d92d
3,889
development_learning
MIT License
src/main/java/challenges/cracking_coding_interview/linked_list/sum_lists/SumListsB.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.linked_list.sum_lists import challenges.data_structure.LinkedListNode object SumListsB { private fun length(l: LinkedListNode?): Int { return if (l == null) { 0 } else { 1 + length(l.next) } } private fun addListsHelper(l1: LinkedListNode?, l2: LinkedListNode?): PartialSum { if (l1 == null && l2 == null) { return PartialSum() } val sum = addListsHelper(l1!!.next, l2!!.next) val value = sum.carry + l1.data + l2.data val fullResult = insertBefore(sum.sum, value % 10) sum.sum = fullResult sum.carry = value / 10 return sum } private fun addLists(_l1: LinkedListNode, _l2: LinkedListNode): LinkedListNode? { var l1: LinkedListNode? = _l1 var l2: LinkedListNode? = _l2 val len1 = length(l1) val len2 = length(l2) if (len1 < len2) { l1 = padList(l1, len2 - len1) } else { l2 = padList(l2, len1 - len2) } val sum = addListsHelper(l1, l2) return if (sum.carry == 0) { sum.sum } else { insertBefore(sum.sum, sum.carry) } } private fun padList(l: LinkedListNode?, padding: Int): LinkedListNode? { var head = l for (i in 0 until padding) { head = insertBefore(head, 0) } return head } private fun insertBefore(list: LinkedListNode?, data: Int): LinkedListNode { val node = LinkedListNode(data) if (list != null) { node.next = list } return node } private fun linkedListToInt(node: LinkedListNode?): Int { var node = node var value = 0 while (node != null) { value = value * 10 + node.data node = node.next } return value } @JvmStatic fun main(args: Array<String>) { val lA1 = LinkedListNode(3, null, null) val lA2 = LinkedListNode(1, null, lA1) val lB1 = LinkedListNode(5, null, null) val lB2 = LinkedListNode(9, null, lB1) val lB3 = LinkedListNode(1, null, lB2) val list3 = addLists(lA1, lB1) println(" " + lA1.printForward()) println("+ " + lB1.printForward()) println("= " + list3!!.printForward()) val l1 = linkedListToInt(lA1) val l2 = linkedListToInt(lB1) val l3 = linkedListToInt(list3) print("$l1 + $l2 = $l3\n") print(l1.toString() + " + " + l2 + " = " + (l1 + l2)) } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,611
CodingChallenges
Apache License 2.0
src/main/kotlin/lesson3/PermMissingElem.kt
iafsilva
633,017,063
false
null
package lesson3 /** * An array A consisting of N different integers is given. * * The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing. * * Your goal is to find that missing element. * * Write a function: * * fun solution(A: IntArray): Int * * that, given an array A, returns the value of the missing element. * * For example, given array A such that: * ``` * A[0] = 2 * A[1] = 3 * A[2] = 1 * A[3] = 5 * ``` * the function should return 4, as it is the missing element. * * Write an efficient algorithm for the following assumptions: * * - N is an integer within the range [0..100,000]; * - the elements of A are all distinct; * - each element of array A is an integer within the range [1..(N + 1)]. */ class PermMissingElem { fun solution(a: IntArray): Int { // First edge case: missing is the first nr if (a.isEmpty()) return 1 a.sort() for (i in a.indices) { // Index 0 must be 1, Index 1 must be 2, and so on. // Whenever that's not true, we found our missing nr if (a[i] != i + 1) return i + 1 } // Second edge case: missing is the last nr return a.size + 1 } }
0
Kotlin
0
0
5d86aefe70e9401d160c3d87c09a9bf98f6d7ab9
1,262
codility-lessons
Apache License 2.0
src/Day22.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
private enum class FaceDirection(val score: Int) { Up(3), Down(1), Left(2), Right(0) } private interface Instruction private data class Move( val steps: Int ) : Instruction private data class Turn( val direction: String ) : Instruction private fun path(input: String): List<Instruction> { val instructions = mutableListOf<Instruction>() var startIndex = 0 do { val turnIndex = input.indexOfAny("LR".toCharArray(), startIndex) if (turnIndex == -1) { instructions.add(Move(input.substring(startIndex).toInt())) break } else { instructions.add(Move(input.substring(startIndex, turnIndex).toInt())) instructions.add(Turn(input.substring(turnIndex, turnIndex + 1))) startIndex = turnIndex + 1 } } while (true) return instructions } private fun parseInput(input: List<String>): Pair<MutableList<String>, List<Instruction>> { val mapWidth = input.maxOf { it.length } val map = mutableListOf<String>() var i = 0 while (input[i].isNotEmpty()) { map.add(input[i].padEnd(mapWidth, ' ')) i++ } val path = path(input[i + 1]) return Pair(map, path) } private fun turn(direction: FaceDirection, instruction: Turn): FaceDirection { return when (direction) { FaceDirection.Right -> if (instruction.direction == "L") FaceDirection.Up else FaceDirection.Down FaceDirection.Down -> if (instruction.direction == "L") FaceDirection.Right else FaceDirection.Left FaceDirection.Left -> if (instruction.direction == "L") FaceDirection.Down else FaceDirection.Up FaceDirection.Up -> if (instruction.direction == "L") FaceDirection.Left else FaceDirection.Right } } private fun moveOffset(direction: FaceDirection): Pair<Int, Int> { return when (direction) { FaceDirection.Right -> Pair(0, 1) FaceDirection.Down -> Pair(1, 0) FaceDirection.Left -> Pair(0, -1) FaceDirection.Up -> Pair(-1, 0) } } private fun part1(input: List<String>): Int { val (map, path) = parseInput(input) val mapHeight = map.size val mapWidth = map[0].length var coordinate = Pair(0, map[0].indexOfFirst { it != ' ' }) var direction = FaceDirection.Right for (instruction in path) { if (instruction is Turn) { direction = turn(direction, instruction) } else if (instruction is Move) { val offset = moveOffset(direction) for (step in 1..instruction.steps) { var nextCoordinate = Pair( (coordinate.first + offset.first + mapHeight) % mapHeight, (coordinate.second + offset.second + mapWidth) % mapWidth ) var nextTile = map[nextCoordinate.first][nextCoordinate.second] while (nextTile == ' ') { nextCoordinate = Pair( (nextCoordinate.first + offset.first + mapHeight) % mapHeight, (nextCoordinate.second + offset.second + mapWidth) % mapWidth ) nextTile = map[nextCoordinate.first][nextCoordinate.second] } if (nextTile == '.') { coordinate = nextCoordinate } else if (nextTile == '#') { break } else { throw IllegalArgumentException("Unknown tile $nextTile") } } } } return 1000 * (coordinate.first + 1) + 4 * (coordinate.second + 1) + direction.score } private fun part2(input: List<String>, faceWidth: Int): Int { val (map, path) = parseInput(input) var coordinate = Pair(0, map[0].indexOfFirst { it != ' ' }) var direction = FaceDirection.Right val warps = mutableMapOf<Triple<FaceDirection, Int, Int>, Triple<FaceDirection, Int, Int>>() for (i in 0 until faceWidth) { warps[Triple(FaceDirection.Left, i, faceWidth)] = Triple(FaceDirection.Right, 3 * faceWidth - i - 1, 0) warps[Triple(FaceDirection.Left, faceWidth + i, faceWidth)] = Triple(FaceDirection.Down, faceWidth * 2, i) warps[Triple(FaceDirection.Up, faceWidth * 2, i)] = Triple(FaceDirection.Right, faceWidth + i, faceWidth) warps[Triple(FaceDirection.Left, 3 * faceWidth - i - 1, 0)] = Triple(FaceDirection.Right, i, faceWidth) warps[Triple(FaceDirection.Left, 3 * faceWidth + i, 0)] = Triple(FaceDirection.Down, 0, faceWidth + i) warps[Triple(FaceDirection.Down, 4 * faceWidth - 1, i)] = Triple(FaceDirection.Down, 0, faceWidth * 2 + i) warps[Triple(FaceDirection.Right, 3 * faceWidth + i, faceWidth - 1)] = Triple(FaceDirection.Up, 3 * faceWidth - 1, faceWidth + i) warps[Triple(FaceDirection.Down, 3 * faceWidth - 1, faceWidth + i)] = Triple(FaceDirection.Left, 3 * faceWidth + i, faceWidth - 1) warps[Triple(FaceDirection.Right, 2 * faceWidth + i, 2 * faceWidth - 1)] = Triple(FaceDirection.Left, faceWidth - i - 1, 3 * faceWidth - 1) warps[Triple(FaceDirection.Right, faceWidth + i, 2 * faceWidth - 1)] = Triple(FaceDirection.Up, faceWidth - 1, 2 * faceWidth + i) warps[Triple(FaceDirection.Down, faceWidth - 1, 2 * faceWidth + i)] = Triple(FaceDirection.Left, faceWidth + i, 2 * faceWidth - 1) warps[Triple(FaceDirection.Right, faceWidth - i - 1, 3 * faceWidth - 1)] = Triple(FaceDirection.Left, 2 * faceWidth + i, 2 * faceWidth - 1) warps[Triple(FaceDirection.Up, 0, faceWidth * 2 + i)] = Triple(FaceDirection.Up, 4 * faceWidth - 1, i) warps[Triple(FaceDirection.Up, 0, faceWidth + i)] = Triple(FaceDirection.Right, 3 * faceWidth + i, 0) } for (instruction in path) { if (instruction is Turn) { direction = turn(direction, instruction) } else if (instruction is Move) { for (step in 1..instruction.steps) { if (warps.containsKey(Triple(direction, coordinate.first, coordinate.second))) { val wrap = warps[Triple(direction, coordinate.first, coordinate.second)]!! val nextCoordinate = Pair(wrap.second, wrap.third) val nextTile = map[nextCoordinate.first][nextCoordinate.second] if (nextTile == '.') { coordinate = nextCoordinate direction = wrap.first } else if (nextTile == '#') { break } else { throw IllegalArgumentException("Unknown tile $nextTile") } } else { val offset = moveOffset(direction) val nextCoordinate = Pair( coordinate.first + offset.first, coordinate.second + offset.second ) val nextTile = map[nextCoordinate.first][nextCoordinate.second] if (nextTile == '.') { coordinate = nextCoordinate } else if (nextTile == '#') { break } else { throw IllegalArgumentException("Unknown tile $nextTile") } } } } } return 1000 * (coordinate.first + 1) + 4 * (coordinate.second + 1) + direction.score } fun main() { val input = readInput("Day22") val faceWidth = 50 // val input = readInput("Test") // val faceWidth = 4 println("Part 1: " + part1(input)) println("Part 2: " + part2(input, faceWidth)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
7,648
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day9.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List object Day9 { fun part1(input: List<String>): String { return parse(input) .sumOf { extrapolate(it) { deltas, ret -> deltas.last() + ret } }.toString() } fun part2(input: List<String>): String { return parse(input) .sumOf { extrapolate(it) { deltas, ret -> deltas.first() - ret } }.toString() } private fun parse(input: List<String>): List<List<Long>> { return input.map { it.split("\\s+".toRegex()).map { it.toLong() } } } private fun extrapolate(input: List<Long>, extrapolator: (List<Long>, Long) -> Long): Long { val deltas = input.zipWithNext().map { (a, b) -> b - a } if (deltas.all { it == 0L }) { return extrapolator(input, 0) } return extrapolator(input, extrapolate(deltas, extrapolator)) } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
883
kotlin-kringle
Apache License 2.0
src/Day01.kt
jandryml
573,188,876
false
{"Kotlin": 6130}
private fun getSumOfHighestElements(input: List<String>, elementCount: Int) = input.joinToString(";") .split(";;") .map { it.split(";").sumOf { calories -> calories.toInt() } } .sortedDescending() .take(elementCount) .sum() private fun part1(input: List<String>) = getSumOfHighestElements(input, 1) private fun part2(input: List<String>) = getSumOfHighestElements(input, 3) fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
90c5c24334c1f26ee1ae5795b63953b22c7298e2
774
Aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ParallelCourses.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 /** * Parallel Courses * @see <a href="https://leetcode.com/problems/parallel-courses/">Source</a> */ fun interface ParallelCourses { fun minimumSemesters(n: Int, relations: Array<IntArray>): Int } /** * Approach 1: Breadth-First Search (Kahn's Algorithm) */ class ParallelCoursesBFS : ParallelCourses { override fun minimumSemesters(n: Int, relations: Array<IntArray>): Int { val inCount = IntArray(n + 1) // or indegree val graph: MutableList<MutableList<Int>> = ArrayList(n + 1) for (i in 0 until n + 1) { graph.add(ArrayList()) } for (relation in relations) { graph[relation[0]].add(relation[1]) inCount[relation[1]]++ } var step = 0 var studiedCount = 0 var bfsQueue: MutableList<Int> = ArrayList() for (node in 1 until n + 1) { if (inCount[node] == 0) { bfsQueue.add(node) } } // start learning with BFS while (bfsQueue.isNotEmpty()) { // start new semester step++ val nextQueue: MutableList<Int> = ArrayList() for (node in bfsQueue) { studiedCount++ for (endNode in graph[node]) { inCount[endNode]-- // if all prerequisite courses learned if (inCount[endNode] == 0) { nextQueue.add(endNode) } } } bfsQueue = nextQueue } // check if learn all courses return if (studiedCount == n) step else -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,294
kotlab
Apache License 2.0
src/nativeMain/kotlin/Day5.kt
rubengees
576,436,006
false
{"Kotlin": 67428}
class Day5 : Day { private data class Instruction(val times: Int, val from: Int, val to: Int) private fun parseInput(input: String): Pair<MutableList<ArrayDeque<Char>>, List<Instruction>> { val stackLines = input.lines().takeWhile { !it.startsWith(" 1 ") } val stackLineChars = stackLines.map { line -> line.toCharArray().toList() .chunked(4) .map { chunk -> chunk.find { char -> char.isLetter() } } } val emptyStacks = stackLineChars.last().map { ArrayDeque<Char>() }.toMutableList() val stacks = stackLineChars.reversed().fold(emptyStacks) { acc, chars: List<Char?> -> chars.forEachIndexed { index, char -> if (char != null) { acc[index].add(char) } } acc } val instructionLines = input.lines().drop(stackLines.size + 2) val instructions = instructionLines.map { line -> val match = Regex("move (\\d+) from (\\d+) to (\\d+)").matchEntire(line) ?: error("Invalid instruction") Instruction(match.groupValues[1].toInt(), match.groupValues[2].toInt(), match.groupValues[3].toInt()) } return stacks to instructions } override suspend fun part1(input: String): String { val (stacks, instructions) = parseInput(input) for (instruction in instructions) { repeat(instruction.times) { stacks[instruction.to - 1].add(stacks[instruction.from - 1].removeLast()) } } return stacks.map { it.last() }.joinToString("") } override suspend fun part2(input: String): String { val (stacks, instructions) = parseInput(input) for (instruction in instructions) { val movingElements = (0 until instruction.times).fold(emptyList<Char>()) { acc, _ -> acc + stacks[instruction.from - 1].removeLast() } stacks[instruction.to - 1].addAll(movingElements.reversed()) } return stacks.map { it.last() }.joinToString("") } }
0
Kotlin
0
0
21f03a1c70d4273739d001dd5434f68e2cc2e6e6
2,128
advent-of-code-2022
MIT License
2023/src/main/kotlin/de/skyrising/aoc2023/day12/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2023.day12 import de.skyrising.aoc.* import it.unimi.dsi.fastutil.ints.IntArrayList import it.unimi.dsi.fastutil.ints.IntList import it.unimi.dsi.fastutil.objects.Object2LongMap import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import java.util.* fun IntList.dec(index: Int) { set(index, getInt(index) - 1) } data class Springs(val op: BitSet, val dmg: BitSet, val length: Int) { constructor(value: String) : this(BitSet(value.length), BitSet(value.length), value.length) { for (i in value.indices) { when (value[i]) { '#' -> op.set(i) '.' -> dmg.set(i) } } } enum class Type { OPERATIONAL, DAMAGED, UNKNOWN } inline fun isOperational(index: Int) = op.get(index) inline fun isDamaged(index: Int) = dmg.get(index) inline operator fun get(index: Int) = when { isOperational(index) -> Type.OPERATIONAL isDamaged(index) -> Type.DAMAGED else -> Type.UNKNOWN } inline fun isEmpty() = length == 0 fun subSequence(offset: Int) = Springs(op.get(offset, length), dmg.get(offset, length), length - offset) fun withFirst(type: Type): Springs { val op = op.clone() as BitSet val dmg = dmg.clone() as BitSet op.set(0, type == Type.OPERATIONAL) dmg.set(0, type == Type.DAMAGED) return Springs(op, dmg, length) } fun count(type: Type) = when (type) { Type.OPERATIONAL -> op.cardinality() Type.DAMAGED -> dmg.cardinality() Type.UNKNOWN -> length - op.cardinality() - dmg.cardinality() } } val test = TestInput(""" ???.### 1,1,3 .??..??...?##. 1,1,3 ?#?#?#?#?#?#?#? 1,3,1,6 ????.#...#... 4,1,1 ????.######..#####. 1,6,5 ?###???????? 3,2,1 """) fun parse(input: PuzzleInput) = input.lines.map { val (springs, counts) = it.split(' ') springs to counts.ints() } fun adjustment(type: Springs.Type, a: Springs.Type, b: Springs.Type) = (type == a).toInt() - (type == b).toInt() data class State( val springs: Springs, val counts: IntList, val operationalCount: Int = springs.count(Springs.Type.OPERATIONAL), val damagedCount: Int = springs.count(Springs.Type.DAMAGED) ) { private var countsHashCode: Int? = null private var countsHashCodeComputed = false fun withFirst(type: Springs.Type) = State( springs.withFirst(type), counts, operationalCount + adjustment(Springs.Type.OPERATIONAL, type, springs[0]), damagedCount + adjustment(Springs.Type.DAMAGED, type, springs[0]) ).also { it.countsHashCode = countsHashCode; it.countsHashCodeComputed = true } fun next() = State( springs.subSequence(1), counts, operationalCount - springs.isOperational(0).toInt(), damagedCount - springs.isDamaged(0).toInt() ).also { it.countsHashCode = countsHashCode; it.countsHashCodeComputed = true } fun computePossibilities(cache: Object2LongMap<State> = Object2LongOpenHashMap()): Long { if (counts.isEmpty()) return (operationalCount == 0).toLong() if (springs.isEmpty()) return 0 val cached = cache.getOrDefault(this as Any, -1L) if (cached >= 0) return cached if (springs.isOperational(0)) { val runLength = counts.getInt(0) if (springs.length - damagedCount < runLength) return 0 var opCount = 1 for (i in 1 until runLength) { if (springs.isDamaged(i)) return 0 if (springs.isOperational(i)) opCount++ } if (runLength == springs.length && damagedCount == 0) return (counts.size == 1).toLong() val next = springs[runLength] if (next == Springs.Type.OPERATIONAL) return 0 return memoize(cache, State(springs.subSequence(runLength + 1), counts.subList(1, counts.size), operationalCount - opCount, damagedCount - (next == Springs.Type.DAMAGED).toInt())) } if (springs.isDamaged(0)) { return memoize(cache, next()) } return memoize(cache, withFirst(Springs.Type.OPERATIONAL).computePossibilities(cache) + next().computePossibilities(cache)) } override fun hashCode(): Int { var hash = springs.hashCode() hash = hash * 31 + operationalCount hash = hash * 31 + damagedCount hash = hash * 31 + counts.size return hash } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as State if (operationalCount != other.operationalCount) return false if (damagedCount != other.damagedCount) return false if (springs != other.springs) return false if (counts.size != other.counts.size) return false if (countsHashCodeComputed && other.countsHashCodeComputed && countsHashCode != other.countsHashCode) return false for (i in 0 until counts.size) { if (counts.getInt(i) != other.counts.getInt(i)) return false } return true } private inline fun memoize(cache: Object2LongMap<State>, value: Long) = value.also { cache[this] = it } private inline fun memoize(cache: Object2LongMap<State>, state: State) = state.computePossibilities(cache).also { cache[this] = it } } @PuzzleName("Hot Springs") fun PuzzleInput.part1() = parse(this).sumOf { (springs, counts) -> State(Springs(springs), counts).computePossibilities() } fun PuzzleInput.part2() = parse(this).sumOf { (springs, counts) -> val repeatedCounts = IntArrayList(counts.size * 5) repeat(5) { repeatedCounts.addAll(counts) } State(Springs(("?$springs").repeat(5).substring(1)), repeatedCounts).computePossibilities() }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
5,854
aoc
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/IntersectionThreeSortedArrays.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 /** * Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, * return a sorted array of only the integers that appeared in all three arrays. * @see <a href="https://leetcode.com/problems/intersection-of-three-sorted-arrays/">Source</a> */ fun interface IntersectionThreeSortedArrays { operator fun invoke(arr1: IntArray, arr2: IntArray, arr3: IntArray): List<Int> } /** * Time Complexity: O(n) * Space Complexity: O(n) */ class IntersectionThreeSortedBruteForce : IntersectionThreeSortedArrays { override operator fun invoke(arr1: IntArray, arr2: IntArray, arr3: IntArray): List<Int> { val ans: MutableList<Int> = ArrayList() val counter: MutableMap<Int, Int> = HashMap() // iterate through arr1, arr2, and arr3 to count the frequencies for (e in arr1) { counter[e] = counter.getOrDefault(e, 0) + 1 } for (e in arr2) { counter[e] = counter.getOrDefault(e, 0) + 1 } for (e in arr3) { counter[e] = counter.getOrDefault(e, 0) + 1 } for (item in counter.keys) { if (counter[item] == 3) { ans.add(item) } } return ans } } /** * Time Complexity: O(n) * Space Complexity: O(1) */ class IntersectionThreeSortedThreePointers : IntersectionThreeSortedArrays { override operator fun invoke(arr1: IntArray, arr2: IntArray, arr3: IntArray): List<Int> { val ans: MutableList<Int> = ArrayList() // prepare three pointers to iterate through three arrays // p1, p2, and p3 point to the beginning of arr1, arr2, and arr3 accordingly // prepare three pointers to iterate through three arrays // p1, p2, and p3 point to the beginning of arr1, arr2, and arr3 accordingly var p1 = 0 var p2 = 0 var p3 = 0 while (p1 < arr1.size && p2 < arr2.size && p3 < arr3.size) { if (arr1[p1] == arr2[p2] && arr2[p2] == arr3[p3]) { ans.add(arr1[p1]) p1++ p2++ p3++ } else { if (arr1[p1] < arr2[p2]) { p1++ } else if (arr2[p2] < arr3[p3]) { p2++ } else { p3++ } } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,033
kotlab
Apache License 2.0
src/main/kotlin/aoc22/Day09.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc22 import aoc22.Day09Solution.part1Day09 import aoc22.Day09Solution.part2Day09 import common.Space2D.Direction import common.Space2D.Direction.* import common.Space2D.Point import common.Year22 import common.Monitoring import kotlin.math.sign object Day09: Year22 { fun List<String>.part1(): Int = part1Day09() fun List<String>.part2(): Int = part2Day09() } object Day09Solution { fun List<String>.part1Day09(): Int = toDirections().toHistory(knots = 2).tailHistory.size fun List<String>.part2Day09(): Int = toDirections().toHistory(knots = 10).tailHistory.size data class State( val head: Point, val rope: List<Point>, val tailHistory: Set<Point> ) fun List<Direction>.toHistory(knots: Int, monitor: Monitoring.PointMonitor? = null): State { val initialState = State(Point(0, 0), listOf(Point(0, 0)), emptySet()) return fold(initialState) { acc, direction -> val movedHead = acc.head.move(direction) fun List<Point>.addTail(): List<Point> = if (this.size < knots - 1) this + initialState.rope else this val rope = acc.rope.addTail().withMovements(movedHead).also { monitor?.invoke(acc.tailHistory.toSet()) } State( head = movedHead, rope = rope, tailHistory = acc.tailHistory + rope.last() ) } } private fun List<Point>.withMovements(movedHead: Point): List<Point> { val movedPoints = mutableListOf<Point>() return mapIndexed { index, point -> movedPoints.getOrElse(index - 1) { movedHead } .let { prev -> val movedPoint = if (point !in listOf(prev) + prev.adjacentWithDiagonal()) pointNearest(point, prev) else point movedPoint.also { movedPoints.add(it) } } } } private fun pointNearest(point: Point, other: Point) = Point( x = point.x + (other.x - point.x).sign, y = point.y + (other.y - point.y).sign ) private fun String.toDirection(): Direction = when (this) { "U" -> North "R" -> East "D" -> South "L" -> West else -> error("don't know") } fun List<String>.toDirections(): List<Direction> = map { it.split(" ") .let { (dir, times) -> dir.toDirection() to (0 until times.toInt()) } .let { (dir, times) -> times.map { dir } } } .flatten() }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
2,682
aoc
Apache License 2.0
src/algorithmsinanutshell/spatialtree/NearestNeighbourQueries.kt
realpacific
234,499,820
false
null
package algorithmsinanutshell.spatialtree import algorithmdesignmanualbook.print import kotlin.math.pow /** * Given a target T and a set of points S, find the nearest neighbour of T in S. * * https://www.youtube.com/watch?v=Glp7THUpGow * * https://www.youtube.com/watch?v=XG4zpiJAkD4 * * https://www.cs.cmu.edu/~ckingsf/bioinfo-lectures/kdtrees.pdf */ class NearestNeighbourQueries(val array: Array<Array<Int>>) { private val tree: MultiDimNode = KDTree(array).tree private fun findNearest(subTree: MultiDimNode?, target: Array<Int>, depth: Int): MultiDimNode? { if (subTree == null) return null val dimensionIndex = depth % target.size val nextBranch: MultiDimNode? val otherBranch: MultiDimNode? if (target[dimensionIndex] < subTree.value[dimensionIndex]) { nextBranch = subTree.left otherBranch = subTree.right } else { nextBranch = subTree.right otherBranch = subTree.left } var nodeFromNextBranch = findNearest(nextBranch, target, depth + 1) var best = closest(MultiDimNode(target), nodeFromNextBranch, subTree) val euclideanDistance = best!!.distanceFrom(target) val perpendicularDistance = (target[dimensionIndex] - subTree.value[dimensionIndex]).toDouble().pow(2) // Traverse into the unvisited section i.e otherBranch if the best distance found so far is bigger than // the perpendicular distance to the unvisited branch if (euclideanDistance >= perpendicularDistance) { nodeFromNextBranch = findNearest(otherBranch, target, depth + 1) best = closest(MultiDimNode(target), nodeFromNextBranch, subTree) return best } return best } fun execute(target: Array<Int>): MultiDimNode? { return findNearest(tree, target, 0) } private fun closest(target: MultiDimNode, vararg p1: MultiDimNode?): MultiDimNode? { return p1.toList() .filterNotNull() .minByOrNull { it.distanceFrom(target.value) } } } fun main() { run { val array = arrayOf( arrayOf(3, 6), arrayOf(17, 15), arrayOf(13, 15), arrayOf(6, 12), arrayOf(9, 1), arrayOf(2, 7), arrayOf(10, 19) ) NearestNeighbourQueries(array).execute(arrayOf(1, 2)).print() } run { val array = arrayOf(arrayOf(30, 40), arrayOf(5, 25), arrayOf(10, 12), arrayOf(70, 70), arrayOf(50, 30), arrayOf(35, 45)) NearestNeighbourQueries(array).execute(arrayOf(52, 52)).print() } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,631
algorithms
MIT License
src/day7/Day07.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day7 import readInput private fun handle(input: List<String>, handler: (value: Int) -> Unit) { val stack = ArrayDeque<Int>() stack.addFirst(0) for (line in input) { if (line.startsWith("$ cd ..")) { val temp = stack.removeFirst() handler(temp) val newItem = (stack.removeFirstOrNull() ?: 0) + temp stack.addFirst(newItem) } else if (line.startsWith("$ cd /")) { popStack(stack, handler) } else if (line.startsWith("$ cd")) { stack.addFirst(0) } else if (line.startsWith("$ ls").not() && line.startsWith("dir").not()) { val temp = stack.removeFirstOrNull() ?: continue val size = temp + line.split(" ")[0].toInt() stack.addFirst(size) } } popStack(stack, handler) } private fun popStack(stack: ArrayDeque<Int>, handler: (value: Int) -> Unit) { while (stack.size > 0) { val temp = stack.removeFirstOrNull() ?: break handler(temp) if (stack.size != 0) { val newItem = stack.removeFirst() + temp stack.addFirst(newItem) } } } private fun part1(input: List<String>): Int { var result = 0 handle(input) { if (it <= 100_000) result += it } return result } const val MAX_SIZE = 70_000_000 const val REQUIRED = 30_000_000 private fun part2(input: List<String>): Int { var total = 0 for (line in input) { if (line.startsWith("$").not() && line.startsWith("dir").not()) { total += line.split(" ")[0].toInt() } } val freeSpace = MAX_SIZE - total val requiredSpace = REQUIRED - freeSpace var min = Int.MAX_VALUE handle(input) { if (it in requiredSpace until min) min = it } return min } fun main() { val input = readInput("day7/input") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
1,925
aoc-2022
Apache License 2.0
src/main/kotlin/aoc2016/BalanceBots.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2016 import komu.adventofcode.utils.nonEmptyLines fun balanceBots1(input: String): Int = buildBalanceRules(input).first.find { it.low() == 17 && it.high() == 61 }?.id!! fun balanceBots2(input: String): Int { val bins = buildBalanceRules(input).second return bins[0].value * bins[1].value * bins[2].value } private fun buildBalanceRules(input: String): Pair<List<Bot>, List<Bin>> { val bots = mutableMapOf<BotId, Bot>() val bins = mutableMapOf<BinId, Bin>() fun bot(id: BotId) = bots.getOrPut(id) { Bot(id) } fun bin(id: BotId) = bins.getOrPut(id) { Bin(id) } fun target(target: BalanceTarget) = when (target) { is BalanceTarget.BotTarget -> bot(target.id) is BalanceTarget.BinTarget -> bin(target.id) } for (line in input.nonEmptyLines()) { when (val rule = BalanceRule.parse(line)) { is BalanceRule.Give -> { val giver = bot(rule.giverId) target(rule.low).addSource { giver.low() } target(rule.high).addSource { giver.high() } } is BalanceRule.Value -> { val bot = bot(rule.botId) bot.addSource { rule.value } } } } return Pair(bots.values.sortedBy { it.id }, bins.values.sortedBy { it.id }) } private sealed class BalanceRule { data class Value(val value: Int, val botId: BotId) : BalanceRule() data class Give(val giverId: BotId, val low: BalanceTarget, val high: BalanceTarget) : BalanceRule() companion object { private val giveRegex = Regex("""bot (\d+) gives low to (.+) and high to (.+)""") private val valueRegex = Regex("""value (\d+) goes to bot (\d+)""") fun parse(s: String): BalanceRule { giveRegex.matchEntire(s)?.destructured?.let { (giver, low, high) -> return Give(giver.toInt(), BalanceTarget.parse(low), BalanceTarget.parse(high)) } valueRegex.matchEntire(s)?.destructured?.let { (value, bot) -> return Value(value.toInt(), bot.toInt()) } error("invalid command '$s'") } } } private typealias Chip = Int private interface ChipTarget { fun addSource(source: ChipSource) } private typealias ChipSource = () -> Chip private class Bot(val id: BotId) : ChipTarget { private val sources = mutableListOf<ChipSource>() private val values: Pair<Int, Int> by lazy { check(sources.size == 2) val values = sources.map { it() } Pair(values.min(), values.max()) } override fun addSource(source: ChipSource) { sources += source } fun low() = values.first fun high() = values.second } private class Bin(val id: BinId) : ChipTarget { private var source: ChipSource? = null val value: Int by lazy { this.source!!() } override fun addSource(source: ChipSource) { this.source = source } } private typealias BotId = Int private typealias BinId = Int private sealed class BalanceTarget { data class BotTarget(val id: BotId) : BalanceTarget() data class BinTarget(val id: BinId) : BalanceTarget() companion object { fun parse(s: String): BalanceTarget = when { s.startsWith("bot ") -> BotTarget(s.removePrefix("bot ").toInt()) s.startsWith("output ") -> BinTarget(s.removePrefix("output ").toInt()) else -> error("invalid target '$s'") } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
3,516
advent-of-code
MIT License
src/main/kotlin/knn/KnnClassificator.kt
widi-nugroho
280,304,894
false
null
package knn class KnnClassificator(val k:Int) { fun getKNearestNeighbour(sorteddata:List<Pair<Double,DataClassificator>>):List<Pair<Double,DataClassificator>>{ var res= mutableListOf<Pair<Double,DataClassificator>>() for (i in 0..k-1){ res.add(sorteddata[i]) } return res } fun computeDistance(input:DataClassificator, data:List<DataClassificator>):List<Pair<Double,DataClassificator>>{ var res= mutableListOf<Pair<Double,DataClassificator>>() for (i in data){ var dist=Distance.euclidDistanceClassificator(i,input) res.add(Pair(dist,i)) } return res.sortedWith(compareBy({it.first})) } fun kNearestNeighbourGroupedByLabel(sorted:List<Pair<Double,DataClassificator>>):List<Pair<String,Int>>{ var group= mutableMapOf<String,Int>() for (i in sorted){ if (group[i.second.output]==null){ group[i.second.output]=1 }else{ group[i.second.output]=group[i.second.output]!!+1 } } var res= mutableListOf<Pair<String,Int>>() for ((k,v) in group){ res.add(Pair(k,v)) } return res.sortedWith(compareByDescending { it.second }) } fun classify(input:List<Double>,data:List<DataClassificator>):String{ var c=DataClassificator(input," ") var cd=computeDistance(c,data) var cd2=getKNearestNeighbour(cd) var md=kNearestNeighbourGroupedByLabel(cd) return md[0].first } } fun main(){ //var t=DataAccess.loadcsv("/home/widi/projects/kotlin-machine-learning/src/main/resources/iris.data") //var k1=KnnClassificator(100) //var t2=k1.getKNearestNeighbour(k1.computeDistance(t[0],t)) //println(k1.kNearestNeighbourGroupedByLabel(t2)) //var test= listOf<Double>(4.9,3.0,1.4,0.2) //println(k1.classify(test,t)) var c2=DataAccess.loadWineData("/home/widi/projects/kotlin-machine-learning/src/main/resources/wine.data") var k2=KnnClassificator(3) var test2= listOf<Double>(11.41,.74,2.5,21.0,88.0,2.48,2.01,.42,1.44,3.08,1.1,2.31,434.0) println(k2.classify(test2,c2)) var t3=k2.computeDistance(c2[0],c2) println(t3[0].first) }
0
Kotlin
0
0
139d768e4e02c76193443c06285d918b0fbbfc7f
2,252
kotlin-machine-learning
Apache License 2.0
src/Day06.kt
rk012
574,169,156
false
{"Kotlin": 9389}
fun main() { fun String.getSequences(size: Int) = runningFold("") { acc, c -> (acc + c).takeLast(size) }.drop(size) tailrec fun hasSameChars(c: Char?, s: String): Boolean = when { s.isEmpty() -> false c?.let { s.contains(it) } == true -> true else -> hasSameChars(s.first(), s.drop(1)) } fun part1(input: List<String>) = input[0].getSequences(4).indexOfFirst { !hasSameChars(null, it) } + 4 fun part2(input: List<String>) = input[0].getSequences(14).indexOfFirst { !hasSameChars(null, it) } + 14 // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bfb4c56c4d4c8153241fa6aa6ae0e829012e6679
831
advent-of-code-2022
Apache License 2.0
leetcode/kotlin/flood-fill.kt
PaiZuZe
629,690,446
false
null
data class Cell(val row: Int, val col: Int) class Solution { fun numIslands(grid: Array<CharArray>): Int { val visited = mutableSetOf<Cell>() var islands = 0 for (i in grid.indices) { for (j in grid[i].indices) { val cell = Cell(i, j) if (grid[i][j] == '1' && !visited.contains(cell)) { bfs(cell, grid, visited) islands++ } } } return islands } private fun bfs(start: Cell, grid: Array<CharArray>, visited: MutableSet<Cell>) { val frontier = ArrayDeque<Cell>(listOf(start)) while (frontier.isNotEmpty()) { val cell = frontier.removeFirst() visited.add(cell) val validNeighbors = getNeighbors(cell, grid.size, grid[0].size).filter { cell -> !visited.contains(cell) && grid[cell.row][cell.col] == '1' } frontier.addAll(validNeighbors) } } private fun getNeighbors(cell: Cell, maxRow: Int, maxCol: Int): List<Cell> { val neighbors = mutableListOf<Cell>() val row = cell.row val col = cell.col if (row > 0) { neighbors.add(Cell(row - 1, col)) } if (row < maxRow - 1) { neighbors.add(Cell(row + 1, col)) } if (col > 0) { neighbors.add(Cell(row, col - 1)) } if (col < maxCol - 1) { neighbors.add(Cell(row, col + 1)) } return neighbors.toList() } }
0
Kotlin
0
0
175a5cd88959a34bcb4703d8dfe4d895e37463f0
1,566
interprep
MIT License
src/main/aoc2023/Day10.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2023 import AMap import Direction import Pos class Day10(input: List<String>) { private val map = AMap.parse(input) private val start = map.toMap().filterValues { it == 'S' }.keys.single() // All points on the right/left hand side of the loop while walking in one direction around the loop private val toRight = mutableSetOf<Pos>() private val toLeft = mutableSetOf<Pos>() // All points that makes up the loop private val loop = mutableSetOf<Pos>() init { // Replace the 'S' with the correct shape map[start] = startShape() // Walk through the loop to discover all points in the loop and what's to the left/right of the loop val facing = exitDirections(start).first() var current = start to facing do { loop.add(current.first) val (l, r) = neighbours(current) toLeft.addAll(l) toRight.addAll(r) current = walk(current) } while (current.first != start) toLeft.removeIf { it in loop || it !in map.keys } toRight.removeIf { it in loop || it !in map.keys } } private fun startShape(): Char { // If it's possible to move in each direction from the start position val up = map[start.move(Direction.Up)] in listOf('|', '7', 'F') val down = map[start.move(Direction.Down)] in listOf('|', 'L', 'J') val left = map[start.move(Direction.Left)] in listOf('-', 'L', 'F') val right = map[start.move(Direction.Right)] in listOf('-', 'J', '7') return when { up && down -> '|' up && left -> 'J' up && right -> 'L' down && left -> '7' down && right -> 'F' left && right -> '-' else -> error("invalid start shape") } } /** * List the directions that it's possible to exit a room from depending on it's shape */ private fun exitDirections(pos: Pos): List<Direction> { return when (map[pos]) { '|' -> listOf(Direction.Up, Direction.Down) '-' -> listOf(Direction.Left, Direction.Right) 'L' -> listOf(Direction.Up, Direction.Right) 'J' -> listOf(Direction.Up, Direction.Left) '7' -> listOf(Direction.Down, Direction.Left) 'F' -> listOf(Direction.Down, Direction.Right) else -> listOf() } } fun solvePart1(): Int { return loop.size / 2 } private fun walk(from: Pair<Pos, Direction>): Pair<Pos, Direction> { val nextRoom = from.first.move(from.second) val nextFacing = exitDirections(nextRoom).single { it != from.second.opposite() } return nextRoom to nextFacing } /** * @current Current position and facing direction * @return a pair of sets. first is the neighbours to the left of the pipe while second is neighbours to the right */ private fun neighbours(current: Pair<Pos, Direction>): Pair<Set<Pos>, Set<Pos>> { val pos = current.first val neighbours = mapOf( Pair('-', Direction.Right) to Pair(setOf(pos.move(Direction.Up)), setOf(pos.move(Direction.Down))), Pair('-', Direction.Left) to Pair(setOf(pos.move(Direction.Down)), setOf(pos.move(Direction.Up))), Pair('|', Direction.Up) to Pair(setOf(pos.move(Direction.Left)), setOf(pos.move(Direction.Right))), Pair('|', Direction.Down) to Pair(setOf(pos.move(Direction.Right)), setOf(pos.move(Direction.Left))), Pair('L', Direction.Up) to Pair(setOf(pos.move(Direction.Left), pos.move(Direction.Down)), setOf()), Pair('L', Direction.Right) to Pair(setOf(), setOf(pos.move(Direction.Left), pos.move(Direction.Down))), Pair('J', Direction.Up) to Pair(setOf(), setOf(pos.move(Direction.Right), pos.move(Direction.Down))), Pair('J', Direction.Left) to Pair(setOf(pos.move(Direction.Right), pos.move(Direction.Down)), setOf()), Pair('7', Direction.Left) to Pair(setOf(), setOf(pos.move(Direction.Right), pos.move(Direction.Up))), Pair('7', Direction.Down) to Pair(setOf(pos.move(Direction.Right), pos.move(Direction.Up)), setOf()), Pair('F', Direction.Down) to Pair(setOf(), setOf(pos.move(Direction.Left), pos.move(Direction.Up))), Pair('F', Direction.Right) to Pair(setOf(pos.move(Direction.Left), pos.move(Direction.Up)), setOf()) ) return neighbours[map[pos] to current.second]!! } private fun Pos.onBorder(): Boolean { return x == 0 || y == 0 || x == map.xRange().last || y == map.yRange().last } // Do a BFS search to walk from each unknown point outward until a point in // either toLeft, or toRight is found. Then assign all visited points to that set private fun assignUnknown() { val unknown = (map.keys - loop - toLeft - toRight).toMutableSet() while (unknown.isNotEmpty()) { val toCheck = ArrayDeque<Pos>().apply { add(unknown.first()) } val connected = mutableSetOf(unknown.first()) while (toCheck.isNotEmpty()) { val current = toCheck.removeFirst() if (current in toLeft) { // all connected are left toLeft.addAll(connected) unknown.removeAll(connected) break } else if (current in toRight) { // all connected are right toRight.addAll(connected) unknown.removeAll(connected) break } current.allNeighbours() .filter { it !in connected } .filter { it in unknown || it in toLeft || it in toRight } .forEach { next -> connected.add(next) toCheck.add(next) } } } } fun solvePart2(): Int { assignUnknown() // The set of positions that touches the border is not enclosed by the loop return if (toLeft.any { it.onBorder()} ) toRight.size else toLeft.size } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
6,209
aoc
MIT License
advent-of-code-2023/src/main/kotlin/Day23.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
// Day 23: A Long Walk // https://adventofcode.com/2023/day/23 import java.io.File private const val FOREST = '#' private const val PATH = '.' data class Tile(val char: Char, val xy: Pair<Int, Int>) fun main() { val trails = File("src/main/resources/Day23.txt").readLines().mapIndexed { x, chars -> chars.toList().mapIndexed { y, char -> if (char != FOREST) Tile(char, x to y) else null } }.flatten().filterNotNull() val startTile = trails.find { it.char == PATH} ?: trails.first() val endTile = trails.findLast { it.char == PATH } ?: trails.last() fun getNeighborTiles(tile: Tile, steps: List<Tile>): List<Tile> { val (x, y) = tile.xy val neighbour: Tile? when (tile.char) { '^' -> { neighbour = trails.find { it.xy == x - 1 to y } return if (neighbour != null && neighbour !in steps) { listOf(neighbour) } else { emptyList() } } 'v' -> { neighbour = trails.find { it.xy == x + 1 to y } return if (neighbour != null && neighbour !in steps) { listOf(neighbour) } else { emptyList() } } '<' -> { neighbour = trails.find { it.xy == x to y - 1 } return if (neighbour != null && neighbour !in steps) { listOf(neighbour) } else { emptyList() } } '>' -> { neighbour = trails.find { it.xy == x to y + 1 } return if (neighbour != null && neighbour !in steps) { listOf(neighbour) } else { emptyList() } } else -> return buildList { var neighbor = trails.find { it.xy == x - 1 to y } if (neighbor != null && neighbor !in steps) add(neighbor) neighbor = trails.find { it.xy == x + 1 to y } if (neighbor != null && neighbor !in steps) add(neighbor) neighbor = trails.find { it.xy == x to y - 1 } if (neighbor != null && neighbor !in steps) add(neighbor) neighbor = trails.find { it.xy == x to y + 1 } if (neighbor != null && neighbor !in steps) add(neighbor) } } } fun takeAHike(steps: List<Tile>): List<List<Tile>> { val lastStep = steps.last() return if (lastStep == endTile) { listOf(steps) } else { getNeighborTiles(lastStep, steps).flatMap { takeAHike(steps + it) } } } val steps = takeAHike(getNeighborTiles(startTile, emptyList())) println(steps.maxOf { it.size }) //TODO Part 2 }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
2,940
advent-of-code
Apache License 2.0
src/main/kotlin/Day19.kt
clechasseur
318,029,920
false
null
import org.clechasseur.adventofcode2020.Day19Data object Day19 { private val rules = Day19Data.rules private val messages = Day19Data.messages private val letterRuleRegex = """^(\d+): "(\w)"$""".toRegex() private val multiRuleRegex = """^(\d+): (\d+(?: \d+)*)$""".toRegex() private val orRuleRegex = """^(\d+): (\d+(?: \d+)*) \| (\d+(?: \d+)*)$""".toRegex() fun part1(): Int { val rulesMap = rules.toRules() val rule0 = rulesMap[0]!!.asRegexString(rulesMap).toRegex() return messages.lines().count { rule0.matches(it) } } fun part2(): Int { val rulesMap = rules.toRules().toMutableMap() rulesMap[8] = OneOrMoreRule(MultiRule(listOf(42))) rulesMap[11] = OrRule(listOf( MultiRule(listOf(42, 31)), MultiRule(listOf(42, 42, 31, 31)), MultiRule(listOf(42, 42, 42, 31, 31, 31)), MultiRule(listOf(42, 42, 42, 42, 31, 31, 31, 31)) )) val rule0 = rulesMap[0]!!.asRegexString(rulesMap).toRegex() return messages.lines().count { rule0.matches(it) } } private interface Rule { fun asRegexString(rules: Map<Int, Rule>): String } private class LetterRule(val letter: Char) : Rule { override fun asRegexString(rules: Map<Int, Rule>): String = "$letter" } private class MultiRule(val multi: List<Int>) : Rule { override fun asRegexString(rules: Map<Int, Rule>): String = multi.joinToString("") { rules[it]!!.asRegexString(rules) } } private class OrRule(val alternatives: List<Rule>) : Rule { override fun asRegexString(rules: Map<Int, Rule>): String = alternatives.joinToString(separator = "|", prefix = "(", postfix = ")") { it.asRegexString(rules) } } private class OneOrMoreRule(val sub: Rule) : Rule { override fun asRegexString(rules: Map<Int, Rule>): String = "(${sub.asRegexString(rules)})+" } private fun String.toRules(): Map<Int, Rule> = lines().associate { line -> when { letterRuleRegex.matches(line) -> line.toLetterRule() multiRuleRegex.matches(line) -> line.toMultiRule() orRuleRegex.matches(line) -> line.toOrRule() else -> error("Not a valid rule: $line") } } private fun String.toLetterRule(): Pair<Int, Rule> { val match = letterRuleRegex.matchEntire(this) ?: error("Not a letter rule: $this") val (rule, letter) = match.destructured return rule.toInt() to LetterRule(letter.single()) } private fun String.toMultiRule(): Pair<Int, Rule> { val match = multiRuleRegex.matchEntire(this) ?: error("Not a multi rule: $this") val (rule, multi) = match.destructured return rule.toInt() to MultiRule(multi.split(' ').map { it.toInt() }) } private fun String.toOrRule(): Pair<Int, Rule> { val match = orRuleRegex.matchEntire(this) ?: error("Not an OR rule: $this") val (rule, eitherThisMulti, orThatMulti) = match.destructured return rule.toInt() to OrRule(listOf( MultiRule(eitherThisMulti.split(' ').map { it.toInt() }), MultiRule(orThatMulti.split(' ').map { it.toInt() }) )) } }
0
Kotlin
0
0
6173c9da58e3118803ff6ec5b1f1fc1c134516cb
3,259
adventofcode2020
MIT License
src/main/kotlin/days/Day10Solution.kt
yigitozgumus
434,108,608
false
{"Kotlin": 17835}
package days import BaseSolution class Day10Solution(inputList: List<String>) : BaseSolution(inputList) { private fun getClosing(operator: Char): Char = when (operator) { '(' -> ')' '[' -> ']' '{' -> '}' else -> '>' } private fun isOpen(operator: Char): Boolean = listOf('(', '[', '{', '<').contains(operator) private fun isClose(operator: Char): Boolean = listOf(')', ']', '}', '>').contains(operator) private fun mapToScore(operator: Char) = when (operator) { ')' -> 3 ']' -> 57 '}' -> 1197 else -> 25137 } private fun mapToAutoComplete(operator: Char) = when (operator) { ')' -> 1 ']' -> 2 '}' -> 3 else -> 4 } override fun part1() { val errorList = mutableListOf<Char>() inputList.forEachIndexed { _, line -> val lookupTable = ArrayDeque<Char>() lookupTable.addFirst(line.first()) line.substring(1).forEach { c -> when { lookupTable.isEmpty() && isOpen(c) -> lookupTable.addFirst(c) lookupTable.isEmpty() && isClose(c) -> { errorList.add(c) return@forEachIndexed } getClosing(lookupTable.first()) == c -> lookupTable.removeFirst() getClosing(lookupTable.first()) != c && isOpen(c) -> lookupTable.addFirst(c) else -> { errorList.add(c) return@forEachIndexed } } } } println(errorList.map { mapToScore(it) }.sum()) } override fun part2() { val autoCompleteList = mutableListOf<List<Char>>() inputList.forEachIndexed { _, s -> val lookupTable = ArrayDeque<Char>() lookupTable.addFirst(s.first()) s.substring(1).forEach { c -> when { lookupTable.isEmpty() && isOpen(c) -> lookupTable.addFirst(c) lookupTable.isEmpty() && isClose(c) -> { return@forEachIndexed } getClosing(lookupTable.first()) == c -> lookupTable.removeFirst() getClosing(lookupTable.first()) != c && isOpen(c) -> lookupTable.addFirst(c) else -> { return@forEachIndexed } } } autoCompleteList.add(lookupTable.map { getClosing(it) }) } println(autoCompleteList.map { var score: Long = 0L it.forEach { score *= 5L score += mapToAutoComplete(it) } score }.sorted()[autoCompleteList.size /2]) } }
0
Kotlin
0
0
c0f6fc83fd4dac8f24dbd0d581563daf88fe166a
2,856
AdventOfCode2021
MIT License
src/day12/RouteCache.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day12 typealias RouteCacheEntry = Pair<Point, Int> class RouteCache (val terrain: Terrain) { val grid = Array<RouteCacheEntry?> (terrain.xs * terrain.ys) { null } fun toIndex(x: Int, y: Int) = y * terrain.xs + x fun toIndex (point: Point) = point.y * terrain.xs + point.x fun get (x: Int, y: Int): RouteCacheEntry? = grid[toIndex (x, y)] fun get (point: Point): RouteCacheEntry? = grid[toIndex (point)] fun put (x: Int, y: Int, entry: RouteCacheEntry?) { grid[toIndex (x, y)] = entry } fun getSegment (start: Point): List<Point>? { var entry: RouteCacheEntry? = get (start) ?: return null val path = mutableListOf<Point> (start) while (entry != null) { path.add (entry.first) entry = get (entry.first) } return path } fun clear () { visit { x, y, _ -> grid[toIndex (x, y)] = null } return } fun visit (func: (Int, Int, RouteCacheEntry?) -> Unit) { for (y in 0 until terrain.ys) { for (x in 0 until terrain.xs) { func (x, y, get (x, y)) } } return } fun dump () { println (toString ()) return } override fun toString (): String { val buf = StringBuffer () val render: (v: Pair<Point, Int>?) -> String = { v -> if (v != null) "[${v.first.x},${v.first.y}]-${v.second}" else "-" } var max = 1 visit { x, y, v -> max = Math.max (max, render (v).length) } visit { x, y, v -> if (x == 0 && y != 0) { buf.append ("\n") } buf.append (String.format ("%${max}s", render (v))) buf.append (" ") } return buf.toString () } /** * Used to save the optimal paths to an end point from a set of possible paths from * a given starting point. */ fun save (paths: List<List<Point>>) { paths.forEach { path -> val size = path.size for (i in 0 until size - 1) { val (x, y) = path [i] val hops = size - i - 1 val already = get (x, y) if (already != null) { assert (already.second == hops) } put (x, y, Pair (path [i+1], hops)) } } return } } fun main (args: Array<String>) { val example = true val terrain = readTerrain(example) val rc = RouteCache (terrain) rc.save (listOf ( listOf (Point(0,0), Point(0,1), Point(1,1), Point(2,1), Point(2,2)) )) rc.dump () println (rc.getSegment(Point (0, 0))) println (rc.getSegment(Point (1,1))) return } // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
2,787
advent_of_code_2022
Apache License 2.0
src/main/kotlin/day14.kt
Gitvert
433,947,508
false
{"Kotlin": 82286}
fun day14() { val lines: List<String> = readFile("day14.txt") day14part1(lines) day14part2(lines) } fun day14part1(lines: List<String>) { val answer = findFinalPolymer(lines, 10) println("14a: $answer") } fun day14part2(lines: List<String>) { val answer = findFinalPolymer(lines, 40) println("14b: $answer") } fun findFinalPolymer(lines: List<String>, rounds: Int): Long { var polymer = lines[0] val insertionRules: MutableMap<String, String> = mutableMapOf() for (i in 2 until lines.size) { val line = lines[i] insertionRules[line.split(" -> ")[0]] = line.split(" -> ")[1] } var pairOccurrences: MutableMap<String, Long> = mutableMapOf() val charFrequency = LongArray(25) { 0L } for (i in 0..polymer.length - 2) { val pair = polymer[i].toString() + polymer[i + 1].toString() val oldValue = pairOccurrences.getOrDefault(pair, 0) pairOccurrences[pair] = oldValue + 1 } for (i in 0 until rounds) { val updatedPairOccurrences: MutableMap<String, Long> = mutableMapOf() pairOccurrences.keys.forEach { val firstPair = it[0].toString().plus(insertionRules[it]!!) val secondPair = insertionRules[it]!!.plus(it[1]) val firstPairOldValue = updatedPairOccurrences.getOrDefault(firstPair, 0) val secondPairOldValue = updatedPairOccurrences.getOrDefault(secondPair, 0) updatedPairOccurrences[firstPair] = firstPairOldValue + pairOccurrences[it]!! updatedPairOccurrences[secondPair] = secondPairOldValue + pairOccurrences[it]!! } pairOccurrences = updatedPairOccurrences } pairOccurrences.keys.forEach { val first = it[0] val second = it[1] val occurrences = pairOccurrences[it]!! charFrequency[first.code - 65] += occurrences charFrequency[second.code - 65] += occurrences } for (i in charFrequency.indices) { if (charFrequency[i] % 2 != 0L) { charFrequency[i]++ } charFrequency[i] /= 2L } val highestFrequency = charFrequency.maxOf { it } val lowestFrequency = charFrequency.filter { it > 0 }.minOf { it } return highestFrequency - lowestFrequency }
0
Kotlin
0
0
02484bd3bcb921094bc83368843773f7912fe757
2,271
advent_of_code_2021
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RingsAndRods.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 /** * 2103. Rings and Rods * @see <a href="https://leetcode.com/problems/rings-and-rods">Source</a> */ fun interface RingsAndRods { fun countPoints(rings: String): Int } class RingsAndRodsBF : RingsAndRods { override fun countPoints(rings: String): Int { val map = HashMap<String, MutableList<String>>() rings.chunked(2).forEach { val a = it[1].toString() val b = it.first().toString() if (map[a] == null) { map[a] = mutableListOf() map[a]?.add(b) } else { map[a]?.add(b) } } var i = 0 map.forEach { (_, u) -> if (u.containsAll(listOf("R", "G", "B"))) { i++ } } return i } } class RingsAndRodsBitmask : RingsAndRods { override fun countPoints(rings: String): Int { val rods = IntArray(10) var i = 0 while (i < rings.length - 1) { if (rings[i] == 'R') { rods[rings[i + 1] - '0'] = rods[rings[i + 1] - '0'] or (1 shl 0) } if (rings[i] == 'G') { rods[rings[i + 1] - '0'] = rods[rings[i + 1] - '0'] or (1 shl 1) } if (rings[i] == 'B') { rods[rings[i + 1] - '0'] = rods[rings[i + 1] - '0'] or (1 shl 2) } i += 2 } var total = 0 for (i0 in rods.indices) { if (rods[i0] == 7) total++ } return total } } class RingsAndRodsArray : RingsAndRods { class Ring { var hasRead = false var hasGreen = false var hasBlue = false } override fun countPoints(rings: String): Int { // Initialize val arr = arrayOfNulls<Ring>(10) for (i in 0..9) { arr[i] = Ring() } // Check every pair of chars var index = 0 val size: Int = rings.length while (index < size) { val target: Int = java.lang.String.valueOf(rings[index + 1]).toInt() when (rings[index]) { 'R' -> { arr[target]?.hasRead = true } 'G' -> { arr[target]?.hasGreen = true } else -> { arr[target]?.hasBlue = true } } index += 2 } // Count them var count = 0 for (i in 0..9) { if (arr[i]?.hasRead == true && arr[i]?.hasGreen == true && arr[i]?.hasBlue == true) { count++ } } return count } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,317
kotlab
Apache License 2.0
AOC-2017/src/main/kotlin/Day07.kt
sagar-viradiya
117,343,471
false
{"Kotlin": 72737}
import utils.DiskUnbalancedException import utils.Node import utils.splitAtComma import utils.splitAtNewLines import java.util.regex.Matcher import java.util.regex.Pattern object Day07 { private val PATTERN = Pattern.compile("(\\w+) \\((\\d+)\\)( -> (.*))?") fun part1(input: String) : String { val map = constructNodes(input) val childList = map.map { it.value.children }.flatten() return map.keys.minus(childList).first() } fun part2(input: String) : Int { val map = constructNodes(input) try { map.entries.filter { !it.value.children.isEmpty() }.forEach { calculateWeight(it.key, map) } } catch (e: DiskUnbalancedException) { return e.expectedWeight } throw IllegalStateException("All disks are balanced") } private fun calculateWeight(node: String, map: Map<String, Node>) : Int { if (map[node]!!.children.isEmpty()) { return map[node]!!.weight } else { val childWeightPairList = map[node]!!.children.map { it to calculateWeight(it, map) } if (childWeightPairList.size > 1) { val distinctWeights = childWeightPairList.map { it.second }.distinct() if (distinctWeights.size > 1) { var firstCount = 0 var secondCount = 0 val weights = childWeightPairList.map { it.second } for (weight in weights) { if (weight == distinctWeights[0]) { if (firstCount++ > 1) { break } } else if (secondCount++ > 1) { break } } val expectedWeight = if (firstCount < secondCount) { map[childWeightPairList[weights.indexOf(distinctWeights[0])].first]!!.weight + (distinctWeights[1] - distinctWeights[0]) } else { map[childWeightPairList[weights.indexOf(distinctWeights[1])].first]!!.weight + (distinctWeights[0] - distinctWeights[1]) } throw DiskUnbalancedException(expectedWeight) } else { return map[node]!!.weight + childWeightPairList.sumBy { it.second } } } else { return map[node]!!.weight + childWeightPairList[0].second } } } private fun constructNodes(input: String) : Map<String, Node> { var matcher: Matcher val map = mutableMapOf<String, Node>() input.splitAtNewLines().map { matcher = PATTERN.matcher(it) matcher.matches() val name = matcher.group(1) val weight = matcher.group(2).toInt() if (matcher.group(3) != null) { map.put(name, Node(name, weight, matcher.group(4).splitAtComma())) } else { map.put(name, Node(name, weight)) } } return map } }
0
Kotlin
0
0
7f88418f4eb5bb59a69333595dffa19bee270064
3,229
advent-of-code
MIT License
src/main/kotlin/org/flightofstairs/ctci/treesAndGraphs/BinarySearchTree.kt
FlightOfStairs
509,587,102
false
{"Kotlin": 38930}
package org.flightofstairs.ctci.treesAndGraphs import org.flightofstairs.ctci.treesAndGraphs.BstDirection.LEFT import org.flightofstairs.ctci.treesAndGraphs.BstDirection.MATCH import org.flightofstairs.ctci.treesAndGraphs.BstDirection.RIGHT class BinarySearchTree<Key : Comparable<Key>, Value>(private val comparator: Comparator<Key> = naturalOrder()) { private var root: BTreeNode<Entry<Key, Value>>? = null operator fun set(key: Key, value: Value) { val possibleNewNode = BTreeNode(Entry(key, value), null, null) if (root == null) { root = possibleNewNode } else { val candidate = path(key, root).last() when (val direction = comparator.direction(key, candidate.item.key)) { MATCH -> candidate.item.value = value else -> candidate[direction] = possibleNewNode } } } operator fun get(key: Key): Value? { val entry = path(key, root).lastOrNull()?.item ?: return null return if (comparator.direction(key, entry.key) == MATCH) entry.value else null } fun delete(key: Key): Value? { val path = path(key, root).toList() val candidate = path.lastOrNull() ?: return null if (comparator.direction(key, candidate.item.key) != MATCH) { return null } val nodePostDeletion = deleteNode(candidate) // I.e., deleting root if (root == candidate) { root = nodePostDeletion } else { val parent = path[path.size - 2] val direction = comparator.direction(candidate.item.key, parent.item.key) parent[direction] = nodePostDeletion } return candidate.item.value } private fun deleteNode(node: BTreeNode<Entry<Key, Value>>?): BTreeNode<Entry<Key, Value>>? { if (node == null) return null if (node.left == null) return node.right if (node.right == null) return node.left val pathToSuccessor = leftMostPath(node.right).toList() val successor = pathToSuccessor.last() val tmpItem = node.item node.item = successor.item successor.item = tmpItem if (successor == node.right) node.right = deleteNode(successor) else pathToSuccessor[pathToSuccessor.size - 2].left = deleteNode(successor) return node } private fun leftMostPath(node: BTreeNode<Entry<Key, Value>>?): Sequence<BTreeNode<Entry<Key, Value>>> = sequence { if (node != null) { yield(node) yieldAll(leftMostPath(node.left)) } } private fun path( key: Key, node: BTreeNode<Entry<Key, Value>>?, ): Sequence<BTreeNode<Entry<Key, Value>>> = sequence { if (node !== null) { yield(node) when (val direction = comparator.direction(key, node.item.key)) { MATCH -> {} else -> yieldAll(path(key, node[direction])) } } } } private data class Entry<Key, Value>(val key: Key, var value: Value) private enum class BstDirection { LEFT, MATCH, RIGHT } private fun <T> Comparator<T>.direction(a: T, b: T): BstDirection { val comparison = compare(a, b) return when { comparison < 0 -> LEFT comparison > 0 -> RIGHT else -> MATCH } } private operator fun <T> BTreeNode<T>.get(direction: BstDirection): BTreeNode<T>? { return when (direction) { LEFT -> left MATCH -> error("Not a valid direction to get node: MATCH") RIGHT -> right } } private operator fun <T> BTreeNode<T>.set(direction: BstDirection, child: BTreeNode<T>?) { when (direction) { LEFT -> left = child MATCH -> error("Not a valid direction to update node: MATCH") RIGHT -> right = child } }
0
Kotlin
0
0
5f4636ac342f0ee5e4f3517f7b5771e5aabe5992
3,854
FlightOfStairs-ctci
MIT License
app/src/main/kotlin/solution/Solution2131.kt
likexx
559,794,763
false
{"Kotlin": 136661}
package solution import solution.annotation.Leetcode import kotlin.math.* class Solution2131 { @Leetcode(2131) class Solution { fun longestPalindrome(words: Array<String>): Int { val counter = hashMapOf<String, Int>() var totalLength = 0 for (w in words) { if (counter.getOrDefault(w, 0) == 0) { val k = "${w[1]}${w[0]}" counter[k] = counter.getOrDefault(k, 0) + 1 } else { totalLength+=4 counter[w] = counter[w]!!-1 } } for (k in counter.keys) { if (k[0]==k[1] && counter[k]==1) { totalLength+=2 break } } return totalLength } fun longestPalindromeOriginal(words: Array<String>): Int { val counter= hashMapOf<String, Int>() val selfPalindrome = mutableSetOf<String>() for (w in words) { counter.putIfAbsent(w, 0) counter[w] = counter[w]!!+1 if (w[0]==w[1]) { selfPalindrome.add(w) } } var totalLength=0 for (k in counter.keys) { val expect = "${k[1]}${k[0]}" if (counter.getOrDefault(expect, 0) == 0) { continue } if (expect != k) { val cost = min(counter[k]!!, counter[expect]!!) totalLength += 2*cost counter[k] = counter[k]!! - cost counter[expect] = counter[expect]!! - cost } else { val cost = counter[k]!!/2 totalLength += 2*cost counter[k] = counter[k]!! - cost*2 } } for (w in selfPalindrome) { if (counter.getOrDefault(w, 0) > 0) { totalLength+=1 break } } return totalLength*2 } } }
0
Kotlin
0
0
376352562faf8131172e7630ab4e6501fabb3002
2,162
leetcode-kotlin
MIT License
src/main/kotlin/io/github/ajoz/puzzles/Day02.kt
ajoz
574,043,593
false
{"Kotlin": 21275}
package io.github.ajoz.puzzles import io.github.ajoz.utils.readInput import java.lang.IllegalArgumentException /** * --- Day 2: Rock Paper Scissors --- * * The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant * Rock Paper Scissors tournament is already in progress. * * Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each * simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: * Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, * the round instead ends in a draw. * * Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say * will be sure to help you win. "The first column is what your opponent is going to play: A for Rock, B for Paper, * and C for Scissors. The second column--" Suddenly, the Elf is called away to help with someone's tent. * * The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. * Winning every time would be suspicious, so the responses must have been carefully chosen. * * The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores * for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, * and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, * and 6 if you won). * * Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get * if you were to follow the strategy guide. */ fun main() { val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(testInput)) check(part2(testInput) == 12) println(part2(input)) } /** * --- Part One --- * * What would your total score be if everything goes exactly according to your strategy guide? */ private fun part1(input: List<String>): Int { return input.fold(0) { totalScore, inputLine -> val (opponentShape, playerShape) = inputLine.split(" ").map { it.toShape() } totalScore + playerShape.points + playerShape.getOutcomeFor(opponentShape).points } } /** * --- Part Two --- * * The Elf finishes helping with the tent and sneaks back over to you. "Anyway, the second column says how the round * needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. * Good luck!" * * The total score is still calculated in the same way, but now you need to figure out what shape to choose so the round * ends as indicated. The example above now goes like this: * * In the first round, your opponent will choose Rock (A), and you need the round to end in a draw (Y), so you also * choose Rock. This gives you a score of 1 + 3 = 4. * In the second round, your opponent will choose Paper (B), and you choose Rock so you lose (X) with a score * of 1 + 0 = 1. * In the third round, you will defeat your opponent's Scissors with Rock for a score of 1 + 6 = 7. * * Now that you're correctly decrypting the ultra top secret strategy guide, you would get a total score of 12. */ private fun part2(input: List<String>): Int { return input.fold(0) { totalScore, inputLine -> val (opponent, game) = inputLine.split(" ") val opponentShape = opponent.toShape() val gameOutcome = game.toOutcome() val playerShape = opponentShape.getShapeFor(gameOutcome) totalScore + playerShape.points + gameOutcome.points } } enum class Shape(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3), } enum class Outcome(val points: Int) { LOSS(0), DRAW(3), WIN(6), } fun Shape.getOutcomeFor(other: Shape): Outcome = when (this) { Shape.ROCK -> when (other) { Shape.ROCK -> Outcome.DRAW Shape.SCISSORS -> Outcome.WIN Shape.PAPER -> Outcome.LOSS } Shape.SCISSORS -> when (other) { Shape.ROCK -> Outcome.LOSS Shape.SCISSORS -> Outcome.DRAW Shape.PAPER -> Outcome.WIN } Shape.PAPER -> when (other) { Shape.ROCK -> Outcome.WIN Shape.SCISSORS -> Outcome.LOSS Shape.PAPER -> Outcome.DRAW } } fun String.toShape(): Shape = when { this == "A" || this == "X" -> Shape.ROCK this == "B" || this == "Y" -> Shape.PAPER this == "C" || this == "Z" -> Shape.SCISSORS else -> throw IllegalArgumentException("Unknown shape type: >$this<") } fun String.toOutcome(): Outcome = when { this == "X" -> Outcome.LOSS this == "Y" -> Outcome.DRAW this == "Z" -> Outcome.WIN else -> throw IllegalArgumentException("Unknown outcome type: >$this<") } fun Shape.getShapeFor(outcome: Outcome): Shape = when (this) { Shape.ROCK -> when (outcome) { Outcome.WIN -> Shape.PAPER Outcome.DRAW -> Shape.ROCK Outcome.LOSS -> Shape.SCISSORS } Shape.PAPER -> when (outcome) { Outcome.WIN -> Shape.SCISSORS Outcome.DRAW -> Shape.PAPER Outcome.LOSS -> Shape.ROCK } Shape.SCISSORS -> when (outcome) { Outcome.WIN -> Shape.ROCK Outcome.DRAW -> Shape.SCISSORS Outcome.LOSS -> Shape.PAPER } }
0
Kotlin
0
0
6ccc37a4078325edbc4ac1faed81fab4427845b8
5,706
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountNicePairs.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.DECIMAL import dev.shtanko.algorithms.MOD /** * 1814. Count Nice Pairs in an Array * @see <a href="https://leetcode.com/problems/count-nice-pairs-in-an-array">Source</a> */ fun interface CountNicePairs { operator fun invoke(nums: IntArray): Int fun rev(a: Int): Int { var a0 = a var b = 0 while (a0 > 0) { b = b * DECIMAL + a0 % DECIMAL a0 /= DECIMAL } return b } } /** * Straight Forward solution */ class CountNicePairsSF : CountNicePairs { override operator fun invoke(nums: IntArray): Int { var res = 0 val count: MutableMap<Int, Int> = HashMap() for (a in nums) { val b = rev(a) val v = count[a - b] ?: 0 count[a - b] = v + 1 res = (res + v) % MOD } return res } } class CountNicePairsTwoSum : CountNicePairs { override operator fun invoke(nums: IntArray): Int { val m: MutableMap<Int, Int> = HashMap() var res = 0 for (n in nums) { val comp = n - rev(n) val prev = m.getOrDefault(comp, 0) res = (res + prev) % MOD m[comp] = prev + 1 } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,905
kotlab
Apache License 2.0
src/main/kotlin/g0901_1000/s0920_number_of_music_playlists/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0920_number_of_music_playlists // #Hard #Dynamic_Programming #Math #Combinatorics // #2023_04_17_Time_136_ms_(100.00%)_Space_35.3_MB_(100.00%) class Solution { fun numMusicPlaylists(n: Int, l: Int, k: Int): Int { val dp = Array(l) { LongArray(n + 1) } for (i in 0 until l) { dp[i].fill(-1) } return helper(0, l, 0, n, k, dp).toInt() } private fun helper(songNumber: Int, l: Int, usedSong: Int, n: Int, k: Int, dp: Array<LongArray>): Long { if (songNumber == l) { return if (usedSong == n) 1 else 0 } if (dp[songNumber][usedSong] != -1L) { return dp[songNumber][usedSong] } val ans: Long = if (songNumber < k) { (n - usedSong) * helper(songNumber + 1, l, usedSong + 1, n, k, dp) } else if (usedSong == n) { (usedSong - k) * helper(songNumber + 1, l, usedSong, n, k, dp) } else { ( (n - usedSong) * helper(songNumber + 1, l, usedSong + 1, n, k, dp) + (usedSong - k) * helper(songNumber + 1, l, usedSong, n, k, dp) ) } val mod = 1e9.toInt() + 7 dp[songNumber][usedSong] = ans % mod return ans % mod } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,283
LeetCode-in-Kotlin
MIT License
src/com/aaron/helloalgorithm/algorithm/数组/_20_有效的括号.kt
aaronzzx
431,740,908
false
null
package com.aaron.helloalgorithm.algorithm.数组 import com.aaron.helloalgorithm.algorithm.LeetCode import java.util.* /** * # 20. 有效的括号 * * 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。 * * 有效字符串需满足: * * 左括号必须用相同类型的右括号闭合。 * 左括号必须以正确的顺序闭合。 * * 来源:力扣(LeetCode) * * 链接:[https://leetcode-cn.com/problems/valid-parentheses] * * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author <EMAIL> * @since 2021/11/26 */ class _20_有效的括号 /** * 使用栈对非右括号的元素进行入栈,如果是右括号则判断栈是否为空,不为空意味着以右括号开头, * 显然是错误的;如果栈不为空且出栈元素不是左括号那也是错的。 * * 使用 Map 简化条件判断,提前将成对括号存储,直接使用字符取对应括号字符。 */ fun LeetCode.数组._20_有效的括号(s: String): Boolean { if (s.isEmpty()) return false val stack: Deque<Char> = LinkedList() val map = hashMapOf( '}' to '{', ']' to '[', ')' to '(' ) s.forEach { if (map.containsKey(it)) { // 是右括号 if (stack.isEmpty() || map[it] != stack.pop()) { // 1. 栈为空,意味着右括号开头,不成立 // 2. 出栈元素不是左括号,不成立 return false } } else { // 是左括号,入栈 stack.push(it) } } return stack.isEmpty() }
0
Kotlin
0
0
2d3d823b794fd0712990cbfef804ac2e138a9db3
1,716
HelloAlgorithm
Apache License 2.0
calendar/day14/Day14.kt
rocketraman
573,845,375
false
{"Kotlin": 45660}
package day14 import Day import Lines class Day14 : Day() { data class Point(val x: Int, val y: Int) val source = Point(500, 0) fun rockPoints(input: Lines): Set<Point> = input.flatMap { i -> i.split(" -> ") .map { vertex -> vertex.split(",").let { Point(it[0].toInt(), it[1].toInt()) } } .windowed(2) .flatMap { (p1, p2) -> // fill in the points and get a complete set of rock locations if (p1.x == p2.x) { if (p1.y < p2.y) { (p2.y downTo p1.y).map { Point(p1.x, it) } } else { (p1.y downTo p2.y).map { Point(p1.x, it) } } } else { if (p1.x < p2.x) { (p2.x downTo p1.x).map { Point(it, p1.y) } } else { (p1.x downTo p2.x).map { Point(it, p1.y) } } } } }.toSet() override fun part1(input: Lines): Any { val rockLocations = rockPoints(input) val maxRockY = rockLocations.maxOf { it.y } fun nextSandLocation( sandLocations: Set<Point> = emptySet(), startFrom: Point = source, ): Set<Point>? { val candidates = listOf( startFrom.copy(y = startFrom.y + 1), startFrom.copy(x = startFrom.x - 1, y = startFrom.y + 1), startFrom.copy(x = startFrom.x + 1, y = startFrom.y + 1), ) candidates.forEach { candidate -> if (candidate !in rockLocations && candidate !in sandLocations) { return if (candidate.y > maxRockY) { null } else { nextSandLocation(sandLocations, candidate) } } } // done this sand particle, on to the next return sandLocations + startFrom } val sandLocations = generateSequence(nextSandLocation()) { nextSandLocation(it) }.last() printCave(rockLocations, sandLocations) return sandLocations.size } override fun part2(input: Lines): Any { val rockLocations = rockPoints(input) val maxRockY = rockLocations.maxOf { it.y } val floorY = maxRockY + 2 fun nextSandLocation( sandLocations: Set<Point> = emptySet(), startFrom: Point = source, ): Set<Point>? { val candidates = listOf( startFrom.copy(y = startFrom.y + 1), startFrom.copy(x = startFrom.x - 1, y = startFrom.y + 1), startFrom.copy(x = startFrom.x + 1, y = startFrom.y + 1), ) candidates.forEach { candidate -> if (candidate !in rockLocations && candidate !in sandLocations && candidate.y < floorY) { return nextSandLocation(sandLocations, candidate) } } // done this sand particle, on to the next (as long as the sand does not cover the source) return if (startFrom != source) sandLocations + startFrom else null } val sandLocations = generateSequence(nextSandLocation()) { nextSandLocation(it) }.last() printCave(rockLocations, sandLocations) return sandLocations.size } fun printCave(rockPoints: Set<Point>, sandPoints: Set<Point>) { val allPoints = rockPoints + sandPoints val minX = allPoints.minOf { it.x } val maxX = allPoints.maxOf { it.x } val maxY = allPoints.maxOf { it.y } for (y in 0..maxY) { for (x in minX..maxX) { when (Point(x, y)) { in rockPoints -> print("█") in sandPoints -> print("o") else -> print(".") } } print("\n") } } }
0
Kotlin
0
0
6bcce7614776a081179dcded7c7a1dcb17b8d212
3,447
adventofcode-2022
Apache License 2.0
src/main/kotlin/days/Day18.kt
butnotstupid
433,717,137
false
{"Kotlin": 55124}
package days class Day18 : Day(18) { override fun partOne(): Any { return inputList.map { line -> parseNumber(line) }.reduce(FishNumber::plus).magnitude } override fun partTwo(): Any { return inputList.flatMap { one -> inputList.flatMap { another -> if (one != another) { listOf( (parseNumber(one) + parseNumber(another)).magnitude, (parseNumber(another) + parseNumber(one)).magnitude ) } else emptyList() } }.maxOrNull()!! } private fun parseNumber(line: String, parent: FishNumber? = null): FishNumber { return line.toIntOrNull()?.let { FishNumber(it, parent) } ?: line.let { var balance = 0 var part = 0 val parts = listOf(StringBuilder(), StringBuilder()) for (c in line) { when (c) { '[' -> { balance += 1 if (balance > 1) parts[part].append(c) } ']' -> { balance -= 1 if (balance > 0) parts[part].append(c) } ',' -> { if (balance == 1) part += 1 if (balance > 1) parts[part].append(c) } else -> parts[part].append(c) } } val (left, right) = parts.map { it.toString() } FishNumber(null, parent).apply { this.left = parseNumber(left, this) this.right = parseNumber(right, this) } } } data class FishNumber( var value: Int?, var parent: FishNumber?, var left: FishNumber? = null, var right: FishNumber? = null ) { val magnitude: Long get() = if (this.value != null) value!!.toLong() else this.left!!.magnitude * 3 + this.right!!.magnitude * 2 private val firstLeft: FishNumber? get() { var cur: FishNumber? = this while (cur?.parent != null && cur.parent?.left == cur) cur = cur.parent!! cur = cur?.parent?.left while (cur?.right != null) cur = cur.right return cur } private val firstRight: FishNumber? get() { var cur: FishNumber? = this while (cur?.parent != null && cur.parent?.right == cur) cur = cur.parent!! cur = cur?.parent?.right while (cur?.left != null) cur = cur.left return cur } operator fun plus(other: FishNumber): FishNumber { val result = FishNumber(null, null, this, other) this.parent = result other.parent = result return result.reduce() } private fun reduce(): FishNumber { val number = this var reduced: Boolean do { reduced = if (number.reduceDepth(0)) true else number.reduceValue() } while (reduced) return number } private fun reduceDepth(depth: Int): Boolean { return when { value != null -> false depth == 4 -> { // explode this.firstLeft?.let { it.value = it.value!! + this.left?.value!! } this.firstRight?.let { it.value = it.value!! + this.right?.value!! } if (this.parent?.left == this) { this.parent!!.left = FishNumber(0, this.parent) true } else { this.parent!!.right = FishNumber(0, this.parent) true } } else -> { when { this.left?.reduceDepth(depth + 1) ?: false -> true else -> this.right?.reduceDepth(depth + 1) ?: false } } } } private fun reduceValue(): Boolean { return when { value != null && value!! >= 10 -> { // split this.left = FishNumber(value!! / 2, this) this.right = FishNumber((value!! + 1) / 2, this) value = null true } value != null && value!! < 10 -> false else -> { when { this.left?.reduceValue() ?: false -> true else -> this.right?.reduceValue() ?: false } } } } override fun toString(): String { return when { value != null -> value.toString() else -> "[$left,$right]" } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FishNumber if (value != other.value) return false if (left != other.left) return false if (right != other.right) return false if (parent !== other.parent) return false return true } override fun hashCode(): Int { var result = value ?: 0 result = 31 * result + (parent?.hashCode() ?: 0) result = 31 * result + (left?.hashCode() ?: 0) result = 31 * result + (right?.hashCode() ?: 0) return result } } }
0
Kotlin
0
0
a06eaaff7e7c33df58157d8f29236675f9aa7b64
5,868
aoc-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/uber/tagir/advent2018/day02/day02.kt
groz
159,977,575
false
null
package com.uber.tagir.advent2018.day02 import com.uber.tagir.advent2018.utils.resourceAsString fun main(args: Array<String>) { Day02().checksum() Day02().findFabric() } data class Repetitions(val twice: Boolean, val thrice: Boolean) class Day02 { private val lines = resourceAsString("input.txt").lines() fun checksum() { val repetitions = lines.map(this::calculateRepetitions) val result = repetitions.count { it.twice } * repetitions.count { it.thrice } println(result) } private fun calculateRepetitions(line: String): Repetitions { val m = mutableMapOf<Char, Int>() for (c in line) { m[c] = m.getOrDefault(c, 0) + 1 } // line.associateWithTo(m) { m.getOrDefault(it, 0) + 1 } return Repetitions(m.values.contains(2), m.values.contains(3)) } fun findFabric() { // O(N^2 * k) feels bad for (i in 0 until lines.size - 1) { for (j in (i + 1) until lines.size) { val pos = differAt(lines[i], lines[j]) if (pos != null) { // could also use ?.let { ... } println(lines[i].removeRange(pos..pos)) return } } } } private fun differAt(a: String, b: String): Int? { if (a.length != b.length) { return null } var count = 0 var pos: Int? = null for (idx in 0 until a.length) { if (a[idx] != b[idx]) { count++ pos = idx } if (count > 1) { return null } } return if (count == 1) pos else null } }
0
Kotlin
0
0
19b5a5b86c9a3d2803192b8c6786a25151b5144f
1,720
advent2018
MIT License
src/Day09.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
import java.lang.Integer.min import java.lang.Integer.max import kotlin.math.abs fun main() { var hPos = Pair(0, 0) var tPos = Pair(0, 0) fun calcTailMove(h: Pair<Int, Int>, t: Pair<Int, Int>, dir: String): Pair<Int, Int> { val (x, y) = h val (tx, ty) = t if (x == tx && y == ty) { return t } val xDiv = max(tx, x) - min(tx, x) val yDiv = max(ty, y) - min(ty, y) if (xDiv > 1) { // they don't touch on x-axis if (yDiv == 1) { return if (tx > x) { Pair(tx - 1, y) } else { Pair(tx + 1, y) } } return if (tx > x) { Pair(tx - 1, ty) } else { Pair(tx + 1, ty) } } if (yDiv > 1) { // they don't touch on y-axis if (xDiv == 1) { return if (ty > y) { Pair(x, ty - 1) } else { Pair(x, ty + 1) } } return if (ty > y) { Pair(tx, ty - 1) } else { Pair(tx, ty + 1) } } return t } fun markTailOnMatrix(t: Pair<Int, Int>, matrix: ArrayList<Triple<Int, Int, Int>>) { val (x, y) = t val position = matrix.find { it.first == x && it.second == y } if (position == null) { matrix.add(Triple(x, y, 1)) } else { matrix.remove(position) matrix.add(Triple(x, y, position.third + 1)) } } fun move(dir: String, steps: Int, matrix: ArrayList<Triple<Int, Int, Int>>) { when (dir) { "R" -> { for (i in 1..steps) { hPos = Pair(hPos.first + 1, hPos.second) tPos = calcTailMove(hPos, tPos, dir) markTailOnMatrix(tPos, matrix) } } "L" -> { for (i in 1..steps) { hPos = Pair(hPos.first - 1, hPos.second) tPos = calcTailMove(hPos, tPos, dir) markTailOnMatrix(tPos, matrix) } } "U" -> { for (i in 1..steps) { hPos = Pair(hPos.first, hPos.second + 1) tPos = calcTailMove(hPos, tPos, dir) markTailOnMatrix(tPos, matrix) } } "D" -> { for (i in 1..steps) { hPos = Pair(hPos.first, hPos.second - 1) tPos = calcTailMove(hPos, tPos, dir) markTailOnMatrix(tPos, matrix) } } } } fun part1(input: List<String>): Int { val matrix = arrayListOf<Triple<Int, Int, Int>>() matrix.add(Triple(0, 0, 1)) input.forEach { line -> val (dir, steps) = line.split(" ") move(dir, steps.toInt(), matrix) } return matrix.size } fun moveTail(dir: String, steps: Int, matrix: ArrayList<Triple<Int, Int, Int>>, tails: Array<Pair<Int, Int>>) { when (dir) { "R" -> { for (i in 1..steps) { hPos = Pair(hPos.first + 1, hPos.second) tails.forEachIndexed { index, pair -> val prev = tails.getOrElse(index - 1) { hPos } tails[index] = calcTailMove(prev, pair, dir) if (index == tails.lastIndex) { markTailOnMatrix(tails[index], matrix) } } } } "L" -> { for (i in 1..steps) { hPos = Pair(hPos.first - 1, hPos.second) tails.forEachIndexed { index, pair -> val prev = tails.getOrElse(index - 1) { hPos } tails[index] = calcTailMove(prev, pair, dir) if (index == tails.lastIndex) { markTailOnMatrix(tails[index], matrix) } } } } "U" -> { for (i in 1..steps) { hPos = Pair(hPos.first, hPos.second + 1) tails.forEachIndexed { index, pair -> val prev = tails.getOrElse(index - 1) { hPos } tails[index] = calcTailMove(prev, pair, dir) if (index == tails.lastIndex) { markTailOnMatrix(tails[index], matrix) } } } } "D" -> { for (i in 1..steps) { hPos = Pair(hPos.first, hPos.second - 1) tails.forEachIndexed { index, pair -> val prev = tails.getOrElse(index - 1) { hPos } tails[index] = calcTailMove(prev, pair, dir) if (index == tails.lastIndex) { markTailOnMatrix(tails[index], matrix) } } } } } } fun part2(input: List<String>): Int { val matrix = arrayListOf<Triple<Int, Int, Int>>() matrix.add(Triple(0, 0, 1)) val tails = (1..9).map { Pair(0, 0) }.toTypedArray() input.forEach { line -> val (dir, steps) = line.split(" ") moveTail(dir, steps.toInt(), matrix, tails) } return matrix.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") // check(part1(testInput) == 13) // check(part2(testInput) == 36) val input = readInput("Day09") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
6,027
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/sk/set2/289. Game of Life.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set2 private fun gameOfLife(board: Array<IntArray>) { val neighbors = intArrayOf(0, 1, -1) val rows = board.size val cols: Int = board[0].size val copyBoard = Array(rows) { IntArray(cols) } for (row in 0 until rows) { for (col in 0 until cols) { copyBoard[row][col] = board[row][col] } } for (row in 0 until rows) { for (col in 0 until cols) { var liveNeighbors = 0 for (i in 0..2) { for (j in 0..2) { if (!(neighbors[i] == 0 && neighbors[j] == 0)) { val r = row + neighbors[i] val c = col + neighbors[j] if (r in 0 until rows && c in 0 until cols && copyBoard[r][c] == 1) liveNeighbors++ } } } // Rule 1 or Rule 3 if (copyBoard[row][col] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) { board[row][col] = 0 } // Rule 4 if (copyBoard[row][col] == 0 && liveNeighbors == 3) { board[row][col] = 1 } } } } private fun gameOfLife2(board: Array<IntArray>?) { if (board == null || board.isEmpty()) return val r = board.size val c: Int = board[0].size fun liveNeighbors(board: Array<IntArray>, m: Int, n: Int, i: Int, j: Int): Int { var lives = 0 for (x in maxOf(i - 1, 0)..minOf(i + 1, m - 1)) { for (y in maxOf(j - 1, 0)..minOf(j + 1, n - 1)) { lives += board[x][y] and 1 } } lives -= board[i][j] and 1 return lives } for (i in 0 until r) { for (j in 0 until c) { val lives = liveNeighbors(board, r, c, i, j) // In the beginning, every 2nd bit is 0; // So we only need to care about when will the 2nd bit become 1. if (board == null || board.isEmpty()) return // val m = board.size // val n: Int = board[0].size if (board[i][j] == 1 && lives >= 2 && lives <= 3) { board[i][j] = 3 // Make the 2nd bit 1: 01 ---> 11 } if (board[i][j] == 0 && lives == 3) { board[i][j] = 2 // Make the 2nd bit 1: 00 ---> 10 } } } for (i in 0 until r) { for (j in 0 until c) { board[i][j] = board[i][j] shr 1 // Get the 2nd state. } } } class Solution289 { /** * Go over matrix and check every cell situation for next generation using 8 neighbours. * If this cell is supposed to change then do -2 for it, to make it negative * Otherwise, don't change as it's not supposed to change in next generation. * * Go over matrix again, if value is negative then, flip it */ fun gameOfLife(board: Array<IntArray>): Unit { for (r in board.indices) { for (c in board[0].indices) { val cur = board[r][c] val live = liveNeighbour(board, r, c) when { cur == 1 && live < 2 -> { board[r][c] -= 2 // It has to flip } cur == 1 && (live == 2 || live == 3) -> { // No flip, No change } cur == 1 && live > 3 -> { board[r][c] -= 2 // It has to flip } cur == 0 && live == 3 -> { board[r][c] -= 2 // It has to flip } } } } for (r in board.indices) { for (c in board[0].indices) { if (board[r][c] < 0) { board[r][c] += 2 // Original value board[r][c] = if (board[r][c] == 0) 1 else 0 } } } } private fun liveNeighbour(board: Array<IntArray>, r: Int, c: Int): Int { if (r !in 0..board.lastIndex || c !in 0..board[0].lastIndex) return 0 var count = 0 if (c - 1 >= 0 && (board[r][c - 1] == 1 || board[r][c - 1] + 2 == 1)) count++ if (c - 1 >= 0 && r - 1 >= 0 && (board[r - 1][c - 1] == 1 || board[r - 1][c - 1] + 2 == 1)) count++ if (r - 1 >= 0 && (board[r - 1][c] == 1 || board[r - 1][c] + 2 == 1)) count++ if (r - 1 >= 0 && c + 1 < board[0].size && (board[r - 1][c + 1] == 1 || board[r - 1][c + 1] + 2 == 1)) count++ if (c + 1 < board[0].size && (board[r][c + 1] == 1 || board[r][c + 1] + 2 == 1)) count++ if (r + 1 < board.size && c + 1 < board[0].size && (board[r + 1][c + 1] == 1 || board[r + 1][c + 1] + 2 == 1)) count++ if (r + 1 < board.size && (board[r + 1][c] == 1 || board[r + 1][c] + 2 == 1)) count++ if (r + 1 < board.size && c - 1 >= 0 && (board[r + 1][c - 1] == 1 || board[r + 1][c - 1] + 2 == 1)) count++ return count } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
5,001
leetcode-kotlin
Apache License 2.0
src/commonMain/kotlin/eu/yeger/cyk/CYK.kt
DerYeger
302,742,119
false
null
package eu.yeger.cyk import eu.yeger.cyk.model.* import eu.yeger.cyk.model.withSymbolAt import eu.yeger.cyk.parser.word public fun cyk( wordString: String, grammar: () -> Result<Grammar> ): Result<CYKModel> { return word(wordString).with(grammar(), ::cyk) } public fun cyk( word: Result<Word>, grammar: Result<Grammar> ): Result<CYKModel> { return word.with(grammar, ::cyk) } public fun cyk( word: Word, grammar: Grammar, ): CYKModel { return (0..word.size).fold(CYKModel(word, grammar)) { cykModel: CYKModel, l: Int -> when (l) { 0 -> cykModel.propagateTerminalProductionRules() else -> cykModel.propagateNonTerminalProductionRules(l + 1) } } } private fun CYKModel.propagateTerminalProductionRules(): CYKModel { return word.foldIndexed(this) { terminalSymbolIndex: Int, cykModel: CYKModel, terminalSymbol: TerminalSymbol -> cykModel.findProductionRulesForTerminalSymbol(terminalSymbol, terminalSymbolIndex) } } private fun CYKModel.findProductionRulesForTerminalSymbol( terminalSymbol: TerminalSymbol, terminalSymbolIndex: Int, ): CYKModel { return grammar.productionRuleSet.terminatingRules.fold(this) { cykModel: CYKModel, terminatingRule: TerminatingRule -> when { terminatingRule produces terminalSymbol -> cykModel.withSymbolAt( terminatingRule.left, rowIndex = 0, columnIndex = terminalSymbolIndex ) else -> cykModel } } } private fun CYKModel.propagateNonTerminalProductionRules( l: Int, ): CYKModel { return (1..(word.size - l + 1)).fold(this) { rowModel: CYKModel, s: Int -> (1 until l).fold(rowModel) { columnModel: CYKModel, p: Int -> columnModel.findProductionRulesForNonTerminalSymbols(l = l, s = s, p = p) } } } private fun CYKModel.findProductionRulesForNonTerminalSymbols( l: Int, s: Int, p: Int, ): CYKModel { return grammar.productionRuleSet.nonTerminatingRules.fold(this) { cykModel: CYKModel, nonTerminatingRule: NonTerminatingRule -> when { cykModel.allowsNonTerminalRuleAt(nonTerminatingRule, l = l, s = s, p = p) -> cykModel.withSymbolAt( nonTerminatingRule.left, rowIndex = l - 1, columnIndex = s - 1 ) else -> cykModel } } }
0
Kotlin
0
2
76b895e3e8ea6b696b3ad6595493fda9ee3da067
2,432
cyk-algorithm
MIT License
leetcode/src/offer/Offer32.kt
zhangweizhe
387,808,774
false
null
package offer import linkedlist.TreeNode import java.util.* import kotlin.collections.ArrayList fun main() { // 剑指 Offer 32 - II. 从上到下打印二叉树 II // https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/ val root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.left?.right = TreeNode(8) root.right?.left = TreeNode(15) root.right?.right = TreeNode(7) val levelOrder = levelOrder1(root) levelOrder.forEach { println(it.toString()) } } /** * 循环实现,借助队列先进先出的特性 */ fun levelOrder1(root: TreeNode?): List<List<Int>> { val result = ArrayList<MutableList<Int>>() if (root == null) { return result } val queue = LinkedList<TreeNode>() queue.offer(root) while (!queue.isEmpty()) { val tmpList = ArrayList<Int>() val queueSize = queue.size for (i in 0 until queueSize) { val poll = queue.poll() tmpList.add(poll.`val`) if (poll.left != null) { queue.offer(poll.left) } if (poll.right != null) { queue.offer(poll.right) } } result.add(tmpList) } return result } /** * 递归实现 */ fun levelOrder(root: TreeNode?): List<List<Int>> { val result = ArrayList<MutableList<Int>>() help(root, 0, result) return result } fun help(root: TreeNode?, layer: Int, result: MutableList<MutableList<Int>>) { if (root == null) { return } val currentLayer = if (layer >= result.size) { val list = ArrayList<Int>() result.add(layer, list) list }else { result.get(layer) } currentLayer.add(root.`val`) help(root.left, layer+1, result) help(root.right, layer+1, result) }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,882
kotlin-study
MIT License
src/main/kotlin/quantum/core/QuantumState.kt
AlexanderScherbatiy
155,193,555
false
{"Kotlin": 58447}
package quantum.core import quantum.core.Complex.Companion.One import quantum.core.Complex.Companion.Zero interface QuantumState { val size: Int operator fun get(index: Int): Complex infix fun scalar(other: QuantumState): Complex { var scalar = Complex.Zero for (i in 0 until size) { scalar += this[i].conjugate() * other[i] } return scalar } infix fun tensor(other: QuantumState): QuantumState { val coefficients = Array(size * other.size) { Complex.Zero } var base = 0 for (i in 0 until size) { for (j in 0 until other.size) { coefficients[base + j] = this[i] * other[j] } base += other.size } return quantumState(*coefficients) } } fun quantumState(vararg coefficients: Complex): QuantumState = ArrayQuantumState(normalize(*coefficients)) fun quantumState(size: Int, coefficients: Map<Int, Complex>): QuantumState = MapQuantumState(size, normalize(coefficients)) fun tensor(n: Int, state: QuantumState): QuantumState = Array(n) { state }.reduce { s1, s2 -> s1 tensor s2 } fun tensor(states: Array<out QuantumState>): QuantumState { val bounds = states.map { it.size }.toIntArray() val counter = IntArray(bounds.size) counter[0] = -1 val coefficients = arrayListOf<Complex>() var hasNext = increment(counter, bounds) while (hasNext) { var c = One for ((stateIndex, coefficientIndex) in counter.withIndex()) { c *= states[stateIndex][coefficientIndex] } coefficients.add(c) hasNext = increment(counter, bounds) } return quantumState(*coefficients.toTypedArray()) } fun QuantumState.toArray(): Array<out Complex> = Array(size) { this[it] } private fun increment(counter: IntArray, bounds: IntArray): Boolean { for (i in 0 until bounds.size) { counter[i]++ if (counter[i] == bounds[i]) { counter[i] = 0 } else { return true } } return false } private fun normalize(vararg coefficients: Complex): Array<out Complex> { val sqr = coefficients.map { it.sqr() }.sum() if (sqr == 1.0) { return coefficients } val r = kotlin.math.sqrt(sqr) return Array(coefficients.size) { coefficients[it] / r } } private fun normalize(coefficients: Map<Int, Complex>): Map<Int, Complex> { val sqr = coefficients.values.map { it.sqr() }.sum() if (sqr == 1.0) { return coefficients } val r = kotlin.math.sqrt(sqr) return coefficients.mapValues { it.value / r } } data class Qubit private constructor(val zero: Complex, val one: Complex) : QuantumState { override val size = 2 override fun get(index: Int) = when (index) { 0 -> zero 1 -> one else -> throw IndexOutOfBoundsException("index $index, size: 2") } companion object { val Zero = Qubit(Complex.One, Complex.Zero) val One = Qubit(Complex.Zero, Complex.One) val Plus = from(Complex.One, Complex.One) val Minus = from(Complex.One, -Complex.One) fun from(zero: Complex, one: Complex): Qubit { val coefficients = normalize(zero, one) return Qubit(coefficients[0], coefficients[1]) } } } private class ArrayQuantumState(val coefficients: Array<out Complex>) : QuantumState { override val size = coefficients.size override fun get(index: Int) = coefficients[index] override fun toString() = "QuantumState(${coefficients.joinToString()})" fun toArray() = coefficients override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is QuantumState) return false return coefficients.contentEquals(other.toArray()) } override fun hashCode(): Int { return coefficients.contentHashCode() } } private class MapQuantumState(override val size: Int, val coefficients: Map<Int, Complex>) : QuantumState { override fun get(index: Int) = if (index < size) coefficients.getOrDefault(index, Zero) else throw IndexOutOfBoundsException("index: $index, size: $size") override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is QuantumState) return false return toArray().contentEquals(other.toArray()) } override fun hashCode(): Int { return toArray().contentHashCode() } override fun toString() = "QuantumState($size, $coefficients)" }
0
Kotlin
0
0
673dd1c2a6c9964700ea682d49410d10843070db
4,615
quntum-gates
Apache License 2.0
Kotlin/problems/0004_advantage_shuffle.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
//Problem Statement // Given two arrays A and B of equal size, the advantage of A with // respect to B is the number of indices i for which A[i] > B[i]. // // Return any permutation of A that maximizes its advantage with respect to B. class Solution { fun advantageCount(A: IntArray, B: IntArray): IntArray { var result:IntArray = IntArray(A.size) { i -> -1}; var helperB:MutableList<Pair<Int,Int>> = mutableListOf<Pair<Int,Int>>(); var to_add: MutableList<Int> = mutableListOf<Int>(); for(i in B.indices){ helperB.add(Pair(B[i],i)); } A.sort(); helperB.sortWith(compareBy({it.first})); var indexA: Int = 0; var indexB: Int = 0; while(indexA < A.size){ if(A[indexA]>helperB[indexB].first){ result[helperB[indexB].second]=A[indexA]; indexB++; }else{ to_add.add(A[indexA]); } indexA++; } indexA = 0; for(i in to_add.indices){ while(result[indexA]>=0){ indexA++; } result[indexA]=to_add[i]; } return result; } } fun main(args:Array<String>){ val numsA: IntArray = intArrayOf(2,7,11,15); val numsB: IntArray = intArrayOf(1,10,4,11); val sol:Solution = Solution(); println(sol.advantageCount(numsA,numsB).joinToString(prefix = "[", postfix = "]")); }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
1,451
algorithms
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/OddStringDifference.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 /** * 2451. Odd String Difference * @see <a href="https://leetcode.com/problems/odd-string-difference">Source</a> */ fun interface OddStringDifference { operator fun invoke(words: Array<String>): String } class OddStringDifferenceHashMap : OddStringDifference { override fun invoke(words: Array<String>): String { // [1] as stated in the problem, there will be two groups // of words according to their difference array; // we'll store them in a hashmap using the difference // array (actually, its hash) as a key val eq: MutableMap<Int, MutableList<String>> = HashMap() for (w in words) { val diff: MutableList<Int> = ArrayList() for (i in 1 until w.length) { diff.add(w[i].code - w[i - 1].code) } // [2] in Java, we can use not the difference array itself, // but rather its 'hashCode' as a hash/identifier // of each group of words eq.computeIfAbsent( diff.hashCode(), ) { ArrayList() }.add(w) } // [3] as guaranteed in the problem, there will be 2 // groups of words, one of them of size 1 for ((_, value) in eq) { if (value.size == 1) return value[0] } return words[0] // unreachable } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,008
kotlab
Apache License 2.0
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day21/Day21.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day21 import eu.janvdb.aocutil.kotlin.runWithTimer import kotlin.math.max //val START_1 = Player(4) //val START_2 = Player(8) val START_1 = Player(3) val START_2 = Player(5) fun main() { runWithTimer("Part 1", ::part1) runWithTimer("Part 2", ::part2) } private fun part1() { val die = DeterministicDie() var player1 = START_1 var player2 = START_2 while (true) { player1 = player1.play(die.roll() + die.roll() + die.roll()) if (player1.hasWon1()) { println("P1: $player1, P2: $player2, Die: $die, Score: ${player2.score * die.numberOfRolls}") break } player2 = player2.play(die.roll() + die.roll() + die.roll()) if (player2.hasWon1()) { println("P1: $player1, P2: $player2, Die: $die, Score: ${player1.score * die.numberOfRolls}") break } } } private fun part2() { val outcomesPerRollValue = /* How frequent a certain roll with three dice is */ IntRange(1, 3).flatMap { n1 -> IntRange(1, 3).flatMap { n2 -> IntRange(1, 3).map { n3 -> n1 + n2 + n3 } } } .groupingBy { it }.eachCount() val numberOfWinsPerStartPosition = mutableMapOf<StateDirac, ScoreDirac>() fun determineNumberOfWins(state: StateDirac): ScoreDirac { if (numberOfWinsPerStartPosition.contains(state)) { return numberOfWinsPerStartPosition[state]!! } if (state.player1.hasWon2()) { val score = ScoreDirac(1, 0) numberOfWinsPerStartPosition[state] = score return score } if (state.player2.hasWon2()) { val score = ScoreDirac(0, 1) numberOfWinsPerStartPosition[state] = score return score } val score = outcomesPerRollValue.asSequence() .map { determineNumberOfWins(state.play(it.key)) * it.value } .fold(ScoreDirac.ZERO) { acc, it -> acc + it } numberOfWinsPerStartPosition[state] = score return score } val numberOfWins = determineNumberOfWins(StateDirac(START_1, START_2, 1)) println("$numberOfWins ${max(numberOfWins.player1Won, numberOfWins.player2Won)}") } data class Player(val position: Int, val score: Int = 0) { fun play(dieValue: Int): Player { val newPosition = (position + dieValue - 1) % 10 + 1 val newScore = score + newPosition return Player(newPosition, newScore) } fun hasWon1() = score >= 1000 fun hasWon2() = score >= 21 override fun toString() = "$position/$score" } class DeterministicDie { var numberOfRolls = 0 fun roll(): Int { numberOfRolls++ return (numberOfRolls - 1) % 100 + 1 } override fun toString() = "$numberOfRolls" } data class StateDirac(val player1: Player, val player2: Player, val currentPlayer: Int) { fun play(dieValue: Int): StateDirac { return if (currentPlayer == 1) { StateDirac(player1.play(dieValue), player2, 2) } else { StateDirac(player1, player2.play(dieValue), 1) } } } data class ScoreDirac(val player1Won: Long, val player2Won: Long) { operator fun plus(other: ScoreDirac) = ScoreDirac(player1Won + other.player1Won, player2Won + other.player2Won) operator fun times(value: Int) = ScoreDirac(value * player1Won, value * player2Won) companion object { val ZERO = ScoreDirac(0L, 0L) } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
3,076
advent-of-code
Apache License 2.0
src/day22/Code.kt
fcolasuonno
225,219,560
false
null
package day22 import isDebug import java.io.File import java.math.BigInteger fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } interface Shuffle { fun shuffle(cards: List<Int>): List<Int> fun apply(offsetIncrement: Pair<BigInteger, BigInteger>, deckSize: BigInteger): Pair<BigInteger, BigInteger> } object Reverse : Shuffle { override fun shuffle(cards: List<Int>) = cards.reversed() override fun apply( offsetIncrement: Pair<BigInteger, BigInteger>, deckSize: BigInteger ): Pair<BigInteger, BigInteger> { val (offset, increment) = offsetIncrement val newIncrement = (increment * (-1).toBigInteger()).mod(deckSize) val newOffset = (offset + newIncrement).mod(deckSize) return newOffset to newIncrement } } data class Cut(val n: Int) : Shuffle { override fun shuffle(cards: List<Int>) = cards.slice(cards.indices.let { it.drop((cards.size + n) % cards.size) + it.take((cards.size + n) % cards.size) }) override fun apply( offsetIncrement: Pair<BigInteger, BigInteger>, deckSize: BigInteger ): Pair<BigInteger, BigInteger> { val (offset, increment) = offsetIncrement val newOffset = (offset + (increment * n.toBigInteger())).mod(deckSize) return newOffset to increment } } data class Increment(val n: Int) : Shuffle { override fun shuffle(cards: List<Int>): List<Int> { val l = cards.indices.toMutableList() cards.indices.forEachIndexed { index, i -> l[(index * n) % cards.size] = i } return cards.slice(l) } override fun apply( offsetIncrement: Pair<BigInteger, BigInteger>, deckSize: BigInteger ): Pair<BigInteger, BigInteger> { val (offset, increment) = offsetIncrement val newIncrement = (increment * n.toBigInteger().modInverse(deckSize)).mod(deckSize) return offset to newIncrement } } private val lineStructure1 = """deal into new stack""".toRegex() private val lineStructure2 = """cut (-?\d+)""".toRegex() private val lineStructure3 = """deal with increment (\d+)""".toRegex() fun parse(input: List<String>) = input.map { lineStructure1.matchEntire(it)?.let { Reverse } ?: lineStructure2.matchEntire(it)?.destructured?.let { Cut(it.component1().toInt()) } ?: lineStructure3.matchEntire(it)?.destructured?.let { Increment(it.component1().toInt()) } }.requireNoNulls() fun part1(input: List<Shuffle>, cards: List<Int> = (0..10006).toList()) = input.fold(cards) { c, op -> op.shuffle(c) }.indexOf(2019) fun part2(input: List<Shuffle>): BigInteger { //CHEATED THIS PART.. would never have found it val deckSize = 119315717514047L.toBigInteger() val iterations = 101741582076661L.toBigInteger() val (offset, increment) = input.fold(BigInteger.ZERO to BigInteger.ONE) { c, op -> op.apply(c, deckSize) } val finalIncrement = increment.modPow(iterations, deckSize) val finalOffset = (offset * (BigInteger.ONE - increment.modPow(iterations, deckSize)) * (BigInteger.ONE - increment).modInverse( deckSize )).mod(deckSize) return (finalOffset + (finalIncrement * 2020.toBigInteger())).mod(deckSize) }
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
3,490
AOC2019
MIT License
src/main/kotlin/aoc2018/day3/FabricClaimCalculator.kt
arnab
75,525,311
false
null
package aoc2018.day3 data class Square(val x: Int, val y: Int) data class Claim( val id: Int, val left: Int, val top: Int, val width: Int, val height: Int, val topLeftSquare: Square = Square(left, top), val bottomRightSquare: Square = Square(left + width - 1, top + height - 1) ) { fun includesSquare(square: Square): Boolean { return topLeftSquare.x <= square.x && topLeftSquare.y <= square.y && bottomRightSquare.x >= square.x && bottomRightSquare.y >= square.y } } object FabricClaimCalculator { fun findConflictingSquares(claims: List<Claim>): List<Square> { val maxX = claims.maxBy { it.bottomRightSquare.x }!!.bottomRightSquare.x val maxY = claims.maxBy { it.bottomRightSquare.y }!!.bottomRightSquare.y val conflictingSquares = mutableListOf<Square>() for (x in 0..maxX) { for (y in 0..maxY) { val square = Square(x,y) val claimsIncludingSquare = claims.filter { it.includesSquare(square) } if (claimsIncludingSquare.size > 1) { conflictingSquares.add(square) } } } return conflictingSquares.distinct() } fun findNonConflictingClaims(claims: List<Claim>): List<Claim> { val maxX = claims.maxBy { it.bottomRightSquare.x }!!.bottomRightSquare.x val maxY = claims.maxBy { it.bottomRightSquare.y }!!.bottomRightSquare.y val conflictingClaims = mutableListOf<Claim>() for (x in 0..maxX) { for (y in 0..maxY) { val square = Square(x,y) val claimsIncludingSquare = claims.filter { it.includesSquare(square) } if (claimsIncludingSquare.size > 1) { conflictingClaims.addAll(claimsIncludingSquare) } } } return claims - conflictingClaims.distinct() } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
1,978
adventofcode
MIT License
src/main/adventofcode/Day07Solver.kt
eduardofandrade
317,942,586
false
null
package adventofcode import java.io.InputStream class Day07Solver(stream: InputStream) : Solver { private val bags: HashMap<String, Bag> = hashMapOf() init { processInput(stream) } private fun processInput(stream: InputStream) { val bagRuleRegex = " bags| bag[s]? | bag[s]?\\.|\\.\$| bag".toRegex() val containsRuleRegex = "([0-9]*) ([a-zA-Z]* [a-zA-Z]*)".toRegex() stream.bufferedReader().readLines().stream() .forEach { line -> val ruleLines = line.replace(bagRuleRegex, "").split(" contain |, ".toPattern()) var b = Bag(ruleLines[0], 1) for (i in 1 until ruleLines.size) { containsRuleRegex.find(ruleLines[i])?.groupValues?.let { val bagQuantity = it[1].toInt() val bagName = it[2] b.contains.put(bagName, Bag(bagName, bagQuantity)) } } bags[b.name] = b } } override fun getPartOneSolution(): Long { return bags.values.stream().filter { bag -> bag.containsShinyGoldBag(bags) }.count() } override fun getPartTwoSolution(): Long { return bags["shiny gold"]!!.getNumberOfContainedBags(bags).toLong() } private class Bag(val name: String, val quantity: Int) { val contains = hashMapOf<String, Bag>() fun containsShinyGoldBag(bags: HashMap<String, Bag>): Boolean { return contains.values.stream().anyMatch { bag -> (bag.quantity > 0 && bag.name == "shiny gold") || bags[bag.name]!!.containsShinyGoldBag(bags) } } fun getNumberOfContainedBags(bags: HashMap<String, Bag>): Int { return contains.values.map { bag -> bag.quantity + (bag.quantity * bags[bag.name]!!.getNumberOfContainedBags(bags)) }.sum() } } }
0
Kotlin
0
0
147553654412ae1da4b803328e9fc13700280c17
1,991
adventofcode2020
MIT License
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day11/Day11.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2021.day11 import nl.sanderp.aoc.common.* import java.util.* fun main() { val input = readResource("Day11.txt").lines().map { line -> line.map { it.asDigit() } } val (answer1, duration1) = measureDuration<Int> { partOne(input) } println("Part one: $answer1 (took ${duration1.prettyPrint()})") val (answer2, duration2) = measureDuration<Int> { partTwo(input) } println("Part two: $answer2 (took ${duration2.prettyPrint()})") } private fun partOne(grid: List<List<Int>>): Int { val state = grid.map { it.toTypedArray() }.toTypedArray() return (1..100).fold(0) { x, _ -> x + step(state) } } private fun partTwo(grid: List<List<Int>>): Int { val state = grid.map { it.toTypedArray() }.toTypedArray() var flashes = 0 var i = 0 while (flashes < 100) { flashes = step(state) i += 1 } return i } private fun step(state: Array<Array<Int>>): Int { val willFlash = LinkedList<Point2D>() val flashed = mutableSetOf<Point2D>() for (y in 0..9) { for (x in 0 ..9) { state[y][x] += 1 if (state[y][x] > 9) { willFlash.add(x to y) } } } while (willFlash.isNotEmpty()) { val point = willFlash.poll() if (flashed.add(point)) { for (p in point.pointsAround().filter { (0..9).contains(it.x) && (0..9).contains(it.y) }) { state[p.y][p.x] += 1 if (state[p.y][p.x] > 9) { willFlash.add(p) } } } } for (point in flashed) { state[point.y][point.x] = 0 } return flashed.size }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
1,686
advent-of-code
MIT License
StreamCiphers/src/main/kotlin/utils/BBSAnalyzer.kt
damcyb
427,749,560
false
{"Kotlin": 73312, "HTML": 39484, "JavaScript": 21008, "CSS": 15120, "PowerShell": 8834, "Python": 3780, "PureBasic": 3134, "Shell": 2894, "Java": 2266, "Assembly": 253}
package utils import java.math.BigDecimal class BBSAnalyzer { fun countOnes(bbs: String): Int = bbs.count { c: Char -> c == '1'} fun countSeries(bbs: String, character: Char): Map<Int, Int> { val occurrencesMap: MutableMap<Int, Int> = initializeOccurrencesMap() var lastFoundChar: Char = 'x' var counter: Int = 0 var position: Int = 0 bbs.forEach { char: Char -> if ((char == lastFoundChar) and (position != bbs.length - 1)) { counter++ } else if ((char == lastFoundChar) and (position == bbs.length - 1)) { val flattenCounter = flatCounter(++counter) if (lastFoundChar == character) { incrementOccurrencesMap(occurrencesMap, flattenCounter) } counter = 0 } else if ((char != lastFoundChar) and (position == bbs.length - 1)) { val flattenCounter = flatCounter(counter) if (lastFoundChar == character) { incrementOccurrencesMap(occurrencesMap, flattenCounter) } counter = 1 if (char == character) { incrementOccurrencesMap(occurrencesMap, counter) } } else { val flattenCounter = flatCounter(counter) if ((position != 0) and (lastFoundChar == character)) { incrementOccurrencesMap(occurrencesMap, flattenCounter) } lastFoundChar = char counter = 1 } position++ } return occurrencesMap } fun checkIfLongSeriesExists(bbs: String): Boolean { var counter: Int = 0 var lastFoundChar: Char = 'x' bbs.forEach { char -> Char counter = if (lastFoundChar == char) counter++ else 0 } return counter >= 26 } fun pokerize(bbs: String): Map<String, Int> { val partitions: List<String> = divideStringIntoPartitions(bbs) return groupPartitions(partitions) } fun calculatePokerScore(partitions: Map<String, Int>): BigDecimal { val fraction = BigDecimal(16).divide(BigDecimal(5000)) return partitions.values .sumOf { Math.pow(it.toDouble(), 2.0) }.toBigDecimal() .multiply(fraction) .minus(BigDecimal(5000)) } private fun divideStringIntoPartitions(input: String): List<String> = input.chunked(4) private fun groupPartitions(partitions: List<String>): Map<String, Int> = partitions .groupBy { it } .mapValues { it.value.size } private fun flatCounter(counter: Int): Int = if (counter < 6) counter else 6 private fun incrementOccurrencesMap(occurrencesMap: MutableMap<Int, Int>, counter: Int) { occurrencesMap.merge(counter, 1, Int::plus) } private fun initializeOccurrencesMap() = mutableMapOf( 1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 0, 6 to 0 ) }
0
Kotlin
0
0
1dd03a20e69e1b3f73b03b9e286c9978e1f122a1
3,074
BasicsOfCryptography
MIT License
src/Day05.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
fun main() { fun part1(crates: List<ArrayDeque<String>>, input: String): String { "(\\d+)".toRegex().findAll(input.split("\n\n")[1]).chunked(3).forEach { val amount = it[0].value.toInt() val from = it[1].value.toInt() - 1 val to = it[2].value.toInt() - 1 (1..amount).forEach { _ -> val crate = crates[from].removeFirst() crates[to].addFirst(crate) } } return crates.joinToString(separator = "") { it.first() } } fun part2(crates: List<ArrayDeque<String>>, input: String): String { "(\\d+)".toRegex().findAll(input.split("\n\n")[1]).chunked(3).forEach { it -> val amount = it[0].value.toInt() val from = it[1].value.toInt() - 1 val to = it[2].value.toInt() - 1 (1..amount) .map { val crate = crates[from].removeFirst() crate } .reversed() .forEach { crates[to].addFirst(it) } } return crates.joinToString(separator = "") { it.first() } } val crates = listOf(ArrayDeque(listOf("N", "W", "B")), ArrayDeque(listOf("B", "M", "D", "T", "P", "S", "Z", "L")), ArrayDeque(listOf("R", "W", "Z", "H", "Q")), ArrayDeque(listOf("R", "Z", "J", "V", "D", "W")), ArrayDeque(listOf("B", "M", "H", "S")), ArrayDeque(listOf("B", "P", "V", "H", "J", "N", "G", "L")), ArrayDeque(listOf("S", "L", "D", "H", "F", "Z", "Q", "J")), ArrayDeque(listOf("B", "Q", "G", "J", "F", "S", "W")), ArrayDeque(listOf("J", "D", "C", "S", "M", "W", "Z"))) val input = readText("Day05") // println(part1(crates, input)) println(part2(crates, input)) }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
1,883
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/adventofcode/y2021/Day09.kt
Tasaio
433,879,637
false
{"Kotlin": 117806}
import adventofcode.GridNode fun main() { val testInput = """ 2199943210 3987894921 9856789892 8767896789 9899965678 """.trimIndent() val test = Day09(testInput) println("TEST: " + test.part1()) println("TEST: " + test.part2()) val day = Day09() val t1 = System.currentTimeMillis() println("${day.part1()} (${System.currentTimeMillis() - t1}ms)") day.reset() val t2 = System.currentTimeMillis() println("${day.part2()} (${System.currentTimeMillis() - t2}ms)") } open class Day09(staticInput: String? = null) : Y2021Day(9, staticInput) { private val grid = fetchInputAsGrid() override fun reset() { super.reset() } override fun part1(): Number? { return grid.filter { it.content < it.getNeighbors().minOf { it.content } }.sumOf { it.contentAsNum() + 1 } } override fun part2(): Number? { val lowPoints = grid.filter { node -> node.contentAsNum() < node.getNeighbors().minOf { it.contentAsNum() } } return lowPoints.map { val seen = hashSetOf<GridNode>() val nodes = hashSetOf<GridNode>(it) var found = false do { found = false nodes .filter { node -> !seen.contains(node) } .forEach { node -> seen.add(node) node.getNeighbors() .filter { it.content.digitToInt() != 9 } .filter { it.content.digitToInt() > node.content.digitToInt() } .forEach { if (nodes.add(it)) { found = true } } } } while (found) nodes.size }.sortedByDescending { it }.take(3).reduce { a, b -> a * b } } }
0
Kotlin
0
0
cc72684e862a782fad78b8ef0d1929b21300ced8
1,984
adventofcode2021
The Unlicense
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day11.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.applyIf import nl.jstege.adventofcode.aoccommon.utils.extensions.head import nl.jstege.adventofcode.aoccommon.utils.extensions.min import kotlin.math.min class Day11 : Day(title = "Chronal Charge") { companion object Configuration { private const val GRID_WIDTH = 300 private const val GRID_HEIGHT = 300 private const val FIRST_SQUARE_SIZE = 3 } override fun first(input: Sequence<String>): Any = input.head.toInt().let { serialNumber -> solve(serialNumber, FIRST_SQUARE_SIZE, FIRST_SQUARE_SIZE) .let { (x, y, size) -> "${x - size + 1},${y - size + 1}" } } override fun second(input: Sequence<String>): Any = input.head.toInt().let { serialNumber -> solve(serialNumber, 1, min(GRID_WIDTH, GRID_HEIGHT)) .let { (x, y, size) -> "${x - size + 1},${y - size + 1},$size" } } private fun solve( serialNumber: Int, minSquareSize: Int, maxSquareSize: Int ): Triple<Int, Int, Int> { val grid = IntArray((GRID_HEIGHT + 1) * (GRID_WIDTH + 1)) var max = Triple(0, 0, Int.MIN_VALUE) var maxValue = Int.MIN_VALUE for (y in 1..GRID_HEIGHT) { for (x in 1..GRID_WIDTH) { grid[x, y] = powerInCell(serialNumber, x, y) + grid[x, y - 1] + grid[x - 1, y] - grid[x - 1, y - 1] for (size in minSquareSize..min(maxSquareSize, x, y)) { grid.getSumOfSquare(x, y, size) .applyIf({ this > maxValue }) { maxValue = this max = Triple(x, y, size) } } } } return max } private fun powerInCell(serialNumber: Int, x: Int, y: Int): Int = (x + 10).let { rackId -> (rackId * y + serialNumber) * rackId / 100 % 10 - 5 } private fun toIndex(x: Int, y: Int) = y * (GRID_WIDTH + 1) + x private fun IntArray.getSumOfSquare(x: Int, y: Int, size: Int): Int = this[x, y] - this[x, y - size] - this[x - size, y] + this[x - size, y - size] private operator fun IntArray.get(x: Int, y: Int): Int = this[toIndex(x, y)] private operator fun IntArray.set(x: Int, y: Int, value: Int) { this[toIndex(x, y)] = value } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,483
AdventOfCode
MIT License
src/main/kotlin/io/nozemi/aoc/solutions/year2021/day11/DumboOctopus.kt
Nozemi
433,882,587
false
{"Kotlin": 92614, "Shell": 421}
package io.nozemi.aoc.solutions.year2021.day11 import io.nozemi.aoc.puzzle.Puzzle import kotlin.reflect.KFunction0 fun main() { DumboOctopus( """ 5665114554 4882665427 6185582113 7762852744 7255621841 8842753123 8225372176 7212865827 7758751157 1828544563 """.trimIndent() ).printAnswers() } class DumboOctopus(val input: String) : Puzzle<List<List<Octopus>>>(input) { override fun Sequence<String>.parse(): List<List<Octopus>> = map { row -> row.toCharArray().map { octopus -> Octopus(octopus.digitToInt(), 0, false) }.toList() }.toList() override fun solutions(): List<KFunction0<Any>> = listOf( ::part1, ::part2 ) private fun part1(): Int { return simulateFlashes(input = parsedInput, steps = 100, visualize = false) } private fun part2(): Int { parsedInput = input.lineSequence().parse() return simulateFlashes(input = parsedInput, steps = -1, visualize = false, findFirstGlobalFlash = true) } private fun simulateFlashes( steps: Int = 2, input: List<List<Octopus>> = parsedInput, visualize: Boolean = false, findFirstGlobalFlash: Boolean = false ): Int { if (visualize) { println("Before any steps:") parsedInput.visualizeInConsole() println() } repeat(if (findFirstGlobalFlash) Int.MAX_VALUE else steps) { index -> input.forEach { it.forEach { octopus -> octopus.flashed = false } } input.flatten().forEach { it.energy++ } if (input.flatten().any { it.energy > 9 }) { for (y in input.indices) { for (x in 0 until input[y].size) { input.flash(Coordinate(x, y)) } } } for (y in input.indices) { for (x in 0 until input[y].size) { if (input[y][x].flashed) input[y][x].energy = 0 } } if (input.flatten().all { it.energy == 0 }) return index + 1 if (visualize) { println("After step ${index + 1}:") parsedInput.visualizeInConsole() println() } } return input.flatten().sumOf { it.flashes } } private fun List<List<Octopus>>.flash(coordinate: Coordinate) { // This octopus has already flashed this step, or is less than 10. if (this.getCoordinate(coordinate).flashed || this.getCoordinate(coordinate).energy <= 9) return // Change the values accordingly. this.getCoordinate(coordinate).flashes++ this.getCoordinate(coordinate).flashed = true // Process adjacent octopuses. this.getAdjacent(coordinate).forEach { if (++this[it.y][it.x].energy > 9) this.flash(it) } } private fun List<List<Octopus>>.getAdjacent( coordinate: Coordinate, includeDiagonal: Boolean = true ): List<Coordinate> { return getAdjacent(coordinate.x, coordinate.y, includeDiagonal) } /** * Returns all possible adjacent cell coordinates. */ private fun List<List<Octopus>>.getAdjacent(x: Int, y: Int, includeDiagonal: Boolean = true): List<Coordinate> { val adjacent = mutableListOf<Coordinate>() // Let's check if we're on the top row, if not, add cell above. if (y > 0) adjacent.add(Coordinate(x, y - 1)) // Let's check if we're on the bottom row, if not, add cell below. if (y < this.size - 1) adjacent.add(Coordinate(x, y + 1)) // Let's check if we're on the leftmost column, if not, add cell to the left. if (x > 0) adjacent.add(Coordinate(x - 1, y)) // Let's check if we're on the rightmost column, if not, add cell to the right. if (x < this[y].size - 1) adjacent.add(Coordinate(x + 1, y)) if (!includeDiagonal) return adjacent // Let's check if we're in the top left cell, if not, add cell top & left. if (y > 0 && x > 0) adjacent.add(Coordinate(x - 1, y - 1)) // Let's check if we're in the top right cell, if not, add cell top & right. if (y > 0 && x < this[y].size - 1) adjacent.add(Coordinate(x + 1, y - 1)) // Let's check if we're in the bottom left corner, if not, add cell below & left. if (y < this.size - 1 && x > 0) adjacent.add(Coordinate(x - 1, y + 1)) // Let's check if we're in the bottom right corner, if not, add cell below & right if (y < this.size - 1 && x < this[y].size - 1) adjacent.add(Coordinate(x + 1, y + 1)) return adjacent } private fun List<List<Octopus>>.getCoordinate(coordinate: Coordinate): Octopus { return this[coordinate.y][coordinate.x] } private fun List<List<Octopus>>.visualizeInConsole() { for (y in 0 until this.size) { for (x in 0 until this[y].size) { print("${this[y][x].energy} ") } println() } } } data class Coordinate(val x: Int, val y: Int) data class Octopus(var energy: Int, var flashes: Int = 0, var flashed: Boolean = false)
0
Kotlin
0
0
fc7994829e4329e9a726154ffc19e5c0135f5442
5,339
advent-of-code
MIT License
src/main/kotlin/io/dmitrijs/aoc2022/Day02.kt
lakiboy
578,268,213
false
{"Kotlin": 76651}
package io.dmitrijs.aoc2022 class Day02(private val input: List<String>) { fun puzzle1() = input.map(::createGame).sumOf { it.myScore } fun puzzle2() = input.map(::createPrediction).sumOf { it.game.myScore } private fun createGame(moves: String) = Shape.of(moves[0]) to Shape.of(moves[2]) private fun createPrediction(moves: String) = Shape.of(moves[0]) to Outcome.of(moves[2]) private enum class Outcome(val points: Int) { WIN(6), DRAW(3), LOSS(0); companion object { fun of(char: Char) = when (char) { 'X' -> LOSS 'Y' -> DRAW 'Z' -> WIN else -> error("Unsupported character.") } } } private enum class Shape(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun of(char: Char) = when (char) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> error("Unsupported character.") } } } private val Pair<Shape, Shape>.myScore get() = second.points + outcome.points private val Pair<Shape, Shape>.outcome get() = when (this) { Shape.ROCK to Shape.ROCK, Shape.PAPER to Shape.PAPER, Shape.SCISSORS to Shape.SCISSORS -> Outcome.DRAW Shape.ROCK to Shape.SCISSORS, Shape.PAPER to Shape.ROCK, Shape.SCISSORS to Shape.PAPER -> Outcome.LOSS else -> Outcome.WIN } private val Pair<Shape, Outcome>.game get() = when (this) { Shape.ROCK to Outcome.WIN, Shape.PAPER to Outcome.DRAW, Shape.SCISSORS to Outcome.LOSS -> first to Shape.PAPER Shape.PAPER to Outcome.LOSS, Shape.ROCK to Outcome.DRAW, Shape.SCISSORS to Outcome.WIN -> first to Shape.ROCK else -> first to Shape.SCISSORS } }
0
Kotlin
0
1
bfce0f4cb924834d44b3aae14686d1c834621456
2,016
advent-of-code-2022-kotlin
Apache License 2.0
src/algorithmsinanutshell/spatialtree/QuadTree.kt
realpacific
234,499,820
false
null
package algorithmsinanutshell.spatialtree import algorithmsinanutshell.Point /** * https://algs4.cs.princeton.edu/92search/QuadTree.java.html * * https://www.youtube.com/watch?v=jxbDYxm-pXg * * https://www.youtube.com/watch?v=xFcQaig5Z2A */ class QuadTree { /** * QuadNode consists of a value and 4 quadrants. * * | sw | se | nw | ne | */ inner class QuadNode( val value: Int, val point: Point ) { var sw: QuadNode? = null var se: QuadNode? = null var nw: QuadNode? = null var ne: QuadNode? = null val x: Int get() = point.x val y: Int get() = point.y override fun toString(): String { return "QuadNode($value, sw=$sw, se=$se, nw=$nw, ne=$ne)" } } private var root: QuadNode? = null fun insert(x: Int, y: Int, value: Int) { val newNode = QuadNode(value, point = Point(x, y)) root = insert(root, newNode) } private fun insert(parent: QuadNode?, node: QuadNode): QuadNode { if (parent == null) { return node } else if (node.x < parent.x && node.y < parent.y) { parent.sw = insert(parent.sw, node) } else if (node.x < parent.x && node.y > parent.y) { parent.nw = insert(parent.nw, node) } else if (node.x > parent.x && node.y < parent.y) { parent.se = insert(parent.se, node) } else if (node.x > parent.x && node.y > parent.y) { parent.ne = insert(parent.ne, node) } return parent } override fun toString(): String { return "QuadTree($root)" } /** * Given a rectangle with ([xmin], [ymin]) and ([xmax], [ymax]), find the points inside it. */ fun rangeQuery(xmin: Int, ymin: Int, xmax: Int, ymax: Int): List<QuadNode> { val result = mutableListOf<QuadNode>() rangeQuery(root!!, xmin, ymin, xmax, ymax, result) return result } private fun rangeQuery(root: QuadNode?, xmin: Int, ymin: Int, xmax: Int, ymax: Int, result: MutableList<QuadNode>) { if (root == null) { return } if (root.x in xmin..xmax && root.y in ymin..ymax) { result.add(root) } if (root.x > xmin && root.y > ymin) { rangeQuery(root.sw, xmin, ymin, xmax, ymax, result) } if (root.x > xmin && root.y < ymax) { rangeQuery(root.nw, xmin, ymin, xmax, ymax, result) } if (root.x < xmax && root.y > ymin) { rangeQuery(root.se, xmin, ymin, xmax, ymax, result) } if (root.x < xmax && root.y < ymax) { rangeQuery(root.ne, xmin, ymin, xmax, ymax, result) } } } fun main() { val tree = QuadTree() tree.insert(10, 10, 1010) tree.insert(11, 11, 1111) tree.insert(5, 5, 55) tree.insert(3, 3, 33) tree.insert(2, 2, 22) tree.insert(4, 4, 43) println(tree) tree.rangeQuery(1, 1, 6, 6).forEach { println(it) } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,061
algorithms
MIT License
src/test/kotlin/Day20.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import kotlin.math.sqrt /* --- Day 20: Jurassic Jigsaw --- See https://adventofcode.com/2020/day/20 */ fun findSolutionTiles(tiles: List<Tile>): List<List<Tile>> { val expectedSizeOfSolution = sqrt(tiles.size.toFloat()).toInt() val tileConnections = tiles.findConnections() val cornerCandidates = tileConnections.filter { it.isTopLeftCorner() } // Corners don't need to be turned because the whole solution would just be turned println("cornerCandidates.size=${cornerCandidates.size}") for (cornerCandidate in cornerCandidates) { println("cornerCandidate=$cornerCandidate") val topRow = tiles.completeEasternNeighbor(cornerCandidate.tile) println("topRow=${topRow.map { it.id }}") if (topRow.size != expectedSizeOfSolution) continue println("topRow=$topRow") val solution = tiles.completeSouthernNeighbors(topRow) if (solution.size == expectedSizeOfSolution && solution.first().size == expectedSizeOfSolution) return solution } throw java.lang.IllegalArgumentException("No solution found") } fun List<List<Tile>>.toIds() = this.map { row -> row.map { it.id } } fun List<List<Tile>>.calculateCornerProduct(): Long { val idArray = this.toIds() val topLeft = idArray.first().first() val topRight = idArray.first().last() val bottomLeft = idArray.last().first() val bottomRight = idArray.last().last() return topLeft.toLong() * topRight.toLong() * bottomLeft.toLong() * bottomRight.toLong() } fun List<Tile>.completeSouthernNeighbors(startRow: List<Tile>): List<List<Tile>> { // This does not check if the tiles match from east to west which they should according to the description // Interestingly the solution is nevertheless found, matching from north to south seems to be unique var remainingTiles = this return sequence { yield(startRow) remainingTiles = remainingTiles.removeByIds(startRow.map { it.id }) var currentTileRow = startRow while(remainingTiles.isNotEmpty()) { val next = remainingTiles.searchSouthernNeighbors(currentTileRow) if (next.isEmpty()) break yield(next) currentTileRow = next remainingTiles = remainingTiles.removeByIds(next.map { it.id }) } }.toList() } fun List<Tile>.searchSouthernNeighbor(tile: Tile): Tile? { val connectedToSouth = searchConnected(tile, this) { tileArray: TileArray, other: TileArray -> tileArray.southBorder() == other.northBorder() }.firstOrNull() connectedToSouth ?: return null val connectedTile = this.find { it.id == connectedToSouth.second }!! return Tile(connectedTile.id, connectedTile.array.variation(connectedToSouth.first)) } fun List<Tile>.searchSouthernNeighbors(startRow: List<Tile>): List<Tile> { var result = emptyList<Tile>() for(tile in startRow) { val next = this.removeByIds((startRow + result).map { it.id }).searchSouthernNeighbor(tile) if (next != null) result = result + next } return result } fun List<Tile>.completeEasternNeighbor(start: Tile): List<Tile> { var remainingTiles = this return sequence { yield(start) remainingTiles = remainingTiles.removeById(start.id) var currentTile = start while(remainingTiles.isNotEmpty()) { val nextCandidates = remainingTiles.searchEasternNeighborCandidates(currentTile) println("eastern neighbors for ${currentTile.id}=${nextCandidates.map { it.id }}") val next = nextCandidates.firstOrNull() ?: break yield(next) currentTile = next remainingTiles = remainingTiles.removeById(next.id) } }.toList() } fun List<Tile>.searchEasternNeighbor(tile: Tile): Tile? { val connectedToEast = searchConnected(tile, this) { tileArray: TileArray, other: TileArray -> tileArray.eastBorder() == other.westBorder() }.firstOrNull() connectedToEast ?: return null val connectedTile = this.find { it.id == connectedToEast.second }!! return Tile(connectedTile.id, connectedTile.array.variation(connectedToEast.first)) } fun List<Tile>.searchEasternNeighborCandidates(tile: Tile): List<Tile> { val connectedToEast = searchConnected(tile, this) { tileArray: TileArray, other: TileArray -> tileArray.eastBorder() == other.westBorder() } return connectedToEast.map { tileVariation -> val connectedTile = this.find { it.id == tileVariation.second }!! Tile(connectedTile.id, connectedTile.array.variation(tileVariation.first)) } } fun searchConnected(tile: Tile, inTiles: List<Tile>, check: (TileArray, TileArray) -> Boolean) = inTiles.flatMap { otherTile -> if (otherTile.id == tile.id) emptyList() else { val variations = otherTile.inAllVariations() variations.mapNotNull { variation -> if (check(tile.array, variation.second)) variation.first to otherTile.id else null } } } fun List<Tile>.findConnections(): List<TileConnection> { return map { tile -> val north = searchConnected(tile, this) { it: TileArray, other: TileArray -> it.northBorder() == other.southBorder() } val east = searchConnected(tile, this) { tileArray: TileArray, other: TileArray -> tileArray.eastBorder() == other.westBorder() } val south = searchConnected(tile, this) { tileArray: TileArray, other: TileArray -> tileArray.southBorder() == other.northBorder() } val west = searchConnected(tile, this) { tileArray: TileArray, other: TileArray -> tileArray.westBorder() == other.eastBorder() } TileConnection(tile, north, east, south, west) } } fun List<Tile>.removeById(id: Int) = filter { it.id != id } fun List<Tile>.removeByIds(ids: List<Int>) = filter { it.id !in ids } data class TileConnection(val tile: Tile, val north: List<Pair<TileVariation, Int>>, val east: List<Pair<TileVariation, Int>>, val south: List<Pair<TileVariation, Int>>, val west: List<Pair<TileVariation, Int>>, ) { fun isTopLeftCorner() = north.isEmpty() && east.size == 1 && south.size == 1 && west.isEmpty() } fun parseTiles(tilesString: String): List<Tile> = tilesString.split("\n\b*\n".toRegex()) .filter { it.isNotBlank() } .map { tileString -> val tileStrings = tileString.split("\n") val headline = tileStrings.first() val id = parseTileHeadline(headline) val tileArray = tileStrings.drop(1).filter { it.isNotBlank() }.map { it.trim().toList() } Tile(id, tileArray) } fun parseTileHeadline(headline: String): Int { val regex = """\w+ (\d+):""".toRegex() val match = regex.find(headline) ?: throw IllegalArgumentException("Can not parse input=$headline") if (match.groupValues.size != 2) throw IllegalArgumentException("Wrong number of elements parsed") return match.groupValues[1].toInt() } data class Tile(val id: Int, val array: TileArray) typealias TileArray = List<List<Char>> fun TileArray.northBorder(): List<Char> = first() fun TileArray.eastBorder(): List<Char> = map { it.last()} fun TileArray.southBorder(): List<Char> = last() fun TileArray.westBorder(): List<Char> = map { it.first()} fun Tile.inAllVariations() = allVariations.map { it to this.array.variation(it) } fun TileArray.variation(variation: TileVariation) = when(variation.flip) { is Original -> this is FlipX -> flipX() is FlipY -> flipY() }.run { var h = this repeat(variation.turnRight.n) { h = h.turnRight() } h } val allVariations = listOf(Original, FlipX, FlipY).flatMap { flip -> (0..3).map { turnN -> TileVariation(flip, TurnRight(turnN)) } } sealed class TileFlip object Original : TileFlip() object FlipX : TileFlip() object FlipY : TileFlip() data class TurnRight(val n: Int) data class TileVariation(val flip: TileFlip, val turnRight: TurnRight) fun TileArray.flipX() = reversed() fun TileArray.flipY() = map { it.reversed() } fun parseTileArray(tileString: String): TileArray = tileString.split("\n").filter { it.isNotBlank() }.map { it.toList() } fun TileArray.countNonMonsters(): Int = map { row -> row.count { it == '#'} }.sum() fun TileArray.findMonstersInAnyVariation(monster: TileArray): TileArray = allVariations.map { this.variation(it) }.map { tileArrayVariation -> tileArrayVariation.findMonsters(monster) }.first { tileArrayWithMarkedMonsters -> tileArrayWithMarkedMonsters.any { row -> row.any { it == 'O'} } } fun TileArray.findMonsters(monster: TileArray): TileArray { fun findMonsterAt(x: Int, y: Int, monster: TileArray): Boolean { for (monsterY in monster.indices) for (monsterX in monster.first().indices) { val monsterC = monster[monsterY][monsterX] if (monsterC == '#' && this.getOrNull(y + monsterY)?.getOrNull(x + monsterX) != '#') return false // found mismatch } return true } fun markMonsterAt(mutableTile: MutableList<MutableList<Char>>, x: Int, y: Int, monster: TileArray) { for (monsterY in monster.indices) for (monsterX in monster.first().indices) { val monsterC = monster[monsterY][monsterX] if (monsterC == '#') { val setX = x + monsterX val setY = y + monsterY if (setY in mutableTile.indices && setX in mutableTile.first().indices) mutableTile[setY][setX] = 'O' } } } val mutableTile = this.map { row -> row.toMutableList() }.toMutableList() for (y in mutableTile.indices) for (x in mutableTile.first().indices) { val monsterFound = findMonsterAt(x, y, monster) if (monsterFound) markMonsterAt(mutableTile, x, y, monster) } return mutableTile } fun combineTiles(tiles: List<List<Tile>>): TileArray = tiles.flatMap { rowOfTile -> val firstTile = rowOfTile.first() firstTile.array.indices.map { y -> val charRow = rowOfTile.indices.map { tileIndex -> rowOfTile[tileIndex].array[y] } val combinedLine = charRow.reduce { acc, tile -> acc + tile } combinedLine } } fun List<List<Tile>>.removeGaps() = map { rowOfTiles -> rowOfTiles.map { tile -> val droppedArray = tile.array.drop(1).dropLast(1).map { row -> row.drop(1).dropLast(1) } Tile(tile.id, droppedArray) } } val exampleTilesString = """ Tile 2311: ..##.#..#. ##..#..... #...##..#. ####.#...# ##.##.###. ##...#.### .#.#.#..## ..#....#.. ###...#.#. ..###..### Tile 1951: #.##...##. #.####...# .....#..## #...###### .##.#....# .###.##### ###.##.##. .###....#. ..#.#..#.# #...##.#.. Tile 1171: ####...##. #..##.#..# ##.#..#.#. .###.####. ..###.#### .##....##. .#...####. #.##.####. ####..#... .....##... Tile 1427: ###.##.#.. .#..#.##.. .#.##.#..# #.#.#.##.# ....#...## ...##..##. ...#.##### .#.####.#. ..#..###.# ..##.#..#. Tile 1489: ##.#.#.... ..##...#.. .##..##... ..#...#... #####...#. #..#.#.#.# ...#.#.#.. ##.#...##. ..##.##.## ###.##.#.. Tile 2473: #....####. #..#.##... #.##..#... ######.#.# .#...#.#.# .######### .###.#..#. ########.# ##...##.#. ..###.#.#. Tile 2971: ..#.#....# #...###... #.#.###... ##.##..#.. .#####..## .#..####.# #..#.#..#. ..####.### ..#.#.###. ...#.#.#.# Tile 2729: ...#.#.#.# ####.#.... ..#.#..... ....#..#.# .##..##.#. .#.####... ####.#.#.. ##.####... ##..#.##.. #.##...##. Tile 3079: #.#.#####. .#..###### ..#....... ######.... ####.#..#. .#...#.##. #.#####.## ..#.###... ..#....... ..#.###... """.trimIndent() val exampleTiles = parseTiles(exampleTilesString) class Day20_Part1 : FunSpec({ context("tile operations") { context("flip x") { val tile = parseTileArray(""" .# .. """.trimIndent()) tile.flipX() shouldBe parseTileArray(""" .. .# """.trimIndent()) } context("flip y") { val tile = parseTileArray(""" .# .. """.trimIndent()) tile.flipY() shouldBe parseTileArray(""" #. .. """.trimIndent()) } context("turn right") { val tile = parseTileArray(""" ## .. """.trimIndent()) tile.turnRight() shouldBe parseTileArray(""" .# .# """.trimIndent()) } context("all variations") { val tileArray = parseTileArray(""" .## ... ... """.trimIndent()) val allVariants = Tile(1, tileArray).inAllVariations() allVariants shouldBe setOf( TileVariation(Original, TurnRight(0)) to parseTileArray(""" .## ... ... """.trimIndent()), TileVariation(Original, TurnRight(1)) to parseTileArray(""" ... ..# ..# """.trimIndent()), TileVariation(Original, TurnRight(2)) to parseTileArray(""" ... ... ##. """.trimIndent()), TileVariation(Original, TurnRight(3)) to parseTileArray(""" #.. #.. ... """.trimIndent()), TileVariation(FlipX, TurnRight(0)) to parseTileArray(""" ... ... .## """.trimIndent()), TileVariation(FlipX, TurnRight(1)) to parseTileArray(""" ... #.. #.. """.trimIndent()), TileVariation(FlipX, TurnRight(2)) to parseTileArray(""" ##. ... ... """.trimIndent()), TileVariation(FlipX, TurnRight(3)) to parseTileArray(""" ..# ..# ... """.trimIndent()), TileVariation(FlipY, TurnRight(0)) to parseTileArray(""" ##. ... ... """.trimIndent()), TileVariation(FlipY, TurnRight(1)) to parseTileArray(""" ..# ..# ... """.trimIndent()), TileVariation(FlipY, TurnRight(2)) to parseTileArray(""" ... ... .## """.trimIndent()), TileVariation(FlipY, TurnRight(3)) to parseTileArray(""" ... #.. #.. """.trimIndent()), ) } } context("parse tiles") { test("should have parsed tiles") { exampleTiles.size shouldBe 9 exampleTiles[7].id shouldBe 2729 exampleTiles[8].array.toPrintableString() shouldBe """ #.#.#####. .#..###### ..#....... ######.... ####.#..#. .#...#.##. #.#####.## ..#.###... ..#....... ..#.###... """.trimIndent() } } context("find borders") { val tile = exampleTiles[8] val northBorder = tile.array.northBorder() test("north border") { northBorder.joinToString("") shouldBe "#.#.#####." } val southBorder = tile.array.southBorder() test("south border") { southBorder.joinToString("") shouldBe "..#.###..." } val eastBorder = tile.array.eastBorder() test("east border") { eastBorder.joinToString("") shouldBe ".#....#..." } val westBorder = tile.array.westBorder() test("west border") { westBorder.joinToString("") shouldBe "#..##.#..." } } context("connect tiles") { val tileConnections = exampleTiles.findConnections() val corner = tileConnections.first { it.isTopLeftCorner() } test("should have found corner") { corner.tile.id shouldBe 2971 } context("eastern neighbors") { val easternNeighbor = (exampleTiles - corner.tile).searchEasternNeighbor(corner.tile) test("should find eastern neighbor of corner") { easternNeighbor?.id shouldBe 1489 } val completedRow = exampleTiles.completeEasternNeighbor(corner.tile) test("should find all eastern neighbor of corner") { completedRow.map { it.id } shouldBe listOf(2971, 1489, 1171) } } context("southern neighbor") { val southernNeighbor = exampleTiles.searchSouthernNeighbor(corner.tile) test("should find southern neighbor of corner") { southernNeighbor?.id shouldBe 2729 } } context("southern neighbors") { val southernNeighbors = exampleTiles.searchSouthernNeighbors(exampleTiles.completeEasternNeighbor(corner.tile)) test("should find southern neighbors of start line") { southernNeighbors.map { it.id } shouldBe listOf(2729, 1427, 2473) } } context("complete southern neighbors") { val solutionTiles = exampleTiles.completeSouthernNeighbors(exampleTiles.completeEasternNeighbor(corner.tile)) test("should find all southern neighbors of start line") { solutionTiles.map { row -> row.map { it.id } } shouldBe listOf( listOf(2971, 1489, 1171), listOf(2729, 1427, 2473), listOf(1951, 2311, 3079), ) } } context("all steps to find the solution") { val solutionTiles = findSolutionTiles(exampleTiles) test("should find all southern neighbors of start line") { solutionTiles.map { row -> row.map { it.id } } shouldBe listOf( listOf(2971, 1489, 1171), listOf(2729, 1427, 2473), listOf(1951, 2311, 3079), ) } val solution = solutionTiles.calculateCornerProduct() test("should calculate solution") { solution shouldBe 20899048083289L } } } }) class Day20_Part1_Exercise: FunSpec({ val input = readResource("day20Input.txt")!! val tiles = parseTiles(input) test("should have read 144 tiles") { tiles.size shouldBe 144 } val solutionTiles = findSolutionTiles(tiles) println(solutionTiles.toIds()) val solution = solutionTiles.calculateCornerProduct() test("should have found solution") { solution shouldBe 23386616781851L } }) val monster = parseTileArray(""" # # ## ## ### # # # # # # """.trimIndent()) class Day20_Part2: FunSpec({ context("search sea monsters") { context("remove gaps") { val solutionTiles = findSolutionTiles(exampleTiles) val tilesWithoutGaps = solutionTiles.removeGaps() test("gaps should be removed") { tilesWithoutGaps[0][0].array.toPrintableString() shouldBe """ ...###.. .#.###.. #.##..#. #####..# #..####. ..#.#..# .####.## .#.#.### """.trimIndent() } context("combine tiles") { val image = combineTiles(tilesWithoutGaps) test("should combined image") { // Flip needed because example has image flipped compared to my solution image.flipX().toPrintableString() shouldBe """ .#.#..#.##...#.##..##### ###....#.#....#..#...... ##.##.###.#.#..######... ###.#####...#.#####.#..# ##.#....#.##.####...#.## ...########.#....#####.# ....#..#...##..#.#.###.. .####...#..#.....#...... #..#.##..#..###.#.##.... #.####..#.####.#.#.###.. ###.#.#...#.######.#..## #.####....##..########.# ##..##.#...#...#.#.#.#.. ...#..#..#.#.##..###.### .#.#....#.##.#...###.##. ###.#...#..#.##.######.. .#.#.###.##.##.#..#.##.. .####.###.#...###.#..#.# ..#.#..#..#.#.#.####.### #..####...#.#.#.###.###. #####..#####...###....## #.##..#..#...#..####...# .#.###..##..##..####.##. ...###...##...#...#..### """.trimIndent() } context("find monster") { val withMarkedMonsters = image.findMonstersInAnyVariation(monster) test("monsters should be marked") { withMarkedMonsters.toPrintableString() shouldBe """ .####...#####..#...###.. #####..#..#.#.####..#.#. .#.#...#.###...#.##.O#.. #.O.##.OO#.#.OO.##.OOO## ..#O.#O#.O##O..O.#O##.## ...#.#..##.##...#..#..## #.##.#..#.#..#..##.#.#.. .###.##.....#...###.#... #.####.#.#....##.#..#.#. ##...#..#....#..#...#### ..#.##...###..#.#####..# ....#.##.#.#####....#... ..##.##.###.....#.##..#. #...#...###..####....##. .#.##...#.##.#.#.###...# #.###.#..####...##..#... #.###...#.##...#.##O###. .O##.#OO.###OO##..OOO##. ..O#.O..O..O.#O##O##.### #.#..##.########..#..##. #.#####..#.#...##..#.... #....##..#.#########..## #...#.....#..##...###.## #..###....##.#...##.##.# """.trimIndent() } test("should count non monsters") { val solution = withMarkedMonsters.countNonMonsters() solution shouldBe 273 } } } } } }) class Day20_Part2_Exercise: FunSpec({ val input = readResource("day20Input.txt")!! val tiles = parseTiles(input) val solutionTiles = findSolutionTiles(tiles) val tilesWithoutGaps = solutionTiles.removeGaps() val image = combineTiles(tilesWithoutGaps) println(image.toPrintableString()) val withMarkedMonsters = image.findMonstersInAnyVariation(monster) println(withMarkedMonsters.toPrintableString()) val solution = withMarkedMonsters.countNonMonsters() test("should have found the correct number on non monsters") { solution shouldBe 2376 } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
24,969
advent_of_code_2020
Apache License 2.0
src/day01/Day01.kt
skempy
572,602,725
false
{"Kotlin": 13581}
package day01 import readInputAsString fun main() { data class Elf(val calories: List<Int>) fun part1(input: String): Int { val elves = input.split("\n\n").map { group -> Elf(group.split("\n").map { it.toInt() }) } return elves.maxOf { it.calories.sum() } } fun part2(input: String): Int { val elves = input.split("\n\n").map { group -> Elf(group.split("\n").map { it.toInt() }) } return elves.map { it.calories.sum() }.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInputAsString("Day01", "_test") println("Test Part1: ${part1(testInput)}") println("Test Part2: ${part2(testInput)}") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputAsString("Day01") println("Actual Part1: ${part1(input)}") println("Actual Part2: ${part2(input)}") }
0
Kotlin
0
0
9b6997b976ea007735898083fdae7d48e0453d7f
947
AdventOfCode2022
Apache License 2.0
day-22/src/main/kotlin/ReactorReboot.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
import kotlin.math.max import kotlin.math.min import kotlin.system.measureTimeMillis fun main() { val partOneMillis = measureTimeMillis { println("Part One Solution: ${partOne()}") } println("Part One Solved in: $partOneMillis ms") val partTwoMillis = measureTimeMillis { println("Part Two Solution: ${partTwo()}") } println("Part Two Solved in: $partTwoMillis ms") } private fun partOne(): Int { val instructions = readInstructions() val on = mutableSetOf<Triple<Int, Int, Int>>() val validRange = -50..50 for (i in instructions) { for (x in i.xRange) { if (x !in validRange) { continue } for (y in i.yRange) { if (y !in validRange) { continue } for (z in i.zRange) { if (z !in validRange) { continue } val cuboid = Triple(x, y, z) if (i.switch == "on") on.add(cuboid) else on.remove(cuboid) } } } } return on.size } private fun partTwo(): Long { val instructions = readInstructions() val on = mutableSetOf<Triple<IntRange, IntRange, IntRange>>() for (i in instructions) { if (i.switch == "on") { on.add(Triple(i.xRange, i.yRange, i.zRange)) } else { handleOffWithOnCollision(on, i.toTriple()) } } val wraps = findWraps(on) on.removeAll(wraps) correctOnCollisions(on) return on.sumOf { it.first.count().toLong() * it.second.count() * it.third.count() } } fun findWraps(on: MutableSet<Triple<IntRange, IntRange, IntRange>>): Set<Triple<IntRange, IntRange, IntRange>> { val wraps = mutableSetOf<Triple<IntRange, IntRange, IntRange>>() for (i in on) { for (j in on) { if (i == j) continue if (i.wraps(j)) { wraps.add(j) } else if (j.wraps(i)) { wraps.add(i) } } } return wraps } fun correctOnCollisions(on: MutableSet<Triple<IntRange, IntRange, IntRange>>) { val alreadyCorrected = mutableSetOf<Triple<IntRange, IntRange, IntRange>>() out@ while (true) { for (i in on.iterator()) { if (i in alreadyCorrected) { continue } for (j in on.iterator()) { if (i == j) continue if (i.collidesWith(j)) { handleOnWithOnCollision(i, j, on) continue@out } } alreadyCorrected.add(i) } break@out } } fun handleOnWithOnCollision( i: Triple<IntRange, IntRange, IntRange>, j: Triple<IntRange, IntRange, IntRange>, on: MutableSet<Triple<IntRange, IntRange, IntRange>> ) { if (i.wraps(j)) { on.remove(j) return } if (j.wraps(i)) { on.remove(i) return } on.remove(i) on.remove(j) mergeOnWithOn(i, j)?.let { on.add(it) return } val xRanges = getNonCollidingRanges(i.first, j.first) val yRanges = getNonCollidingRanges(i.second, j.second) val zRanges = getNonCollidingRanges(i.third, j.third) addRangeCombinations( on, xRanges.filter { it.inRange(i.first) && it.count() > 0 }, yRanges.filter { it.inRange(i.second) && it.count() > 0 }, zRanges.filter { it.inRange(i.third) && it.count() > 0 }, ) addRangeCombinations( on, xRanges.filter { it.inRange(j.first) && it.count() > 0 }, yRanges.filter { it.inRange(j.second) && it.count() > 0 }, zRanges.filter { it.inRange(j.third) && it.count() > 0 }, ) } private fun getNonCollidingRanges(i: IntRange, j: IntRange): Set<IntRange> { val common = i.intersect(j).toSortedSet() if (common.isEmpty()) return emptySet() val commonRange = common.first()..common.last() val minFirst = min(i.first, j.first) val maxLast = max(i.last, j.last) val firstRange = minFirst until common.first() val lastRange = common.last() + 1..maxLast return setOf(commonRange, firstRange, lastRange) } private fun mergeOnWithOn( i: Triple<IntRange, IntRange, IntRange>, j: Triple<IntRange, IntRange, IntRange>, ): Triple<IntRange, IntRange, IntRange>? { return if (i.first == j.first && i.second == j.second) { i.copy(third = min(i.third.first, j.third.first)..max(i.third.last, j.third.last)) } else if (i.first == j.first && i.third == j.third) { i.copy(second = min(i.second.first, j.second.first)..max(i.second.last, j.second.last)) } else if (i.second == j.second && i.third == j.third) { i.copy(first = min(i.first.first, j.first.first)..max(i.first.last, j.first.last)) } else { null } } fun addRangeCombinations( on: MutableSet<Triple<IntRange, IntRange, IntRange>>, xRanges: List<IntRange>, yRanges: List<IntRange>, zRanges: List<IntRange>, ) { for (x in xRanges) { for (y in yRanges) { for (z in zRanges) { on.add(Triple(x, y, z)) } } } } private fun handleOffWithOnCollision( on: MutableSet<Triple<IntRange, IntRange, IntRange>>, i: Triple<IntRange, IntRange, IntRange>, ) { val onCopy = on.toSet() for (triple in onCopy) { if (i.collidesWith(triple)) { on.remove(triple) if (i.wraps(triple)) { continue } val xRanges = getNonCollidingRanges(i.first, triple.first) val yRanges = getNonCollidingRanges(i.second, triple.second) val zRanges = getNonCollidingRanges(i.third, triple.third) addRangeCombinationsOff( on, xRanges.filter { it.count() > 0 && triple.first.wraps(it) }, yRanges.filter { it.count() > 0 && triple.second.wraps(it) }, zRanges.filter { it.count() > 0 && triple.third.wraps(it) }, i, ) } } } fun addRangeCombinationsOff( on: MutableSet<Triple<IntRange, IntRange, IntRange>>, xRanges: List<IntRange>, yRanges: List<IntRange>, zRanges: List<IntRange>, offTriple: Triple<IntRange, IntRange, IntRange>, ) { for (x in xRanges) { for (y in yRanges) { for (z in zRanges) { if (x.inRange(offTriple.first) && y.inRange(offTriple.second) && z.inRange(offTriple.third)) continue on.add(Triple(x, y, z)) } } } } fun IntRange.inRange(other: IntRange) = this.first in other || this.last in other || other.first in this || other.last in this fun IntRange.wraps(other: IntRange) = this.first <= other.first && this.last >= other.last fun Triple<IntRange, IntRange, IntRange>.wraps(other: Triple<IntRange, IntRange, IntRange>): Boolean { return this.first.wraps(other.first) && this.second.wraps(other.second) && this.third.wraps(other.third) } fun Triple<IntRange, IntRange, IntRange>.collidesWith(other: Triple<IntRange, IntRange, IntRange>): Boolean { return this.first.inRange(other.first) && this.second.inRange(other.second) && this.third.inRange(other.third) } fun readInstructions(): List<Instruction> { val regex = Regex("([a-z]+)\\sx=(-?[0-9]+)\\.\\.(-?[0-9]+),y=(-?[0-9]+)\\.\\.(-?[0-9]+),z=(-?[0-9]+)\\.\\.(-?[0-9]+)") return readInputLines().map { val result = regex.matchEntire(it)!! val switch = result.groups[1]!!.value val xFrom = result.groups[2]!!.value.toInt() val xTo = result.groups[3]!!.value.toInt() val yFrom = result.groups[4]!!.value.toInt() val yTo = result.groups[5]!!.value.toInt() val zFrom = result.groups[6]!!.value.toInt() val zTo = result.groups[7]!!.value.toInt() Instruction(switch, xFrom..xTo, yFrom..yTo, zFrom..zTo) } } data class Instruction( val switch: String, val xRange: IntRange, val yRange: IntRange, val zRange: IntRange, ) { fun toTriple() = Triple(xRange, yRange, zRange) } private fun readInputLines(): List<String> { return {}::class.java.classLoader.getResource("input.txt")!! .readText() .split("\n") .filter { it.isNotBlank() } }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
8,398
aoc-2021
MIT License
workshops/moscow_prefinals2020/day3/k.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package workshops.moscow_prefinals2020.day3 fun main() { val (x, y, z) = List(3) { readInts().drop(1).reversed() } var (low, high) = maxOf((x + y + z).maxOrNull()!!, 1).toLong() to Long.MAX_VALUE / 2 binarySearch@while (low + 1 < high) { val b = (low + high) / 2 val zNew = LongArray(z.size) var tooLarge = false fun add(index: Int, value: Long) { if (index >= zNew.size) tooLarge = true else zNew[index] += value } for (i in x.indices) for (j in y.indices) { add(i + j, x[i].toLong() * y[j]) for (k in i + j until zNew.size) { if (zNew[k] < b) break add(k + 1, zNew[k] / b) zNew[k] %= b } if (tooLarge) { low = b continue@binarySearch } } for (k in zNew.indices.reversed()) { if (zNew[k] == z[k].toLong()) continue if (zNew[k] > z[k]) low = b else high = b continue@binarySearch } return println(b) } println("impossible") } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,042
competitions
The Unlicense
src/Day03.kt
ChrisCrisis
575,611,028
false
{"Kotlin": 31591}
import java.lang.IllegalStateException fun main() { fun processInput(data: List<String>): List<Char> { return data.map{ bucket -> val firstHalf = bucket.substring(0 until bucket.length/2) val secondHalf = bucket.substring(bucket.length/2 until bucket.length ) firstHalf.forEach { if(secondHalf.contains(it)){ return@map it } } throw IllegalStateException("No match found") } } fun List<String>.processInputChunked(): List<Char> { return this.chunked(3) {group -> val minion1 = group[1] val minion2 = group[2] group.first().forEach { if(minion1.contains(it) && minion2.contains(it)){ return@chunked it } } throw IllegalStateException("No match found") } } fun Char.getScore(): Int { return when{ this.isLowerCase() -> this.code - 96 this.isUpperCase() -> this.code - 64 + 26 else -> throw IllegalStateException() } } fun part1(data: List<String>): Int { return processInput(data).sumOf { it.getScore() } } fun part2(data: List<String>): Int { return data.processInputChunked().sumOf { it.getScore() } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
1
Kotlin
0
0
732b29551d987f246e12b0fa7b26692666bf0e24
1,575
aoc2022-kotlin
Apache License 2.0
src/Day03.kt
ty-garside
573,030,387
false
{"Kotlin": 75779}
// Day 03 - Rucksack Reorganization // https://adventofcode.com/2022/day/3 fun main() { fun compartments(line: String): Pair<String, String> { val mid = line.length / 2 return line.substring(0, mid) to line.substring(mid, line.length) } fun priority(char: Char) = when { char.isLowerCase() -> char - 'a' + 1 char.isUpperCase() -> char - 'A' + 27 else -> error("Invalid: $char") } fun part1(input: List<String>): Int { return input.asSequence() .map { compartments(it) } .map { it.first.toSet().intersect(it.second.toSet()) } .flatMap { it.map { char -> priority(char) } } .sum() } fun part2(input: List<String>): Int { return input.asSequence() .chunked(3) { it[0].toSet() .intersect(it[1].toSet()) .intersect(it[2].toSet()) } .flatMap { it.map { char -> priority(char) } } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) } /* --- Day 3: Rucksack Reorganization --- One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged. Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack. The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items). The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment. For example, suppose you have the following list of contents from six rucksacks: vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p. The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L. The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P. The fourth rucksack's compartments only share item type v. The fifth rucksack's compartments only share item type t. The sixth rucksack's compartments only share item type s. To help prioritize item rearrangement, every item type can be converted to a priority: Lowercase item types a through z have priorities 1 through 26. Uppercase item types A through Z have priorities 27 through 52. In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157. Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types? Your puzzle answer was 7742. --- Part Two --- As you finish identifying the misplaced items, the Elves come to you with another issue. For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group. For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves. That is, if a group's badge is item type B, then all three Elves will have item type B somewhere in their rucksack, and at most two of the Elves will be carrying any other item type. The problem is that someone forgot to put this year's updated authenticity sticker on the badges. All of the badges need to be pulled out of the rucksacks so the new authenticity stickers can be attached. Additionally, nobody wrote down which item type corresponds to each group's badges. The only way to tell which item type is the right one is by finding the one item type that is common between all three Elves in each group. Every set of three lines in your list corresponds to a single group, but each group can have a different badge item type. So, in the above example, the first group's rucksacks are the first three lines: vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg And the second group's rucksacks are the next three lines: wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw In the first group, the only item type that appears in all three rucksacks is lowercase r; this must be their badges. In the second group, their badge item type must be Z. Priorities for these items must still be found to organize the sticker attachment efforts: here, they are 18 (r) for the first group and 52 (Z) for the second group. The sum of these is 70. Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of those item types? Your puzzle answer was 2276. Both parts of this puzzle are complete! They provide two gold stars: ** */
0
Kotlin
0
0
49ea6e3ad385b592867676766dafc48625568867
5,904
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/g1501_1600/s1559_detect_cycles_in_2d_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1501_1600.s1559_detect_cycles_in_2d_grid // #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find // #2023_06_13_Time_871_ms_(33.33%)_Space_103.6_MB_(33.33%) class Solution { fun containsCycle(grid: Array<CharArray>): Boolean { val n = grid.size val m = grid[0].size val visited = Array(n + 1) { BooleanArray(m + 1) } for (i in 0 until n) { for (j in 0 until m) { if (!visited[i][j] && cycle(grid, i, j, visited, grid[i][j])) { return true } } } return false } private fun cycle(grid: Array<CharArray>, i: Int, j: Int, visited: Array<BooleanArray>, cc: Char): Boolean { if (i < 0 || j < 0 || i >= grid.size || j >= grid[0].size || grid[i][j] != cc) { return false } if (visited[i][j]) { return true } visited[i][j] = true val temp = grid[i][j] grid[i][j] = '*' val ans = ( cycle(grid, i + 1, j, visited, cc) || cycle(grid, i - 1, j, visited, cc) || cycle(grid, i, j + 1, visited, cc) || cycle(grid, i, j - 1, visited, cc) ) grid[i][j] = temp return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,308
LeetCode-in-Kotlin
MIT License
app/src/main/java/com/alpriest/energystats/ui/statsgraph/SelfSufficiencyCalculator.kt
alpriest
606,081,400
false
{"Kotlin": 742930}
package com.alpriest.energystats.ui.statsgraph import com.alpriest.energystats.models.rounded import com.alpriest.energystats.ui.CalculationBreakdown import com.alpriest.energystats.ui.flow.roundedToString import kotlin.math.pow import kotlin.math.roundToInt class AbsoluteSelfSufficiencyCalculator { fun calculate(grid: Double, feedIn: Double, loads: Double, batteryCharge: Double, batteryDischarge: Double): Pair<Double, CalculationBreakdown> { val netGeneration = feedIn - grid + batteryDischarge - batteryCharge val homeConsumption = loads val formula = """netGeneration = feedIn - grid + batteryCharge - batteryDischarge If netGeneration > 0 then result = 1 Else if netGeneration + homeConsumption < 0 then result = 0 Else if netGeneration + homeConsumption > 0 then result = (netGeneration + homeConsumption) / homeConsumption """ val calculation: (Int) -> String = { """netGeneration = $feedIn - $grid + $batteryCharge - $batteryDischarge If ${netGeneration.roundedToString(it)} > 0 then result = 1 Else if ${netGeneration.roundedToString(it)} + ${homeConsumption.roundedToString(it)} < 0 then result = 0 Else if ${netGeneration.roundedToString(it)} + ${homeConsumption.roundedToString(it)} > 0 then result = (${netGeneration.roundedToString(it)} + ${homeConsumption.roundedToString(it)}) / ${ homeConsumption.roundedToString( it ) } """ } var result = 0.0 if (netGeneration > 0) { result = 1.0 } else if (netGeneration + homeConsumption < 0) { result = 0.0 } else if (netGeneration + homeConsumption > 0) { result = (netGeneration + homeConsumption) / homeConsumption } return Pair( (result * 100.0).roundTo(1), CalculationBreakdown(formula, calculation) ) } } class NetSelfSufficiencyCalculator { fun calculate(loads: Double, grid: Double): Pair<Double, CalculationBreakdown> { val formula = "1 - (min(loads, max(grid, 0.0)) / loads)" if (loads <= 0) { return Pair(0.0, CalculationBreakdown(formula, { "" })) } val result = 1 - (minOf(loads, maxOf(grid, 0.0)) / loads) return Pair( (result * 100.0).roundTo(1), CalculationBreakdown(formula, { "1 - (min(${loads.roundedToString(it)}, max(${grid.roundedToString(it)}, 0.0)) / ${loads.roundedToString(it)})" }) ) } } fun Double.roundTo(decimalPlaces: Int): Double { val factor = 10.0.pow(decimalPlaces.toDouble()) return (this * factor).roundToInt() / factor }
6
Kotlin
3
3
6de8f2a01a047aa1fe79d8888673141612e37a3b
2,667
EnergyStats-Android
MIT License
src/main/kotlin/Day13.kt
i-redbyte
433,743,675
false
{"Kotlin": 49932}
data class Dot(val x: Int, val y: Int) fun main() { val data = readInputFile("day13") var dots = makeData(data) fun makeDots(s: String, value: Int) { dots = if (s.first() == 'x') { dots.map { p -> if (p.x > value) { Dot(2 * value - p.x, p.y) } else p }.toSet() } else { dots.map { p -> if (p.y > value) { Dot(p.x, 2 * value - p.y) } else p }.toSet() } } fun getInputData(s: String) { val foldAlong = "fold along " check(s.startsWith(foldAlong)) val dotString = s.substring(foldAlong.length) makeDots(dotString, dotString.substringAfter('=').toInt()) } fun part1(): Int { val i = data.indexOf("") + 1 getInputData(data[i]) return dots.size } fun part2(): Int { for (i in data.indexOf("") + 1 until data.size) { getInputData(data[i]) } val charTable = Array(6) { CharArray(40) { ' ' } } for (dot in dots) { charTable[dot.y][dot.x] = '$' } for (ch in charTable) { println(ch.concatToString()) } println() /** Solution part 2: $ $$$ $$ $$$ $$$ $$$$ $$ $$$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $$$ $ $$$ $ $$$ $ $$ $$$ $$$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $$$$ $ $ $$$ $ $ $ $$$$ $$ $$$ */ return dots.size } println("Result part1: ${part1()}") println() println("Result part2: ${part2()}") } private fun makeData(data: List<String>) = data.takeWhile { it.isNotEmpty() }.map { line -> line.split(",").map { it.toInt() }.let { (x, y) -> Dot(x, y) } }.toSet()
0
Kotlin
0
0
6d4f19df3b7cb1906052b80a4058fa394a12740f
1,899
AOC2021
Apache License 2.0
src/main/kotlin/com/sk/topicWise/dp/medium/1043. Partition Array for Maximum Sum.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.dp.medium class Solution1043 { fun maxSumAfterPartitioning(arr: IntArray, k: Int): Int { val dp = IntArray(arr.size) { -1 } fun maxFromCurrentPart(s: Int, e: Int): Int { val start = maxOf(0, s) val end = e return arr.slice(start..end).max() * (end - start + 1) } fun maxAt(A: IntArray, i: Int): Int { if (i < 0) return 0 if (dp[i] != -1) return dp[i] var maxhere = 0 for (len in 1..k) { maxhere = maxOf( maxhere, maxAt(A, i - len) + maxFromCurrentPart(i - len + 1, i) ) } dp[i] = maxhere return dp[i] } return maxAt(arr, arr.lastIndex) } fun maxSumAfterPartitioning2(A: IntArray, K: Int): Int { val dp = IntArray(A.size + 1) for (i in 1..A.size) { var curMax = 0 var best = 0 var k = 1 while (k <= K && i - k >= 0) { curMax = maxOf(curMax, A[i - k]) best = maxOf(best, dp[i - k] + curMax * k) ++k } dp[i] = best } return dp[A.size] } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,254
leetcode-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ValidPathInGraph.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 java.util.LinkedList import java.util.Queue /** * 1971. Find if Path Exists in Graph * @see <a href="https://leetcode.com/problems/find-if-path-exists-in-graph">Source</a> */ fun interface ValidPathInGraph { operator fun invoke(n: Int, edges: Array<IntArray>, source: Int, destination: Int): Boolean } /** * 1. Simple union-find without any rank consideration */ class ValidPathUnionFind : ValidPathInGraph { override operator fun invoke(n: Int, edges: Array<IntArray>, source: Int, destination: Int): Boolean { val set = DisjointSetUnion(n) for (edge in edges) { set.union(edge[0], edge[1]) } return set.areConnected(source, destination) } private class DisjointSetUnion(private val n: Int, val parent: IntArray = IntArray(n)) { init { for (i in 0 until n) { parent[i] = i } } fun areConnected(u: Int, v: Int): Boolean { return find(u) == find(v) } fun union(u: Int, v: Int) { if (u != v) { val a = find(u) val b = find(v) parent[a] = b } } private fun find(u: Int): Int { var x = u while (x != parent[x]) { x = parent[x] } parent[u] = x return x } } } /** * 2. Disjoint Set Union by Rank */ class ValidPathUnionByRank : ValidPathInGraph { override operator fun invoke(n: Int, edges: Array<IntArray>, source: Int, destination: Int): Boolean { val set = DisjointSetUnion(n) for (edge in edges) { set.union(edge[0], edge[1]) } return set.areConnected(source, destination) } private class DisjointSetUnion( private val n: Int, val parent: IntArray = IntArray(n), val rank: IntArray = IntArray(n), ) { init { for (i in 0 until n) { parent[i] = i rank[i] = 1 } } fun areConnected(u: Int, v: Int): Boolean { return find(u) == find(v) } fun union(u: Int, v: Int) { if (u != v) { val a = find(u) val b = find(v) if (a != b) { if (rank[a] > rank[b]) { parent[b] = a rank[a] += rank[b] } else { parent[a] = b rank[b] += rank[a] } } } } private fun find(u: Int): Int { var x = u while (x != parent[x]) { x = parent[x] } parent[u] = x return x } } } /** * 3. DFS - Depth First Search */ class ValidPathDFS : ValidPathInGraph { private var seen = false override operator fun invoke(n: Int, edges: Array<IntArray>, source: Int, destination: Int): Boolean { val visited = BooleanArray(n) val graph: Array<HashSet<Int>> = Array(n) { HashSet() } for (edge in edges) { graph[edge[0]].add(edge[1]) graph[edge[1]].add(edge[0]) } // direct connection exists if (graph[source].contains(destination)) { return true } seen = false dfs(graph, visited, source, destination) return seen } private fun dfs(graph: Array<HashSet<Int>>, visited: BooleanArray, start: Int, end: Int) { if (!visited[start] && !seen) { if (start == end) { seen = true return } visited[start] = true for (neighbor in graph[start]) { dfs(graph, visited, neighbor, end) } } } } /** * 3. BFS - Breadth First Search */ class ValidPathBFS : ValidPathInGraph { override operator fun invoke(n: Int, edges: Array<IntArray>, source: Int, destination: Int): Boolean { val visited = BooleanArray(n) val graph: Array<HashSet<Int>> = Array(n) { java.util.HashSet() } for (edge in edges) { graph[edge[0]].add(edge[1]) graph[edge[1]].add(edge[0]) } // direct connection exists if (graph[source].contains(destination)) { return true } val queue: Queue<Int> = LinkedList() var current: Int queue.offer(source) visited[source] = true while (queue.isNotEmpty()) { current = queue.poll() if (current == destination) { return true } for (neighbor in graph[current]) { if (!visited[neighbor]) { visited[neighbor] = true queue.offer(neighbor) } } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,610
kotlab
Apache License 2.0
src/main/kotlin/com/vvv/engine/utils/Trie.kt
vicol13
530,589,547
false
{"Kotlin": 40611, "Jupyter Notebook": 36031}
package com.vvv.engine.utils import java.util.TreeMap import kotlin.RuntimeException class TrieException(msg: String) : RuntimeException(msg) /** * Class which represent trie structure for input recommendation * * Beside child node each tree has a property word, which mean * this tree is a leaf(represent a word) we keep this in order * to avoid making reference to parent node so having next case * * t * ├── to (is marked as word if is called trie.add(to)) * ├── toy * ├── top */ open class Trie { protected constructor() { } constructor(words: Set<String>) : this() { words.forEach { this.addWord(it) } } protected val map: TreeMap<String, Trie> = TreeMap<String, Trie>() protected var word: String? = null private fun isLeaf(): Boolean { return word != null } /** * should add word into tree * @param word which will be added into tree */ fun addWord(word: String) { if (word.isEmpty() || word.isBlank()) { throw TrieException("add blank or empty word to trie") } return this.addWord(word, 1) } /** * function mark node as leaf node like this * can also have child nodes with words * * which means that key/word of this node has an actual meaning * like we */ private fun addLeafNode(word: String) { this.map.putIfAbsent(word, Trie()) this.map[word]!!.word = word // this.word = word } /** * recursively get elements of a word and add them in the trie * saying that we want to add "toys" in the tree it will grow it as follows * ├── t add("toys",1) * ├── to add("toys",2) * ├── toy add("toys",3) * ├── toys add("toys",4) * * in the last call toys-node will be marked leaf */ private fun addWord(word: String, index: Int) { if (index == word.length) { // println(word) this.addLeafNode(word) return //exit recursion } val currentSubSequence = word.subSequence(0, index).toString() if (!map.containsKey(currentSubSequence)) { this.map[currentSubSequence] = Trie() } this.map[currentSubSequence]!!.addWord(word, index + 1) } open fun search(prefix: String): List<String> { if (prefix.isEmpty() || prefix.isBlank()) { throw TrieException("search input can't be empty or blank") } return search(prefix, 1) } /** * recursively parse the tree in order to find word with root @param prefix * assuming that we want to search for prefix "toy" the function chain looks * like this root.get("t").get("to").get("toy").getAllChild() */ private fun search(prefix: String, index: Int): List<String> { if (!isLeaf() && this.map.isEmpty()) { // throw TrieException("Unknown sequence [$prefix]") return emptyList() } if (index == prefix.length + 1) { return this.getWords() } val currentSubSequence = prefix.subSequence(0, index) if (map.containsKey(currentSubSequence)) { return map[currentSubSequence]!!.search(prefix, index + 1) } // throw TrieException("Unknown sequence [$prefix]") return emptyList() } /** * load all leaf nodes which are kids of this node */ fun getWords(): List<String> { val collectingList = mutableListOf<String>() if (this.isLeaf()) { collectingList.add(this.word!!) } collectFromChild(collectingList) return collectingList } private fun collectFromChild(collectingList: MutableList<String>) { this.map.values.forEach { entry -> entry.word?.also { collectingList.add(it) } if (entry.map.isNotEmpty()) { entry.collectFromChild(collectingList) } } } fun print(indent: String = " ") { println("$indent keys ${this.map.keys} word [${this.word}] \t\t level:{${indent.length}}") if (map.isEmpty()) return this.map.forEach { it.value.print("$indent ") } } }
0
Kotlin
0
1
534a40c5a4c0b02f1935ba4ea976d47cd8c43485
4,363
search-engine
MIT License
app/src/main/java/site/paulo/pathfinding/algorithm/Djikstra.kt
paulofernando
238,713,514
false
{"Kotlin": 117418}
package site.paulo.pathfinding.algorithm import site.paulo.pathfinding.data.model.graph.GraphTypes import site.paulo.pathfinding.data.model.Node import site.paulo.pathfinding.data.model.PathFindingAlgorithms import java.util.* import kotlin.collections.HashMap open class Djikstra ( var graph: LinkedList<Node>, var startNode: Node, var endNode: Node ) : PathFindingAlgorithm { /** * Shortest distance from S to V */ private val shortestPath = HashMap<String, Double>() /** * Priority queue based on shortest path with all nodes in the graph */ protected val remaining = PriorityQueue<Node>() /** * Node visited order */ private val nodeVisitedOrder = LinkedList<Node>() override fun run(graphType: GraphTypes) { prepare() if (remaining.isEmpty()) return var lowest = remaining.poll() while (lowest != null && (lowest.shortestPath != Double.POSITIVE_INFINITY)) { if (graphType == GraphTypes.GRID && (lowest == endNode)) break searchPath(lowest) lowest = remaining.poll() } } private fun searchPath(currentNode: Node?) { if (currentNode == null) return nodeVisitedOrder.add(currentNode) for (adjacentNode in currentNode.getAdjacentNodes()) { val edge = currentNode.edges[adjacentNode.name] if (edge != null && edge.connected) { val shortestPathFromAdjacent = adjacentNode.shortestPath + edge.weight if (shortestPathFromAdjacent == Double.POSITIVE_INFINITY) { setShortestPath(adjacentNode, currentNode.shortestPath + edge.weight) adjacentNode.previous = edge } else if (currentNode.shortestPath > shortestPathFromAdjacent) { setShortestPath(currentNode, shortestPathFromAdjacent) currentNode.previous = edge } } } } open fun prepare() { graph.forEach { node -> node.reset()} //make sure that the nodes has no 'previous' from older processing setShortestPath(startNode, 0.0) for (edge in startNode.edges.values) { if (edge.connected) { val opposite = edge.getOpposite(startNode) setShortestPath(opposite, edge.weight) opposite.previous = edge } } } private fun setShortestPath(node: Node, weight: Double) { node.shortestPath = weight shortestPath[node.name] = weight //updating priority queue remaining.remove(node) remaining.add(node) } /** * Retrieves the shortest from start to end */ override fun getPath(): Stack<Node> { var currentNode: Node? = endNode val stackOfNodes: Stack<Node> = Stack() //used to reverse order to print while (currentNode != null) { stackOfNodes.push(currentNode) currentNode = currentNode.previous?.getOpposite(currentNode) } if (stackOfNodes.peek() == startNode) return stackOfNodes return Stack() } override fun getVisitedOrder(): LinkedList<Node> { return nodeVisitedOrder } override fun getType(): PathFindingAlgorithms { return PathFindingAlgorithms.DJIKSTRA } /** * Prints shortest path in System.out */ fun printPath() { val path = getPath() println("Printing shortest path from ${startNode.name} to ${endNode.name}:") if (path.empty()) { println("No path found from ${startNode.name} to ${endNode.name}") return } println("Visiting: ${path.size} nodes...") print(path.pop().name) while(path.isNotEmpty()) { print(" -> ${path.pop().name}") } println() } }
0
Kotlin
0
7
ba6c2438159424fdb325191cb94d78daf404db3c
3,894
pathfinding
MIT License
src/day17/Day17.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
package day17 import containsAny import readInput enum class Direction(val symbol: Char, val vec: Point) { UP('^', Point(0, 1)), RIGHT('>', Point(1, 0)), DOWN('v', Point(0, -1)), LEFT('<', Point(-1, 0)); companion object { private val symbolMap = Direction.values().associateBy { it.symbol } fun fromSymbol(symbol: Char): Direction { return symbolMap[symbol]!! } } } /* y 5|..#.#..| 4|#####..| 3|..###..| 2|...#...| 1|..####.| 0+-------+ 012345678x */ data class Point(val x: Int, val y: Int) { operator fun plus(other: Point): Point { return Point(x + other.x, y + other.y) } } data class Figure(val points: List<Point>) { fun moved(dir: Direction): Figure { return Figure(points.map { it + dir.vec }) } fun moved(vec: Point): Figure { return Figure(points.map { it + vec }) } fun top(): Int { return points.maxOf { it.y } } fun left(): Int { return points.minOf { it.x } } fun right(): Int { return points.maxOf { it.x } } } fun spawn(figure: Figure, towerHeight: Int): Figure { return figure.moved(Point(3, towerHeight + 4)) } fun printState(tower: Tower, fallingFigure: Figure?) { val pictureHeight = fallingFigure?.top() ?: tower.height for (y in pictureHeight downTo 0) { for (x in 0..8) { val p = Point(x, y) if (fallingFigure?.points?.contains(p) == true) { print("@") } else if (x == 0 && y == 0) { print("+") } else if (x == 8 && y == 0) { print("+") } else if ((x == 0) || (x == 8)) { print("|") } else if (y == 0) { print("-") } else if (tower.points.contains(p)) { print("#") } else { print('.') } } println() } } data class Tower(val points: MutableSet<Point>, var height: Int) fun simulate( jetPattern: List<Direction>, figureSequence: List<Figure>, steps: Int, verbose: Boolean = false ): List<Int> { val tower = Tower(List(9) { Point(it, 0) }.toMutableSet(), 0) var jetCount = 0 val heightIncrease = mutableListOf<Int>() var height = 0 repeat(steps) { val figureIndex = it % figureSequence.size var figure = spawn(figureSequence[figureIndex], tower.height) while (true) { val jetDirection = jetPattern[jetCount % jetPattern.size] val jetMoved = figure.moved(jetDirection) if (jetMoved.right() <= 7 && jetMoved.left() >= 1 && !tower.points.containsAny(jetMoved.points) ) { figure = jetMoved } if (verbose) { println("jet ${jetDirection.symbol} $it") printState(tower, figure) println() } ++jetCount val movedDown = figure.moved(Direction.DOWN) if (tower.points.containsAny(movedDown.points)) { tower.points.addAll(figure.points) tower.height = figure.points.maxOf { f -> f.y }.coerceAtLeast(tower.height) break } figure = movedDown if (verbose) { println("down $it") printState(tower, figure) println() } } if (verbose) { println("finish $it") printState(tower, null) println() } val currentHeightIncrease = tower.height - height heightIncrease.add(currentHeightIncrease) height = tower.height } return heightIncrease } fun countWithCycles(totalSteps: Long, cycleInit: List<Long>, cycle: List<Long>): Long { val amountOfCycles = (totalSteps - cycleInit.size) / cycle.size val remainder = ((totalSteps - cycleInit.size) % cycle.size).toInt() return cycleInit.sum() + amountOfCycles * cycle.sum() + cycle.take(remainder).sum() } data class Cycle(val offset: Int, val length: Int) fun findCycle(data: List<Int>, maxOffset: Int, maxLength: Int): Cycle? { for (length in 5..maxLength step 5) { for (offset in 0..maxOffset) { var isGoodCycle = true for (i in offset until data.size - length) { if (data[i] != data[i + length]) { isGoodCycle = false break } } if (isGoodCycle) { return Cycle(offset, length) } } } return null } fun predictHeightFromSimulationResult(heightIncrease: List<Int>, numberOfSteps: Long): Long { val cycle = findCycle(heightIncrease, 5000, 5000) ?: throw Exception("Couldn't find cycle") val cycleInit = heightIncrease.take(cycle.offset) val cycleElements = heightIncrease.drop(cycle.offset).take(cycle.length) return countWithCycles(numberOfSteps, cycleInit.map { x -> x.toLong() }, cycleElements.map { x -> x.toLong() }) } fun main() { println("Day 17") val testInput = readInput("Day17-test")[0].map { Direction.fromSymbol(it) } val input = readInput("Day17")[0].map { Direction.fromSymbol(it) } val horizontalLine = Figure(listOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0))) val plus = Figure(listOf(Point(1, 0), Point(0, 1), Point(1, 1), Point(2, 1), Point(1, 2))) val corner = Figure(listOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, 1), Point(2, 2))) val verticalLine = Figure(listOf(Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3))) val square = Figure(listOf(Point(0, 0), Point(0, 1), Point(1, 0), Point(1, 1))) val figureSequence = listOf(horizontalLine, plus, corner, verticalLine, square) val totalSteps = 1000000000000 val testHeightIncrease = simulate(testInput, figureSequence, 10000) val realHeightIncrease = simulate(input, figureSequence, 50000) println("part 1 test ${testHeightIncrease.take(2022).sum()}") println("part 1 real: ${realHeightIncrease.take(2022).sum()}") println("part 2 test: ${predictHeightFromSimulationResult(testHeightIncrease, totalSteps)}") println("part 2 real: ${predictHeightFromSimulationResult(realHeightIncrease, totalSteps)}") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
6,365
aoc-2022
Apache License 2.0
src/Day14.kt
anilkishore
573,688,256
false
{"Kotlin": 27023}
fun main() { val grid = mutableSetOf<Pair<Int, Int>>() fun part1(input: List<String>, bottom: Boolean = false): Int { fun diff(x: Int, y: Int) = if (x == y) 0 else { if (x < y) 1 else -1 } var maxy = 0 for (s in input) { val splits = s.split(" -> ") for (i in 0 until splits.size - 1) { val a = splits[i].split(",") val b = splits[i+1].split(",") var ax = a[0].toInt() var ay = a[1].toInt() val bx = b[0].toInt() val by = b[1].toInt() maxy = maxOf(maxy, ay, by) val dx = diff(ax, bx) val dy = diff(ay, by) grid.add(Pair(ax, ay)) while(ax != bx || ay != by) { ax += dx ay += dy grid.add(Pair(ax, ay)) } } } var res = 0 val max = 200 while (true) { var x = 500 var y = 0 var steps = 0 while (steps < max) { ++steps if (!grid.contains(Pair(x, y+1))) { ++y } else if (!grid.contains(Pair(x-1, y+1))) { --x ++y } else if (!grid.contains(Pair(x+1, y+1))) { ++x ++y } else { break } if (y + 1 == maxy) break; } // if (bottom) { // println(">>>> here") // if (x == 500 && y == 0) // break; // } else if (steps == max) break; grid.add(Pair(x, y)) println("Settled at $x, $y. Steps = $steps") ++res } return res } fun part2(input: List<String>) = part1(input, true) val input = readInput("Day14") println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
2,100
AOC-2022
Apache License 2.0
algorithms/src/main/kotlin/com/kotlinground/algorithms/backtracking/restoreipaddresses/restoreIpAddresses.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.algorithms.backtracking.restoreipaddresses /** * Complexity Analysis * Let's assume we need to separate the input string into N integers, each integer is at most M digits. * * - Time complexity: O(M ^ N * N) * There are at most M ^ {N - 1} possibilities, and for each possibility checking whether all parts are valid takes * O(M⋅N) time, so the final time complexity is O(M ^ {N - 1}) * O(M*N) = O(M ^ (N) * N) * * For this question, M = 3, N = 4, so the time complexity is O(1). * * Space complexity: O(M*N). * * For each possibility, we save (N - 1) numbers (the number of digits before each dot) which takes O(N) space. * And we need temporary space to save a solution before putting it into the answer list. The length of each solution * string is M * N + M − 1 = O(M⋅N), so the total space complexity is O(M⋅N) if we don't take the output space into * consideration. * * For this question, M = 3, N = 4, so the space complexity is O(1). */ fun restoreIpAddresses(s: String): List<String> { /** * Checks whether the substring from index start to start+length is a valid number from 0-255. * The logic is to check both the conditions(caller guarantees that the length is in the range of [1,3]): * 1. If the substring's first character is 0 (s[start] is '0'), then the length must be 1 * 2. If length is 3, the substring should be no larger than '255 lexically. if the length is 1 or 2 and the first * case was not triggered, then it will be in the acceptable range */ fun valid(stringToCheck: String, start: Int, length: Int): Boolean { return length == 1 || stringToCheck[start] != '0' && (length < 3 || stringToCheck.substring( start, start + length ) <= "255") } fun helper(candidate: String, startIndex: Int, dots: ArrayList<Int>, ips: ArrayList<String>) { // string length we want to process val remainingLength = s.length - startIndex val remainingNumberOfIntegers = 4 - dots.size // how many integers we have left to form // since each integer has 1-3 digits. This catches the case where s.length > 12 since at the beginning // remainingLength is s.length and remainingNumberOfIntegers is 4 if (remainingLength > (remainingNumberOfIntegers * 3) || remainingLength < remainingNumberOfIntegers) { return } /** * If remainingNumberOfIntegers = 1, * - if the last integer s.substring(startIndex, startIndex + remainingLength) is valid * - Create an empty string to save this answer using the following steps. * - Set last to 0. * - Iterate over all elements dot in the list dots. * - Append s.substring(last, last + dot) and a '.' into the answer string. * - Increase last by dot and repeat these steps for each dot. * - Append s.substring(last, s.length). This is the final integer after the last dot. * - Add the answer string into ans. * Return. */ if (dots.size == 3) { if (valid(candidate, startIndex, remainingLength)) { val sb = StringBuilder() var last = 0 for (dot in dots) { sb.append(candidate.substring(last, last + dot)) last += dot sb.append(".") } sb.append(candidate.substring(startIndex)) ips.add(sb.toString()) } return } /** * Iterate over curPos from 1 to min(3, remainingLength). curPos is the number of digits we are including before * placing a dot. * - Place a dot by adding curPos into dots. * - If the integer s.substring(startIndex, startIndex + curPos) is valid * - Call helper(s, startIndex + curPos, dots, ans) * - Remove the dot that we placed to backtrack. */ var curPos = 1 while (curPos <= 3 && curPos <= remainingLength) { // Append a dot at the current position. dots.add(curPos) // Try making all combinations with the remaining string. if (valid(candidate, startIndex, curPos)) { helper(candidate, startIndex + curPos, dots, ips) } // Backtrack, i.e. remove the dot to try placing it at the next position. dots.remove(dots.size - 1) ++curPos } } val ipAddresses = arrayListOf<String>() val startIndex = 0 val dots = arrayListOf<Int>() helper(s, startIndex, dots, ipAddresses) return ipAddresses }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
4,796
KotlinGround
MIT License
Lapindrome.kt
sysion
353,734,921
false
null
/** * https://www.codechef.com/problems/LAPIN * * * Lapindromes Problem Code: LAPIN * * Lapindrome is defined as a string which when split in the middle, gives two halves * having the same characters and same frequency of each character. If there are odd * number of characters in the string, we ignore the middle character and check for * lapindrome. For example gaga is a lapindrome, since the two halves ga and ga have * the same characters with same frequency. Also, abccab, rotor and xyzxy are a few * examples of lapindromes. Note that abbaab is NOT a lapindrome. The two halves * contain the same characters but their frequencies do not match. * * Your task is simple. Given a string, you need to tell if it is a lapindrome. * * Input: * First line of input contains a single integer T, the number of test cases. * Each test is a single line containing a string S composed of only lowercase English * alphabet. * * Output: * For each test case, output on a separate line: "YES" if the string is a lapindrome * and "NO" if it is not. * * Constraints: * 1 ≤ T ≤ 100 * 2 ≤ |S| ≤ 1000, where |S| denotes the length of S * * * Example: * Input: * 6 * gaga * abcde * rotor * xyzxy * abbaab * ababc * * Output: * YES * NO * YES * YES * NO * NO */ fun main(){ //val inpString = "gaga" //val inpString = "abcde" //val inpString = "rotor" val inpString = "xyzxy" //val inpString = "abbaab" //val inpString = "ababc" //val inpString = "gotrej" //val inpString = "abcabcbb" //val inpString = "bbbbb" //val inpString = "pwwkew" //val inpString = "" LapindromeCheck(inpString) } fun LapindromeCheck(inputString: String): String{ var isLapindrome = "NO" var strLen = inputString.trim().length var evenOdd = if (strLen % 2 == 0) 0 else 1 if (strLen == 0) { println("Is BLANK a Lapindrome? : $isLapindrome") return isLapindrome } var charArray1 = inputString.substring(0, evenOdd+strLen/2).toCharArray() var charArray2 = inputString.substring(strLen/2, strLen).toCharArray() //println(charArray1) //println(charArray2) //println(charArray1.sorted().toString()) //println(charArray2.sorted().toString()) if (charArray1.sorted() == charArray2.sorted()) isLapindrome = "YES" //var charArray1 = inputString.toList().slice(0..evenOdd+strLen/2) //var charArray2 = inputString.toList().slice(-1+strLen/2..strLen-1) //println(charArray1) //println(charArray2) println("Is $inputString a Lapindrome? : $isLapindrome") return isLapindrome }
0
Kotlin
0
0
6f9afda7f70264456c93a69184f37156abc49c5f
2,491
DataStructureAlgorithmKt
Apache License 2.0
03/src/commonMain/kotlin/Main.kt
daphil19
725,415,769
false
{"Kotlin": 131380}
expect fun getLines(inputOrPath: String): List<String> fun main() { var lines = getLines(INPUT_FILE) // lines = ("467..114..\n" + // "...*......\n" + // "..35..633.\n" + // "......#...\n" + // "617*......\n" + // ".....+.58.\n" + // "..592.....\n" + // "......755.\n" + // "...\$.*....\n" + // ".664.598..").split("\n") part1(lines) part2(lines) } // bound by in-memory array... data class Point(val row: Int, val col: Int) { fun moveBy(row: Int = 0, col: Int = 0) = copy(row = this.row + row, col = this.col + col) fun neighbors() = listOf( copy(row = row - 1), copy(row = row + 1), copy(col = col - 1), copy(col = col + 1), copy(row = row - 1, col = col - 1), copy(row = row + 1, col = col - 1), copy(row = row - 1, col = col + 1), copy(row = row + 1, col = col + 1), ) } data class Region(val row: IntRange, val col: IntRange) { fun contains(point: Point) = row.contains(point.row) && col.contains(point.col) } fun part1(lines: List<String>) { val numbers = mutableMapOf<Region, Long>() val symbols = mutableMapOf<Point, Char>() lines.forEachIndexed {row, line -> var buildingNum = false var start = 0 var numStr = "" line.forEachIndexed { col, c -> if (c.isDigit()) { if (!buildingNum) { buildingNum = true start = col } numStr += c } else if (buildingNum) { buildingNum = false numbers[Region((row-1)..(row+1), (start-1)..(col))] = numStr.toLong() numStr = "" // numbers[] = numStr.toLong() } if (!c.isDigit() && c != '.') { symbols[Point(row, col)] = c } } // handle end of line edge case if (buildingNum) { numbers[Region((row-1)..(row+1), (start-1)..(line.length))] = numStr.toLong() } } val foundRegions = mutableSetOf<Region>() val answer = symbols.keys.flatMap { point -> // n^2 ftw numbers.keys.mapNotNull { if (!foundRegions.contains(it) && it.contains(point)) { foundRegions.add(it) numbers[it] } else null } } .sum() println(answer) } fun part2(lines: List<String>) { val numbers = mutableMapOf<Region, Long>() val symbols = mutableMapOf<Point, Char>() lines.forEachIndexed {row, line -> var buildingNum = false var start = 0 var numStr = "" line.forEachIndexed { col, c -> if (c.isDigit()) { if (!buildingNum) { buildingNum = true start = col } numStr += c } else if (buildingNum) { buildingNum = false numbers[Region((row-1)..(row+1), (start-1)..(col))] = numStr.toLong() numStr = "" // numbers[] = numStr.toLong() } if (c == '*') { symbols[Point(row, col)] = c } } // handle end of line edge case if (buildingNum) { numbers[Region((row-1)..(row+1), (start-1)..(line.length))] = numStr.toLong() } } val foundRegions = mutableSetOf<Region>() // we only want symbols that have exactly 2 adjacent numbers val answer = symbols.keys.map { point -> // n^2 ftw numbers.keys.mapNotNull { if (!foundRegions.contains(it) && it.contains(point)) { foundRegions.add(it) numbers[it] } else null } }.filter { it.size == 2 }.sumOf { it[0] * it[1] } // .sum() println(answer) }
0
Kotlin
0
0
70646b330cc1cea4828a10a6bb825212e2f0fb18
3,946
advent-of-code-2023
Apache License 2.0
src/main/kotlin/aoc2017/HexEd.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2017 import kotlin.math.absoluteValue fun hexEdDistance(input: String): Int = hexEdDistance(input.split(",").map { HexMove.valueOf(it.toUpperCase().trim()) }) fun hexEdMaxDistance(input: String): Int = hexEdMaxDistance(input.split(",").map { HexMove.valueOf(it.toUpperCase().trim()) }) fun hexEdDistance(steps: List<HexMove>): Int { val (x, y) = takeSteps(steps) return distanceTo(x, y) } fun hexEdMaxDistance(steps: List<HexMove>): Int { var max = 0 var x = 0 var y = 0 for (step in steps) { x += step.dx y += step.dy val distance = distanceTo(x, y) if (distance > max) max = distance } return max } fun distanceTo(x: Int, y: Int): Int { val xx = x.absoluteValue val yy = y.absoluteValue return if (yy < xx) xx else yy } fun takeSteps(steps: List<HexMove>): Pair<Int, Int> { var x = 0 var y = 0 for (step in steps) { x += step.dx y += step.dy } return Pair(x, y) } enum class HexMove(val dx: Int, val dy: Int) { N(0, -1), NE(1, -1), SE(1, 0), S(0, 1), SW(-1, 1), NW(-1, 0); }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,176
advent-of-code
MIT License
src/Day17.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
sealed class Block { class HorizLine : Block() { override val shape = listOf( "####".toCharArray() ) } class Cross : Block() { override val shape = listOf( ".#.".toCharArray(), "###".toCharArray(), ".#.".toCharArray() ) } class Corner : Block() { override val shape = listOf( "..#".toCharArray(), "..#".toCharArray(), "###".toCharArray() ) } class VertLine : Block() { override val shape = listOf( "#".toCharArray(), "#".toCharArray(), "#".toCharArray(), "#".toCharArray() ) } class Cube : Block() { override val shape = listOf( "##".toCharArray(), "##".toCharArray() ) } abstract val shape: List<CharArray> fun hitCheck(grid: Array<CharArray>, position: Position): Boolean { if (position.x + width >= grid[0].size || position.x == -1) return true if (position.y - height == -1) return true for (i in shape.indices) { for (j in 0 until shape[0].size) { if ((shape[shape.size - j - 1][i] == '#') && (grid[position.y - j][i + position.x] == '#')) { return true } } } return false } fun place(grid: Array<CharArray>, position: Position) { for (i in shape.indices) { for (j in 0 until shape[0].size) { if (shape[shape.size - j - 1][i] == '#') { grid[position.y - j][i + position.x] = shape[shape.size - j - 1][i] } } } } private val width: Int get() = shape[0].size val height: Int get() = shape.size } fun main() { // ktlint-disable filename fun part1(input: List<String>): Int { val moves = input[0] // grid coordinates go up, zero is at bottom dropping goes down var yOffset = 0 val height = 50 // when height reached, add to offset val grid = Array(10000) { CharArray(7) { '.' } } // start pos is 2, y + height + 3 from bottom or highest rock var moveNum = 0 var blockNum = 0 val blockTypes = listOf(Block.HorizLine(), Block.Cross(), Block.Corner(), Block.VertLine(), Block.Cube()) var block = blockTypes[blockNum] var pos = Position(2, 3 + block.height) while (true) { if (block.hitCheck(grid, pos)) { block.place(grid, pos) block = blockTypes[(++blockNum).rem(blockTypes.size)] pos = Position(2, 3 + pos.y) } } return 0 } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test") println("Test height of rocks: ${part1(testInput)}") check(part1(testInput) == 3068) // println("Test #Sand units with floor: ${part2(testInput)}") // check(part2(testInput) == 93) // val input = readInput("Day17_input") // println("Height of rocks: ${part1(input)}") // println("#Sand units with floor: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
3,322
KotlinAdventOfCode2022
Apache License 2.0
src/main/kotlin/g1901_2000/s1998_gcd_sort_of_an_array/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1998_gcd_sort_of_an_array // #Hard #Array #Math #Sorting #Union_Find #2023_06_21_Time_437_ms_(100.00%)_Space_45.4_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun gcdSort(nums: IntArray): Boolean { val sorted = nums.clone() sorted.sort() val len = nums.size val max = sorted[len - 1] // grouping tree child(index)->parent(value), index==value is root val nodes = IntArray(max + 1) for (j in nums) { nodes[j] = -1 } // value: <=0 not sieved, <0 leaf node, 0 or 1 not in nums, >1 grouped for (p in 2..max / 2) { if (nodes[p] > 0) { // sieved so not a prime number. continue } // p is now a prime number, set self as root. nodes[p] = p var group = p var num = p + p while (num <= max) { var existing = nodes[num] if (existing < 0) { // 1st hit, set group nodes[num] = group } else if (existing <= 1) { // value doesn't exist in nums nodes[num] = 1 } else if (root(nodes, existing).also { existing = it } < group) { nodes[group] = existing group = existing } else { nodes[existing] = group } num += p } } for (i in 0 until len) { if (root(nodes, nums[i]) != root(nodes, sorted[i])) { return false } } return true } companion object { private fun root(nodes: IntArray, num: Int): Int { var num = num var group: Int while (nodes[num].also { group = it } > 0 && group != num) { num = group } return num } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,990
LeetCode-in-Kotlin
MIT License
src/main/kotlin/lib/Solver.kt
jetpants
130,976,101
false
null
package judoku class Solver(private val puzzle: Grid) { init { check(puzzle.isLegal()) } fun findSolution(): Grid? { val solutions = findSolutions(1) return if (solutions.size == 0) null else solutions[0] } fun findSolutions(max: Int): ArrayList<Grid> { val solutions = ArrayList<Grid>() val n = search(puzzle, solutions, max, puzzle.numFilledCells == 0) check(n == solutions.size) { "$n <> ${solutions.size}" } return solutions } fun countSolutions() = countSolutions(Int.MAX_VALUE) fun countSolutions(max: Int) = search(puzzle, null, max, false) fun hasSolution() = countSolutions(1) == 1 fun isUnique() = countSolutions(2) == 1 // exactly one solution fun isMinimal(): Boolean { if (!puzzle.isViable()) return false; for (n in 1..puzzle.numCells) if (!puzzle.isEmpty(n) && countSolutions(puzzle.withEmpty(n), 2) < 2) return false return true } fun isProper(): Boolean { /* A so-called 'proper' puzzle has exactly one unique solution and no clue is superfluous. I.e., removing any one of the clues would result in a puzzle with more than one solution. Proper puzzles are both sufficent and minimal. */ return isUnique() && isMinimal() } var nodeCounting = false var nodeCount: Int = 0 // incremented with each node traversed companion object { @JvmStatic fun findSolution(puzzle: Grid) = Solver(puzzle).findSolution() @JvmStatic fun findSolutions(puzzle: Grid, max: Int) = Solver(puzzle).findSolutions(max) @JvmStatic fun countSolutions(puzzle: Grid, max: Int) = Solver(puzzle).countSolutions(max) @JvmStatic fun isUnique(grid: Grid) = Solver(grid).isUnique() @JvmStatic fun isMinimal(grid: Grid) = Solver(grid).isMinimal() @JvmStatic fun isProper(grid: Grid) = Solver(grid).isProper() } private data class Frame( val cache: OptionsCache, val solutions: ArrayList<Grid>?, val max: Int, // maximum solutions to find/count val randomise: Boolean, // generate solutions in random order var total: Int // number of solutions found ) private fun search(g: Grid, solutions: ArrayList<Grid>?, max: Int, randomise: Boolean): Int { if (!g.isViable() || max <= 0) return 0 val frame = Frame(OptionsCache(g), solutions, max, randomise, 0) return traverse(g, max, frame) } private fun traverse(g: Grid, remaining: Int, frame: Frame): Int { if (nodeCounting) ++nodeCount if (remaining == 0) return 0 val target = frame.cache.fewestOptions() if (target == null) { frame.solutions?.add(Grid(g)); return 1 } if (target.mask == 0) return 0 // zombie leaf node var value = 0 var mask = target.mask if (frame.randomise) { assert(frame.solutions != null) val rot = Util.random.nextInt(g.size) + 1 // +1 for bit-0 (EMPTY) value += rot mask = Integer.rotateRight(mask, rot) } var found = 0 var current = Grid.EMPTY repeat (target.popcount) { val zeroes = Integer.numberOfTrailingZeros(mask) if (zeroes > 0) { value = (value + zeroes) % Integer.SIZE mask = mask ushr zeroes } frame.cache.update(target.n, current, value); current = value g._setCell(target.n, value) found += traverse(g, remaining - found, frame) ++value; mask = mask ushr 1 } g._setCell(target.n, Grid.EMPTY) frame.cache.update(target.n, current, Grid.EMPTY) return found } } /* EXPERIMENTAL - splitting the traversal across multiple threads // new thread per sub-root val threads = Array<Thread>(target.options.size, { val child = g.withCell(target.n, target.options[it]) Thread(Runnable { traverse(child, max, frame) }) }) for (t in threads) t.start() for (t in threads) t.join() val total = minOf(frame.total.get(), max) check(solutions == null || solutions.size == total) { "${solutions!!.size} <> ${total}" } return total // re-use threads from POOL_SIZE companion object { // executor.shutdown() needs to be called to allow the program to exit private final val POOL_SIZE = 8 private val executor = Executors.newFixedThreadPool(POOL_SIZE); } val futures = Array<Future<*>>(POOL_SIZE, { executor.submit( Runnable { var i = it var child = Grid(g) var found = 0 while (i < target.options.size) { child = child.withCell(target.n, target.options[i]) found += traverse(child, max - found, frame) i += POOL_SIZE } } )}) for (f in futures) f.get() val total = minOf(frame.total.get(), max) check(solutions == null || solutions.size == total) { "${solutions!!.size} <> ${total}" } return total // multi-thread-sade traverse() private fun traverse(g: Grid, remaining: Int, frame: Frame): Int { if (remaining == 0 || frame.stop) return 0 val target = fewestOptions(g) if (target == null) { if (frame.total.incrementAndGet() == frame.max) frame.stop = true if (frame. solutions != null) synchronized(frame.solutions) { if (frame.solutions.size < frame.max) frame.solutions.add(Grid(g)) } return 1 } // optimisation - if you're only counting them, the order doesn't matter if (frame.solutions != null) target.options.shuffle() var found = 0 for (possibility in target.options) { if (frame.stop) break g.setCell(target.n, possibility) found += traverse(g, remaining - found, frame) } g.setCell(target.n, Grid.EMPTY) return found } // mostOptions() private fun mostOptions(g: Grid): Options? { var best: Options? = null for (n in 1..g.numCells) if (g.isEmpty(n)) { val opts = g.getOptions(n) when { opts.size == g.size() -> return Options(n, opts) best == null -> best = Options(n, opts) best.options.size < opts.size -> best = Options(n, opts) } } return best } */
0
Kotlin
2
3
904c05456ecf83f8707f4d3c6c5afa0a50f4b9e7
7,041
judoku
Apache License 2.0
src/main/kotlin/g1001_1100/s1072_flip_columns_for_maximum_number_of_equal_rows/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1001_1100.s1072_flip_columns_for_maximum_number_of_equal_rows // #Medium #Array #Hash_Table #Matrix #2023_05_31_Time_536_ms_(100.00%)_Space_108.4_MB_(50.00%) class Solution { fun maxEqualRowsAfterFlips(matrix: Array<IntArray>): Int { /* Idea: For a given row[i], 0<=i<m, row[j], 0<=j<m and j!=i, if either of them can have all values equal after some number of flips, then row[i]==row[j] <1> or row[i]^row[j] == 111...111 <2> (xor result is a row full of '1') Go further, in case<2> row[j] can turn to row[i] by flipping each column of row[j] IF assume row[i][0] is 0, then question is convert into: 1> flipping each column of each row if row[i][0] is not '0', 2> count the frequency of each row. The biggest number of frequencies is the answer. */ // O(M*N), int M = matrix.length, N = matrix[0].length; var answer = 0 val frequency: MutableMap<String, Int> = HashMap() for (row in matrix) { val rowStr = StringBuilder() for (c in row) { if (row[0] == 1) { rowStr.append(if (c == 1) 0 else 1) } else { rowStr.append(c) } } val key = rowStr.toString() val value = frequency.getOrDefault(key, 0) + 1 frequency[key] = value answer = answer.coerceAtLeast(value) } return answer } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,523
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/dmc/advent2022/Day07.kt
dorienmc
576,916,728
false
{"Kotlin": 86239}
package com.dmc.advent2022 import kotlin.time.ExperimentalTime import kotlin.time.measureTime // --- Day 7: No Space Left On Device --- class Day07 : Day<Int> { override val index = 7 fun parseInput(input: List<String>) : List<Directory> { val root = Directory("/") val dirs = mutableListOf(root) var currentNode: Directory = root // Determine file structure for(line in input) { when { line == "$ ls" -> {/*do nothing*/} line.startsWith("$ cd") -> { // cd - change currentNode val (_,_,arg) = line.split(" ") currentNode = goTo(currentNode, arg) } line.startsWith("dir") -> dirs.add(currentNode.addSubdir(line)) else -> currentNode.addFile(line) } } return dirs.toList() } override fun part1(input: List<String>): Int { val allDirs = parseInput(input) // val root = allDirs.first() // println(root) // Get directories of at most 100000 val boundary = 100000 allDirs.filter{ it.getSize() <= boundary }.forEach{ println("${it.name} ${it.getSize()}")} return allDirs.map{ it.getSize()}.filter{ it <= boundary }.sum() } private fun goTo(currentNode: Directory, arg: String) : Directory { return when(arg) { ".." -> currentNode.parent!! //go up "/" -> currentNode //do nothing else -> currentNode.getSubdir(arg)!! } } override fun part2(input: List<String>): Int { val requiredFreeSpace = 30000000 val totalSpace = 70000000 val allDirs = parseInput(input) val root = allDirs.first() // Get smallest directory that when deleted ensures; unusedSpace <= requiredFreeSpace val unusedSpace = totalSpace - root.getSize() val boundary = requiredFreeSpace - unusedSpace var currentSmallest = root.getSize() for(dir in allDirs) { val current = dir.getSize() if (current in boundary..currentSmallest) { currentSmallest = current } } return currentSmallest } } data class MyFile(var name: String, var fileSize: Int) { override fun toString(): String { return "- $name (file, size=$fileSize)" } } class Directory(var name: String, val parent: Directory? = null) { var children: MutableList<Directory> = mutableListOf() var files: MutableList<MyFile> = mutableListOf() fun addFile(line: String) { val (nodesize, name) = line.split(" ") addFile(MyFile(name, nodesize.toInt())) } fun addFile(file: MyFile) { files.add(file) } fun addSubdir(line: String) : Directory { val name = line.substringAfter(" ") val child = Directory(name, this) return addSubdir(child) } fun addSubdir(dir: Directory) : Directory { children.add(dir) return dir } fun getSubdir(name: String) : Directory? { return children.find { it.name == name } } fun getSize(): Int { return children.sumOf { it.getSize() } + files.sumOf { it.fileSize } } override fun toString(): String { var result = "- $name (dir)\n" result += children.joinToString("\n") { child -> child.toString().prependIndent(" ") } result += files.joinToString("\n") { child -> child.toString().prependIndent(" ") } return result } } @OptIn(ExperimentalTime::class) fun main() { val day = Day07() // test if implementation meets criteria from the description, like: val testInput = readInput(day.index, true) var dur = measureTime { check(day.part1(testInput) == 95437) } println("Took ${dur.inWholeMicroseconds}") val input = readInput(day.index) dur = measureTime { day.part1(input).println() } println("Took ${dur.inWholeMicroseconds}") day.part2(input).println() }
0
Kotlin
0
0
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
4,024
aoc-2022-kotlin
Apache License 2.0
src/Day09.kt
Totwart123
573,119,178
false
null
import kotlin.math.absoluteValue fun main() { data class MutablePair(var first: Int, var second: Int){ override fun equals(other: Any?): Boolean { if(other?.javaClass != javaClass) return false other as MutablePair return other.first == first && other.second == second } } fun printMoves(head: MutablePair, tails: List<MutablePair>){ val temp = tails.toMutableList() temp.add(head) val maxX = temp.maxOf { it.first } val maxY = temp.maxOf { it.second } val minX = temp.minOf { it.first } val minY = temp.minOf { it.second } for(i in maxY downTo minY){ var line = "" for(j in minX..maxX){ val tmp = MutablePair(j, i) val indexOf = tails.indexOf(tmp) if(head == tmp){ line += "H" } else if(indexOf != - 1){ line += "${indexOf + 1}" } else{ line += "." } } println(line) } } fun tailIsArroundHead(head: MutablePair, tail: MutablePair): Boolean{ if(head == tail) return true if(head.first == tail.first && (head.second == tail.second + 1 || head.second == tail.second - 1)) return true if(head.second == tail.second && (head.first == tail.first + 1 || head.first == tail.first - 1)) return true //Top left if(head.first - 1 == tail.first && head.second + 1 == tail.second) return true //Top right if(head.first + 1 == tail.first && head.second + 1 == tail.second) return true //bottom left if(head.first - 1 == tail.first && head.second - 1 == tail.second) return true //bottom right if(head.first + 1 == tail.first && head.second - 1 == tail.second) return true return false } fun part1(input: List<String>): Int { val tail = MutablePair(0,0) val head = MutablePair(0,0) val positions = mutableListOf(Pair(tail.first, tail.second)) input.forEach { move -> val splitted = move.split(" ") val direction = splitted[0] val count = splitted[1].toInt() for (i in 0 until count ){ when(direction){ "U" -> head.second++ "D" -> head.second-- "R" -> head.first++ "L" -> head.first-- } if(!tailIsArroundHead(head, tail)){ val xDif = (head.first - tail.first).absoluteValue val yDif = (head.second - tail.second).absoluteValue if(xDif == 0 || xDif < yDif){ if(head.second > tail.second){ tail.second = head.second - 1 } else{ tail.second = head.second + 1 } tail.first = head.first } else if(yDif == 0 || xDif > yDif){ if(head.first > tail.first){ tail.first = head.first - 1 } else{ tail.first = head.first + 1 } tail.second = head.second } val positionPair = Pair(tail.first, tail.second) if(!positions.contains(positionPair)){ positions.add(positionPair) } } } } return positions.count() } fun part2(input: List<String>): Int { val tails = (0..8).map { MutablePair(0,0) }.toMutableList() val head = MutablePair(0,0) val positions = mutableListOf(Pair(tails.last().first, tails.last().second)) input.forEach { move -> val splitted = move.split(" ") val direction = splitted[0] val count = splitted[1].toInt() for (i in 0 until count ){ when(direction){ "U" -> head.second++ "D" -> head.second-- "R" -> head.first++ "L" -> head.first-- } println("####HEAD-MOVES####") printMoves(head, tails) var tailInFront = head for(tail in tails){ if(!tailIsArroundHead(tailInFront, tail)){ val xDif = (tailInFront.first - tail.first).absoluteValue val yDif = (tailInFront.second - tail.second).absoluteValue if(xDif == 0 || xDif < yDif){ if(tailInFront.second > tail.second){ tail.second = tailInFront.second - 1 } else{ tail.second = tailInFront.second + 1 } tail.first = tailInFront.first } else if(yDif == 0 || xDif > yDif){ if(tailInFront.first > tail.first){ tail.first = tailInFront.first - 1 } else{ tail.first = tailInFront.first + 1 } tail.second = tailInFront.second } else if(xDif > 1){ if(tailInFront.second > tail.second){ tail.second = tailInFront.second - 1 } else{ tail.second = tailInFront.second + 1 } if(tailInFront.first > tail.first){ tail.first = tailInFront.first - 1 } else{ tail.first = tailInFront.first + 1 } } } tailInFront = tail printMoves(head, tails) } val positionPair = Pair(tails.last().first, tails.last().second) if(!positions.contains(positionPair)){ positions.add(positionPair) } } } return positions.count() } var testInput = readInput("Day09_test") check(part1(testInput) == 13) testInput = readInput("Day09_test2") check(part2(testInput) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
33e912156d3dd4244c0a3dc9c328c26f1455b6fb
7,007
AoC
Apache License 2.0
2022/src/main/kotlin/day3_imp.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.map import utils.mapItems import utils.split object Day3All { @JvmStatic fun main(args: Array<String>) { mapOf("func" to Day3Func, "imp" to Day3Imp, "fast" to Day3Fast).forEach { (header, solution) -> solution.run( header = header, printParseTime = false ) } } } object Day3Imp : Solution<Day3Input>() { override val name = "day3" override val parser = Parser.lines.mapItems { line -> line.split().map { it.toCharArray().toSet() } } override fun part1(input: Day3Input): Int { var sum = 0 for (rucksack in input) { sum += (rucksack.first intersect rucksack.second).first().priority + 1 } return sum } override fun part2(input: Day3Input): Number { var sum = 0 (input.indices step 3).forEach { i -> var set = input[i].first + input[i].second for (j in i + 1 until i + 3) { set = set intersect (input[j].first + input[j].second) } sum += set.first().priority + 1 } return sum } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,060
aoc_kotlin
MIT License
src/Lesson5PrefixSums/PassingCars.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
/** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { var numCarsGoingEast = 0 var numPassing = 0 if (A.size > 1) { for (i in A.indices) { if (A[i] == 0) { numCarsGoingEast++ } else { numPassing += numCarsGoingEast } if (numPassing > 1000000000) return -1 } } return numPassing } /** * A non-empty array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road. * * Array A contains only 0s and/or 1s: * * 0 represents a car traveling east, * 1 represents a car traveling west. * The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west. * * For example, consider array A such that: * * A[0] = 0 * A[1] = 1 * A[2] = 0 * A[3] = 1 * A[4] = 1 * We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4). * * Write a function: * * class Solution { public int solution(int[] A); } * * that, given a non-empty array A of N integers, returns the number of pairs of passing cars. * * The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000. * * For example, given: * * A[0] = 0 * A[1] = 1 * A[2] = 0 * A[3] = 1 * A[4] = 1 * the function should return 5, as explained above. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [1..100,000]; * each element of array A is an integer that can have one of the following values: 0, 1. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
1,686
Codility-Kotlin
Apache License 2.0
src/day10/Day10.kt
JoeSkedulo
573,328,678
false
{"Kotlin": 69788}
package day10 import Runner fun main() { Day10Runner().solve() } class Day10Runner : Runner<Int>( day = 10, expectedPartOneTestAnswer = 13140, expectedPartTwoTestAnswer = null ) { override fun partOne(input: List<String>, test: Boolean): Int { val cycles = cycles(input) return listOf(20, 60, 100, 140, 180, 220) .sumOf { cycleIndex -> cycles[cycleIndex - 1].xValue * cycleIndex } } override fun partTwo(input: List<String>, test: Boolean): Int { val cycles = cycles(input) cycles.forEachIndexed { index, cycle -> if (index % 40 == 0) { println("") } if (cycle.xValue in (index % 40 - 1)..(index % 40 + 1)) { print("█") } else { print(" ") } } return 1 } private fun cycles(input: List<String>) : List<Cycle> { val instructions = instructions(input) return buildList { add(Cycle(1)) instructions.forEach { instruction -> addAll(instruction.toCycles(this.last().xValue)) } } } private fun instructions(input : List<String>) : List<Instruction> { return input.map { line -> when (line) { "noop" -> Noop else -> Addx(value = line.split(" ").last().toInt()) } } } private fun Instruction.toCycles(currentValue: Int) : List<Cycle> { return when (this) { is Addx -> listOf(Cycle(currentValue), Cycle(currentValue + this.value)) Noop -> listOf(Cycle(currentValue)) } } } sealed interface Instruction object Noop : Instruction data class Addx(val value: Int) : Instruction data class Cycle( val xValue: Int )
0
Kotlin
0
0
bd8f4058cef195804c7a057473998bf80b88b781
1,832
advent-of-code
Apache License 2.0
src/9DynamicProgramming2/TheCitrusIntern.kt
bejohi
136,087,641
false
{"Java": 63408, "Kotlin": 5933, "C++": 5711, "Python": 3670}
import java.util.* // Solution for https://open.kattis.com/problems/citrusintern // With help from https://github.com/amartop var numberOfEmployees = 0 var input = Scanner(System.`in`) var costs = mutableListOf<Int>() var inL = arrayOf<Long>() var outUpL = arrayOf<Long>() var outDownL = arrayOf<Long>() var root = -1 fun init() : Array<MutableList<Int>>{ numberOfEmployees = input.nextInt() val adjList = Array(numberOfEmployees,{ _ -> mutableListOf<Int>()}) val rootList = BooleanArray(numberOfEmployees,{_ -> true}) for(i in 0 until numberOfEmployees){ costs.add(input.nextInt()) val childs = input.nextInt() for(x in 0 until childs){ val currentChild = input.nextInt() adjList[i].add(currentChild) rootList[currentChild] = false } } for(i in 0 until numberOfEmployees){ if(rootList[i]){ root = i break } } return adjList } fun solve(adjList: Array<MutableList<Int>>){ inL = Array<Long>(numberOfEmployees,{ _ -> 0}) // Init to weight for(i in 0 until costs.size){ inL[i] = costs[i].toLong() } outDownL = Array<Long>(numberOfEmployees,{ _ -> 0}) outUpL = Array<Long>(numberOfEmployees,{ _ -> 0}) fillTable2(root,adjList) println(Math.min(outDownL[root],inL[root])) } fun fillTable2(currentVertex: Int, adjList: Array<MutableList<Int>>){ if(adjList[currentVertex].isEmpty()){ outDownL[currentVertex] = Long.MAX_VALUE return } var delta: Long = Long.MAX_VALUE for(neighbour in adjList[currentVertex]){ fillTable2(neighbour,adjList) inL[currentVertex] += outUpL[neighbour] outUpL[currentVertex] += Math.min(inL[neighbour], outDownL[neighbour]) outDownL[currentVertex] += Math.min(inL[neighbour], outDownL[neighbour]) delta = Math.min(Math.max(inL[neighbour]- outDownL[neighbour],0),delta) } outDownL[currentVertex] += delta } fun main(args: Array<String>){ val adjList = init() solve(adjList) }
0
Java
0
0
7e346636786215dee4c681b80bc694c8e016e762
2,072
UiB_INF237
MIT License
y2017/src/main/kotlin/adventofcode/y2017/Day19.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution object Day19 : AdventSolution(2017, 19, "A Series of Tubes") { override fun solvePartOne(input: String): String { val lines = input.lines() val pipeRunner = PipeRunner(lines) pipeRunner.run() return pipeRunner.word } override fun solvePartTwo(input: String): String { val lines = input.lines() val pipeRunner = PipeRunner(lines) pipeRunner.run() return pipeRunner.count.toString() } } private class PipeRunner(private val pipes: List<String>) { private var position = Point(pipes[0].indexOf("|"), 0) var direction = Point(0, 1) var word = "" var count = 0 fun run() { do { val ch = charAt(position) when (ch) { '+' -> direction = findNewDirection() in 'A'..'Z' -> word += ch ' ' -> count-- } position += direction count++ } while (ch != ' ') } private fun findNewDirection(): Point { val options = if (direction.x == 0) listOf(Point(-1, 0), Point(1, 0)) else listOf(Point(0, -1), Point(0, 1)) return options.first { charAt(position + it) in "-|" } } private fun charAt(p: Point) = pipes.getOrNull(p.y)?.getOrNull(p.x) ?: ' ' } private data class Point(val x: Int, val y: Int) { operator fun plus(o: Point) = Point(x + o.x, y + o.y) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,283
advent-of-code
MIT License
src/main/kotlin/g2701_2800/s2746_decremental_string_concatenation/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2701_2800.s2746_decremental_string_concatenation // #Medium #Array #String #Dynamic_Programming // #2023_08_08_Time_264_ms_(100.00%)_Space_44.7_MB_(59.38%) class Solution { private val inf = 1e9.toInt() private lateinit var dp: Array<Array<Array<Int?>>> fun minimizeConcatenatedLength(words: Array<String>): Int { val n = words.size dp = Array(n) { Array(26) { arrayOfNulls( 26 ) } } val curWord = words[0] val curLen = curWord.length val curFirst = curWord[0] val curLast = curWord[curLen - 1] return curLen + solve(1, curFirst, curLast, n, words) } private fun solve(idx: Int, prevFirst: Char, prevLast: Char, n: Int, words: Array<String>): Int { if (idx == n) return 0 if (dp[idx][prevFirst.code - 'a'.code][prevLast.code - 'a'.code] != null) { return dp[idx][prevFirst.code - 'a'.code][prevLast.code - 'a'.code]!! } val curWord = words[idx] val curLen = curWord.length val curFirst = curWord[0] val curLast = curWord[curLen - 1] var ans = inf ans = if (prevFirst == curLast) { ans.coerceAtMost(curLen - 1 + solve(idx + 1, curFirst, prevLast, n, words)) } else { ans.coerceAtMost(curLen + solve(idx + 1, curFirst, prevLast, n, words)) } ans = if (prevLast == curFirst) { ans.coerceAtMost(curLen - 1 + solve(idx + 1, prevFirst, curLast, n, words)) } else { ans.coerceAtMost(curLen + solve(idx + 1, prevFirst, curLast, n, words)) } return ans.also { dp[idx][prevFirst.code - 'a'.code][prevLast.code - 'a'.code] = it } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,780
LeetCode-in-Kotlin
MIT License
src/main/kotlin/g1501_1600/s1519_number_of_nodes_in_the_sub_tree_with_the_same_label/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1501_1600.s1519_number_of_nodes_in_the_sub_tree_with_the_same_label // #Medium #Hash_Table #Depth_First_Search #Breadth_First_Search #Tree #Counting // #2023_06_12_Time_1130_ms_(87.50%)_Space_290.4_MB_(12.50%) class Solution { fun countSubTrees(n: Int, edges: Array<IntArray>, labelsString: String): IntArray { val labelsCount = IntArray(n) if (n <= 0) { return labelsCount } val labels = IntArray(n) var nodeNumber = 0 for (label in labelsString.toCharArray()) { labels[nodeNumber++] = label.code - 'a'.code } val graph = ArrayList<ArrayList<Int>>() for (i in 0 until n) { graph.add(ArrayList()) } for (edge in edges) { val parent = edge[0] val child = edge[1] graph[parent].add(child) graph[child].add(parent) } getLabelsFrequency(0, graph, labels, labelsCount, 0) return labelsCount } private fun getLabelsFrequency( root: Int, graph: ArrayList<ArrayList<Int>>, labels: IntArray, labelsCount: IntArray, parent: Int ): IntArray { val labelsFrequency = IntArray(26) val rootLabel = labels[root] labelsFrequency[rootLabel]++ for (child in graph[root]) { if (child == parent) { continue } val childLabelsFrequency = getLabelsFrequency(child, graph, labels, labelsCount, root) for (i in childLabelsFrequency.indices) { labelsFrequency[i] += childLabelsFrequency[i] } } labelsCount[root] = labelsFrequency[rootLabel] return labelsFrequency } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,757
LeetCode-in-Kotlin
MIT License
src/main/kotlin/Day9.kt
corentinnormand
725,992,109
false
{"Kotlin": 40576}
fun main(args: Array<String>) { Day9().two() } class Day9 : Aoc("day9.txt") { val test = """ 10 13 16 21 30 45 """.trimIndent() override fun one() { val input = readFile("day9.txt").lines() val first = input .map { it.split(" ") } .map { it.map { str -> str.toInt() } } val tmp = first[0].toMutableList() val res = first.map { it.toMutableList() } .map { val oneRes = mutableListOf(it) while (oneRes.last().any { it != 0 }) { val newLine = mutableListOf<Int>() val last = oneRes.last() for (i in 0..<last.size - 1) { newLine.add(last[i + 1] - last[i]) } oneRes.add(newLine) } oneRes.last().add(0) for (i in oneRes.size - 2 downTo 0) { oneRes[i].add(oneRes[i].last() + oneRes[i + 1].last()) } oneRes.first().last() } .sum() println(res) } override fun two() { val input =readFile("day9.txt").lines() val first = input .map { it.split(" ") } .map { it.map { str -> str.toInt() } } val tmp = first[0].toMutableList() val res = first.map { it.toMutableList() } .map { val oneRes = mutableListOf(it) while (oneRes.last().any { it != 0 }) { val newLine = mutableListOf<Int>() val last = oneRes.last() for (i in 0..<last.size - 1) { newLine.add(last[i + 1] - last[i]) } oneRes.add(newLine) } oneRes.last().addFirst(0) for (i in oneRes.size - 2 downTo 0) { oneRes[i].addFirst(oneRes[i].first() - oneRes[i + 1].first()) } oneRes.first().first() } .sum() println(res) } }
0
Kotlin
0
0
2b177a98ab112850b0f985c5926d15493a9a1373
2,115
aoc_2023
Apache License 2.0
src/main/kotlin/aoc/Day8.kt
dtsaryov
573,392,550
false
{"Kotlin": 28947}
package aoc /** * [AoC 2022: Day 8](https://adventofcode.com/2022/day/8) */ fun amountOfVisibleTrees(input: List<String>): Int { val grid = parseGrid(input) val visibleTrees = mutableSetOf<Pair<Int, Int>>() walk(grid) { tree, i, j -> if (visibleFromTop(tree, i, j, grid)) visibleTrees += i to j if (visibleFromRight(tree, i, j, grid)) visibleTrees += i to j if (visibleFromBottom(tree, i, j, grid)) visibleTrees += i to j if (visibleFromLeft(tree, i, j, grid)) visibleTrees += i to j } return visibleTrees.size } fun highestScenicScore(input: List<String>): Int { val grid = parseGrid(input) var maxScore = 0 walk(grid) { tree, i, j -> val treeScore = getTopScore(tree, i, j, grid) * getRightScore(tree, i, j, grid) * getBottomScore(tree, i, j, grid) * getLeftScore(tree, i, j, grid) if (treeScore > maxScore) maxScore = treeScore } return maxScore } private fun visibleFromTop(tree: Int, i: Int, j: Int, grid: Array<Array<Int>>): Boolean { if (i == 0) return true var highest = -1 for (ii in i - 1 downTo 0) { if (highest < grid[ii][j]) highest = grid[ii][j] } return highest < tree } private fun visibleFromRight(tree: Int, i: Int, j: Int, grid: Array<Array<Int>>): Boolean { if (j == grid.size - 1) return true var highest = -1 for (jj in j + 1 until grid.size) { if (highest < grid[i][jj]) highest = grid[i][jj] } return highest < tree } private fun visibleFromBottom(tree: Int, i: Int, j: Int, grid: Array<Array<Int>>): Boolean { if (i == grid.size - 1) return true var highest = -1 for (ii in i + 1 until grid.size) { if (highest < grid[ii][j]) highest = grid[ii][j] } return highest < tree } private fun visibleFromLeft(tree: Int, i: Int, j: Int, grid: Array<Array<Int>>): Boolean { if (j == 0) return true var highest = -1 for (jj in j - 1 downTo 0) { if (highest < grid[i][jj]) highest = grid[i][jj] } return highest < tree } private fun getTopScore(tree: Int, i: Int, j: Int, grid: Array<Array<Int>>): Int { if (i == 0) return 0 var score = 0 for (ii in i - 1 downTo 0) { score++ if (tree <= grid[ii][j]) break } return score } private fun getRightScore(tree: Int, i: Int, j: Int, grid: Array<Array<Int>>): Int { if (j == grid.size - 1) return 0 var score = 0 for (jj in j + 1 until grid.size) { score++ if (tree <= grid[i][jj]) break } return score } private fun getBottomScore(tree: Int, i: Int, j: Int, grid: Array<Array<Int>>): Int { if (i == grid.size - 1) return 0 var score = 0 for (ii in i + 1 until grid.size) { score++ if (tree <= grid[ii][j]) break } return score } private fun getLeftScore(tree: Int, i: Int, j: Int, grid: Array<Array<Int>>): Int { if (j == 0) return 0 var score = 0 for (jj in j - 1 downTo 0) { score++ if (tree <= grid[i][jj]) break } return score } @Suppress("UNCHECKED_CAST") private fun parseGrid(input: List<String>): Array<Array<Int>> { val grid = arrayOfNulls<Array<Int>>(input.size) for ((i, s) in input.withIndex()) { val row = arrayOfNulls<Int>(s.length) for ((j, ch) in s.withIndex()) row[j] = ch.digitToInt() grid[i] = row as Array<Int> } return grid as Array<Array<Int>> } private fun <T> walk(grid: Array<Array<T>>, visitor: (T, Int, Int) -> Unit) { for (i in grid.indices) for (j in grid.indices) visitor(grid[i][j], i, j) }
0
Kotlin
0
0
549f255f18b35e5f52ebcd030476993e31185ad3
3,777
aoc-2022
Apache License 2.0
src/Lesson3TimeComplexity/PermMissingElem.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
import java.util.Arrays /** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { Arrays.sort(A) if (A.size == 0 || A[0] != 1) return 1 for (i in 0 until A.size - 1) { if (A[i] + 1 != A[i + 1]) { return A[i] + 1 } } return A[A.size - 1] + 1 } /** * An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing. * * Your goal is to find that missing element. * * Write a function: * * class Solution { public int solution(int[] A); } * * that, given an array A, returns the value of the missing element. * * For example, given array A such that: * * A[0] = 2 * A[1] = 3 * A[2] = 1 * A[3] = 5 * the function should return 4, as it is the missing element. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [0..100,000]; * the elements of A are all distinct; * each element of array A is an integer within the range [1..(N + 1)]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
1,077
Codility-Kotlin
Apache License 2.0
src/main/kotlin/com/sk/leetcode/kotlin/253. Meeting Rooms II.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package leetcode.kotlin.array.easy import java.util.PriorityQueue private fun minMeetingRooms(intervals: Array<IntArray>): Int { intervals.sortBy { it[0] } var pq = PriorityQueue<IntArray>() { a1, a2 -> a1[1] - a2[1] } // sort by end time for (meeting in intervals) { if (!pq.isEmpty() && pq.peek()[1] <= meeting[0]) pq.poll() // notice equal, we are not counting swapping time pq.add(meeting) } return pq.size } private fun minMeetingRooms2(intervals: Array<IntArray>): Int { val starts = IntArray(intervals.size) val ends = IntArray(intervals.size) intervals.forEachIndexed { index, interval -> starts[index] = interval[0] ends[index] = interval[1] } starts.sort() ends.sort() var rooms = 0 var endsItr = 0 for (i in starts.indices) { if (starts[i] < ends[endsItr]) { rooms++ } else { endsItr++ } } return rooms } private fun minMeetingRooms3(intervals: Array<IntArray>): Int { val time = mutableListOf<Pair<Int, Boolean>>() intervals.forEach { time.add(Pair(it[0], true)) time.add(Pair(it[1], false)) } // Notice sort, there can we same start and end point, put start point first time.sortWith(compareBy<Pair<Int, Boolean>> { it.first }.thenBy { it.second }) var runningMeeting = 0 // running meeting at any time var maxRooms = 0 for (pair in time) { if (pair.second) { //start time, allocate room runningMeeting++ maxRooms = maxOf(maxRooms, runningMeeting) } else { runningMeeting-- } } return maxRooms }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,676
leetcode-kotlin
Apache License 2.0
src/main/kotlin/g1701_1800/s1755_closest_subsequence_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1755_closest_subsequence_sum // #Hard #Array #Dynamic_Programming #Two_Pointers #Bit_Manipulation #Bitmask // #2023_06_18_Time_620_ms_(100.00%)_Space_43.5_MB_(100.00%) class Solution { private var idx = 0 private var sum = 0 fun minAbsDifference(nums: IntArray, goal: Int): Int { val n = nums.size val nFirst = Math.pow(2.0, n.toDouble() / 2).toInt() val nSecond = Math.pow(2.0, (n - n / 2).toDouble()).toInt() val first = IntArray(nFirst) val second = IntArray(nSecond) helper(nums, first, 0, n / 2 - 1) sum = 0 idx = sum helper(nums, second, n / 2, n - 1) first.sort() second.sort() var low = 0 var high = nSecond - 1 var ans = Int.MAX_VALUE while (low < nFirst && high >= 0) { val localSum = first[low] + second[high] ans = Math.min(ans, Math.abs(localSum - goal)) if (ans == 0) { break } if (localSum < goal) { low++ } else { high-- } } return ans } private fun helper(nums: IntArray, arr: IntArray, start: Int, end: Int) { for (i in start..end) { sum += nums[i] arr[idx++] = sum helper(nums, arr, i + 1, end) sum -= nums[i] } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,414
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/chriswk/aoc/advent2021/Day4.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger class Day4 : AdventDay(2021, 4) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day4() report { day.part1() } report { day.part2() } } val logger: Logger = LogManager.getLogger(Day4::class.java) } fun part1(): Int { val (draws, boards) = parseInput(inputAsLines) val (hadToDraw, winningBoard) = playGame(draws, boards) return winningBoard.score(hadToDraw) } fun part2(): Int { val (draws, boards) = parseInput(inputAsLines) val (hadToDraw, winningBoard) = playGameLast(draws, boards) return winningBoard.score(hadToDraw) } fun playGame(draws: List<Int>, boards: List<Bingo>): Pair<List<Int>, Bingo> { val minimumDraws = draws.take(5) val hasAWinner = draws.drop(5).asSequence().runningFold(minimumDraws) { drawn, nextNumber -> logger.info("Drawing $nextNumber. So far: $drawn") drawn + nextNumber }.first { drawn -> val winner = boards.find { it.hasBingo(drawn) } logger.info(winner) winner != null } return hasAWinner to boards.first { it.hasBingo(hasAWinner) } } fun playGameLast(draws: List<Int>, boards: List<Bingo>): Pair<List<Int>, Bingo> { val minimumDraws = draws.take(5) val lastWinner = draws.drop(5).asSequence().runningFold(minimumDraws) { drawn, nextNumber -> drawn + nextNumber }.first { drawn -> boards.all { it.hasBingo(drawn) } } return lastWinner to boards.filterNot { it.hasBingo(lastWinner.dropLast(1)) }.first() } fun parseInput(input: List<String>): Pair<List<Int>, List<Bingo>> { val draws = input.first().split(",").map { it.trim().toInt() } val boards = input.drop(2).chunked(6).map { board -> val parsedBoard = board.take(5).flatMap { row -> val split = row.trim().split(" ").filter { it.isNotBlank() } split.map { it.toInt() } } Bingo(parsedBoard) } return draws to boards } data class Bingo(val board: List<Int>) { val rows = board.chunked(5) val columns: List<List<Int>> = (0.until(5)).map { col -> (0.until(5)).map { row -> board[col + (row * 5)] } } fun hasBingo(marked: List<Int>): Boolean { return rows.any { marked.containsAll(it) } || columns.any { marked.containsAll(it) } } fun matches(marked: List<Int>): List<Int> { return board.filter { marked.contains(it) } } fun score(drawn: List<Int>): Int { return board.filterNot { drawn.contains(it) }.sum() * drawn.last() } } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
3,072
adventofcode
MIT License
src/Day03.kt
azarovalex
573,931,704
false
{"Kotlin": 4391}
fun main() { val costs = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun part1(input: List<String>): Int { return input .map { val halfSize = it.length / 2 val leftHalf = it.subSequence(0, halfSize) val rightHalf = it.subSequence(halfSize, it.lastIndex + 1) val commonChar = leftHalf.toSet().intersect(rightHalf.toSet()).first() return@map costs.indexOf(commonChar) } .sum() } fun part2(input: List<String>): Int { return input .chunked(3) .map { val commonChar = it[0].toSet() intersect it[1].toSet() intersect it[2].toSet() return@map costs.indexOf(commonChar.first()) } .sum() } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
48578aeed4250987d4ee339d801f8d5e6577b55b
918
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/g2901_3000/s2983_palindrome_rearrangement_queries/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2983_palindrome_rearrangement_queries // #Hard #String #Hash_Table #Prefix_Sum #2024_01_19_Time_905_ms_(87.50%)_Space_131.9_MB_(37.50%) class Solution { private var n = 0 // get associated index in the other half private fun opp(i: Int): Int { return n - 1 - i } fun canMakePalindromeQueries(s: String, queries: Array<IntArray>): BooleanArray { val fq = IntArray(26) val m = queries.size val ret = BooleanArray(m) n = s.length // check that both halves contain the same letters for (i in 0 until n / 2) { fq[s[i].code - 'a'.code]++ } for (i in n / 2 until n) { fq[s[i].code - 'a'.code]-- } for (em in fq) { if (em != 0) { return ret } } // find the first and the last characters in the first half // that do not match with their associated character in // the second half var problemPoint = -1 var lastProblem = -1 for (i in 0 until n / 2) { if (s[i] != s[opp(i)]) { if (problemPoint == -1) { problemPoint = i } lastProblem = i } } // if already a palindrome if (problemPoint == -1) { ret.fill(true) return ret } // the idea is that at least one of the intervals in the // query has to cover the first pair of different characters. // But depending on how far the other end of that interval // goes, the requirements for the other interval are lessened val dpFirst = IntArray(n / 2 + 1) val dpSecond = IntArray(n + 1) dpFirst.fill(-1) dpSecond.fill(-1) // assuming the first interval covers the first problem, // and then extends to the right var rptr = opp(problemPoint) val mp: MutableMap<Char, Int> = HashMap() for (i in problemPoint until n / 2) { mp.compute(s[i]) { _: Char?, v: Int? -> if (v == null) 1 else v + 1 } // the burden for the left end of the second interval does not change; // it needs to go at least until the last problematic match. But the // requirements for the right end do. If we can rearrange the characters // in the left half to match the right end of the right interval, this // means we do not need the right end of the right interval to go too far while (mp.containsKey(s[rptr]) || (rptr >= n / 2 && s[rptr] == s[opp(rptr)] && mp.isEmpty()) ) { mp.computeIfPresent(s[rptr]) { _: Char?, v: Int -> if (v == 1) null else v - 1 } rptr-- } dpFirst[i] = rptr } // mirrored discussion assuming it is the right interval that takes // care of the first problematic pair var lptr = problemPoint mp.clear() for (i in opp(problemPoint) downTo n / 2) { mp.compute(s[i]) { _: Char?, v: Int? -> if (v == null) 1 else v + 1 } while (mp.containsKey(s[lptr]) || (lptr < n / 2 && s[lptr] == s[opp(lptr)] && mp.isEmpty()) ) { mp.computeIfPresent(s[lptr]) { _: Char?, v: Int -> if (v == 1) null else v - 1 } lptr++ } dpSecond[i] = lptr } for (i in 0 until m) { val a = queries[i][0] val b = queries[i][1] val c = queries[i][2] val d = queries[i][3] // if either interval the problematic interval on its side, it does not matter // what happens with the other interval if (a <= problemPoint && b >= lastProblem || c <= opp(lastProblem) && d >= opp(problemPoint) ) { ret[i] = true continue } // if the left interval covers the first problem, we use // dp to figure out if the right one is large enough if (a <= problemPoint && b >= problemPoint && d >= dpFirst[b] && c <= opp(lastProblem)) { ret[i] = true } // similarly for the case where the right interval covers // the first problem if (d >= opp(problemPoint) && c <= opp(problemPoint) && a <= dpSecond[c] && b >= lastProblem) { ret[i] = true } } return ret } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
4,573
LeetCode-in-Kotlin
MIT License
src/Day01.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
fun main() { fun parseInput(input: List<String>): List<List<Int>> { return input.fold(emptyList()) { acc, cal -> when { cal.isBlank() -> acc.plusElement(emptyList()) else -> acc.dropLast(1).plusElement((acc.lastOrNull() ?: emptyList()) + cal.toInt()) } } } fun part1(input: List<String>): Int { return parseInput(input).maxOf { it.sum() } } fun part2(input: List<String>): Int { return parseInput(input).map { it.sum() } .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") checkThat(part1(testInput), 24000) checkThat(part2(testInput), 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
886
aoc22
Apache License 2.0
src/main/kotlin/info/dgjones/barnable/parser/TextSplitter.kt
jonesd
442,279,905
false
{"Kotlin": 474251}
/* * 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 info.dgjones.barnable.parser import info.dgjones.barnable.nlp.TextSentence import info.dgjones.barnable.nlp.WordMorphology /* Split up a text of words up into a list of LexicalItems. The largest expression is selected for each split. Each split may contain multiple options. In case a word is not known, then an Unknown Word entry will be used. */ class TextSplitter(val lexicon: Lexicon) { fun split(text: TextSentence): TextSplitUnits { val words = text.elements.map { it.token } return split(words) } private fun split(words: List<String>): TextSplitUnits { var wordIndex = 0 val split = mutableListOf<List<LexicalItem>>() while (wordIndex < words.size) { val entry = lexicon.lookupNextEntry(words.subList(wordIndex, words.size)) val selectedEntries = if (entry.isNotEmpty()) selectByMostWords(entry) else unknownEntry(words[wordIndex]) split.add(selectedEntries) wordIndex += wordsIncrement(selectedEntries) } return TextSplitUnits(split.toList()) } private fun wordsIncrement(selectedEntries: List<LexicalItem>): Int = if (selectedEntries.isNotEmpty()) selectedEntries.first().handler.word.expression.size else 1 private fun selectByMostWords(lexicalItems: List<LexicalItem>): List<LexicalItem> { if (lexicalItems.isEmpty()) { return listOf() } val maxExpressionSize = lexicalItems.maxOfOrNull { it.handler.word.expression.size } return lexicalItems.filter { it.handler.word.expression.size == maxExpressionSize } } private fun unknownEntry(word: String): List<LexicalItem> = listOf(LexicalItem(listOf(WordMorphology(word)), WordUnknown(word))) } data class TextSplitUnits(val units: List<List<LexicalItem>>)
1
Kotlin
0
0
b5b7453e2fe0b2ae7b21533db1b2b437b294c63f
2,428
barnable
Apache License 2.0
src/main/kotlin/twentytwenty/Day11.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwenty fun main() { var input = {}.javaClass.getResource("twentytwenty/input11.txt").readText().lines().asSequence() .map { it.toCharArray().toMutableList() } .toList() SeatingArea({}.javaClass.getResource("twentytwenty/input11.txt").readText().lines()).countStableState().also { println(it) } val dx = listOf(1, -1, 0, 0, -1, -1, 1, 1) val dy = listOf(0, 0, 1, -1, -1, 1, -1, 1) while (true) { val next = input.map { it.toMutableList() } var changed = false for (i in input.indices) { for (j in input[i].indices) { var occupied = 0 for (k in dx.indices) { var x = i + dx[k] var y = j + dy[k] try { while (true) { if (input[x][y] == '#') { occupied++ break } else if (input[x][y] == 'L') { break } x += dx[k] y += dy[k] } } catch (e: Exception) { } } if (input[i][j] == 'L' && occupied == 0) { changed = true next[i][j] = '#' } else if (input[i][j] == '#' && occupied >= 5) { changed = true next[i][j] = 'L' } } } input = next if (!changed) break } input.map { row -> row.count { it == '#' } }.sum().let(::println) } class SeatingArea { private val area: Array<CharArray>; constructor(lines: List<String>) { area = Array(lines.size) { i -> lines[i].toCharArray() } } fun countStableState(): Int { var stable = false while (!stable) { var next = calcNext() stable = !next.second if (!stable) { next.first.copyInto(area) } } return area.flatMap { sa -> sa.asSequence() }.count { c -> c == '#' } } private fun calcNext(): Pair<Array<CharArray>, Boolean> { val copy = Array(area.size) { i -> area[i].copyOf() } var changed = false for (i in copy.indices) { for (j in copy[i].indices) { val future = future(i, j) changed = changed || future != copy[i][j] copy[i][j] = future } } return Pair(copy, changed) } private fun future(i: Int, j: Int): Char { return if (area[i][j] == '.') { '.' } else if (area[i][j] == '#' && countAdjecentOccupiedSeats(i, j) >= 4) { 'L' } else if (area[i][j] == 'L' && countAdjecentOccupiedSeats(i, j) == 0) { '#' } else { area[i][j] } } private fun countAdjecentOccupiedSeats(i: Int, j: Int) = collectAdjecentSeats(i, j).count { c -> c == '#' } private fun collectAdjecentSeats(i: Int, j: Int): List<Char> { val result = mutableListOf<Char>() for (ii in i - 1..i + 1) { for (jj in j - 1..j + 1) { if ((ii != i || jj != j) && (ii > -1 && jj > -1 && ii < area.size && jj < area[ii].size)) { result.add(area[ii][jj]) } } } return result } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
3,565
aoc202xkotlin
The Unlicense
src/main/kotlin/com/polydus/aoc18/Day15.kt
Polydus
160,193,832
false
null
package com.polydus.aoc18 class Day15: Day(15){ //https://adventofcode.com/2018/day/15 val height = input.size val width = input.sortedBy { it.length }.last().length val map = Array(height) {CharArray(width){ ' '}} val mapVecs = Array(height) {Array<Vec?>(width) {null} } val goblins = arrayListOf<Unit>() val elves = arrayListOf<Unit>() val units = arrayListOf<Unit>() var lastPath = arrayListOf<Vec>() init { var i = 0 input.forEach { val chars = it.toCharArray() for(c in 0 until chars.size){ map[i][c] = chars[c] if(chars[c] == 'G'){ goblins.add(Unit(c, i, 0)) units.add(goblins.last()) map[i][c] = '.' } else if(chars[c] == 'E'){ elves.add(Unit(c, i, 1)) units.add(elves.last()) map[i][c] = '.' } mapVecs[i][c] = Vec(c, i) } i++ } print() partOne() //partTwo() } fun partOne(){ var running = true var tick = -1 while (running){ goblins.sortWith(compareBy({ it.y }, { it.x })) elves.sortWith(compareBy({ it.y }, { it.x })) units.sortWith(compareBy({ it.y }, { it.x })) tick++ for(u in units){ if(u.alive){ //else { var adj = getAdj(u) if(!(adj.contains(0) && u.type == 1) && !(adj.contains(1) && u.type == 0)){ val targets = units .filter { it.type != u.type } .filter { it.alive } //.sortedBy { Math.abs(it.x - u.x) + Math.abs(it.y - u.y) } val options = arrayListOf<Vec>() for(t in targets){ val adjacent = getAdj(t) for(a in adjacent.withIndex()){ if(a.value == 100){ when(a.index){ 0 -> options.add(mapVecs[t.y - 1][t.x]!!) 1 -> options.add(mapVecs[t.y][t.x + 1]!!) 2 -> options.add(mapVecs[t.y + 1][t.x]!!) 3 -> options.add(mapVecs[t.y][t.x - 1]!!) } } } } options.removeIf { !canReach(u, it)} options.sortBy { it.length } //options.sortBy { (Math.abs(it.x - u.x) + Math.abs(it.y - u.y)) } //options.removeIf { // (Math.abs(it.x - u.x) + Math.abs(it.y - u.y)) != // (Math.abs(options.first().x - u.x) + Math.abs(options.first().y - u.y)) //} options.removeIf { it.length != options.first().length } //options.sortWith(compareBy({ it.y }, { it.x })) if(options.size > 1){ options.sortWith(compareBy({ it.y }, { it.x })) } if(!options.isEmpty()){ //move to options.first //just check for a sec if there is a prioritized way to get to the pos canReach(u, options.first()) val length = lastPath.size val target = lastPath.last() //if(!(target.x == u.x && u.y - 1 == target.y)){ canReach(u, mapVecs[options.first().y - 1][options.first().x]!!) var lengthFrom0 = lastPath.size + 1 canReach(u, mapVecs[options.first().y][options.first().x - 1]!!) var lengthFrom3 = lastPath.size + 1 canReach(u, mapVecs[options.first().y][options.first().x + 1]!!) var lengthFrom1 = lastPath.size + 1 canReach(u, mapVecs[options.first().y + 1][options.first().x]!!) var lengthFrom2 = lastPath.size + 1 println() //} println("moving unit from ${u.x}x ${u.y}y to $target") u.x = target.x u.y = target.y /*var dists = arrayOf(999999, 999999, 999999, 999999) if(adj[0] == 100) dists[0] = Math.abs((u.x) - target.x) + Math.abs((u.y - 1) - target.y) if(adj[1] == 100) dists[1] = Math.abs((u.x + 1) - target.x) + Math.abs((u.y) - target.y) if(adj[2] == 100) dists[2] = Math.abs((u.x) - target.x) + Math.abs((u.y + 1) - target.y) if(adj[3] == 100) dists[3] = Math.abs((u.x - 1) - target.x) + Math.abs((u.y) - target.y) //var lowest = 0 var lowestDist = 999999 for(d in dists.withIndex()){ if(d.value != 999999 && d.value < lowestDist){ lowestDist = d.value //lowest = d.index } }*/ /*if(lowestDist == 999999){ println("$u did nothing") } else { if(dists[0] == lowestDist){ u.y-- } else if(dists[3] == lowestDist){ u.x-- } else if(dists[1] == lowestDist){ u.x++ } else if(dists[2] == lowestDist){ u.y++ } println("$u moved") }*/ } else { println("$u did nothing") } //println() // .sortWith((Math.abs(it.x - u.x) + Math.abs(it.y - u.y))) //.sortWith { (Math.abs(it.x - unit.x) + Math.abs(it.y - unit.y)) } //.sortWith(compareBy({ it.y }, { it.x })) /* var moved = false for(t in targets.withIndex()){ var closestIndex = -1 var dist = 999999999 if(adj[2] == 100 && (Math.abs(t.value.x - u.x) + Math.abs(t.value.y - (u.y + 1))) <= dist){ closestIndex = 2 dist = (Math.abs(t.value.x - u.x) + Math.abs(t.value.y - (u.y + 1))) } if(adj[1] == 100 && (Math.abs(t.value.x - (u.x + 1)) + Math.abs(t.value.y - (u.y))) <= dist){ closestIndex = 1 dist = (Math.abs(t.value.x - (u.x + 1)) + Math.abs(t.value.y - (u.y))) } if(adj[3] == 100 && (Math.abs(t.value.x - (u.x - 1)) + Math.abs(t.value.y - (u.y))) <= dist){ closestIndex = 3 dist = (Math.abs(t.value.x - (u.x - 1)) + Math.abs(t.value.y - (u.y))) } if(adj[0] == 100 && (Math.abs(t.value.x - u.x) + Math.abs(t.value.y - (u.y - 1))) <= dist){ closestIndex = 0 dist = (Math.abs(t.value.x - u.x) + Math.abs(t.value.y - (u.y - 1))) } if(t.value == targets.last() && closestIndex > -1){ //move to this tile when(closestIndex){ 0 -> u.y-- 1 -> u.x++ 2 -> u.y++ 3 -> u.x-- } moved = true break } } if(moved){ println("$u moved") } else { println("$u did nothing") }*/ } adj = getAdj(u) if(adj.contains(0) && u.type == 1){ val units = getAdjUnits(u) val target = units.first() target.hp -= 3 if(target.hp < 0) target.alive = false println("$u hit a target: $target ${target.type}(${target.hp}) was hit") } else if(adj.contains(1) && u.type == 0){ val units = getAdjUnits(u) val target = units.first() target.hp -= 3 if(target.hp < 0) target.alive = false println("$u hit a target: $target ${target.type}(${target.hp}) was hit") } } if(goblins.none { it.alive }){ running = false //tick++ println("After $tick rounds:") print() break } else if(elves.none { it.alive }){ running = false //tick++ println("After $tick rounds:") print() break } /*when(c.direction){ 0 -> c.y-- 1 -> c.x++ 2 -> c.y++ 3 -> c.x-- } setDirection(c) for(c2 in carts){ if(c != c2 && c.x == c2.x && c.y == c2.y){ running = false println("Collision at ${c.x},${c.y}! tick: $tick") break } }*/ } //if(running) tick++ println("After $tick rounds:") print() //if(tick == 3) break //carts.sortWith(compareBy({ it.y }, { it.x })) } var answer = 0 for(u in units){ if(u.alive) answer += u.hp } answer *= tick println("done. turn: $tick. Answer: $answer") //for(c in carts.withIndex()){ //println("Cart ${c.index} at ${c.value.x}x${c.value.y}y | ${c.value.direction}d") //} } fun partTwo(){ } fun canReach(unit: Unit, target: Vec): Boolean{ //lastPath.clear() val origin = mapVecs[unit.y][unit.x] if(origin == target) return false for(y in 0 until height){ for(x in 0 until width){ mapVecs[y][x]?.resetPathVars() } } val openList = HashSet<Vec>() val closedList = HashSet<Vec>() openList.add(origin!!) origin.distToOrigin = 0 origin.distToTarget = origin.getDeltaTo(target) while(!openList.isEmpty()){ var tile = openList.elementAt(0) for(t in openList){ if(t.pathCost < tile.pathCost) tile = t } if(tile == target) break openList.remove(tile) closedList.add(tile) val adjacents = tile.getPassableAdjacents(mapVecs, map, units) for(a in adjacents){ val newDistToOrigin = tile.distToOrigin + 1 if(newDistToOrigin < a.distToOrigin){ openList.remove(a) closedList.remove(a) } if(!openList.contains(a) && !closedList.contains(a)){ a.distToOrigin = newDistToOrigin a.distToTarget = a.getDeltaTo(target) a.parent = tile openList.add(a) } } } val result = ArrayList<Vec>() var tile: Vec? = target while(tile?.parent != null){ result.add(tile) tile = tile.parent } lastPath.clear() lastPath.addAll(result) if(result.size > 0){ target.length = result.size } else { target.length = 99999 } return (result.size > 0) } fun print(){ println("") for(y in 0 until height){ var units = arrayListOf<Unit>() for(x in 0 until width){ var cart = false for(c in this.units){ if(c.alive && c.x == x && c.y == y){ when(c.type){ 0 -> print('G') 1 -> print('E') } cart = true units.add(c) break } } if(!cart) print(map[y][x]) } if(units.size > 0){ print(" ") for(u in units){ if(u.type == 0){ print(" G(${u.hp})") } else { print(" E(${u.hp})") } } } print("\n") } } fun getAdj(unit: Unit): Array<Int>{ val result = Array<Int>(4){-1} result[0] = type(unit.x, unit.y - 1) result[1] = type(unit.x + 1, unit.y) result[2] = type(unit.x, unit.y + 1) result[3] = type(unit.x - 1, unit.y) return result } fun getAdjUnits(unit: Unit): List<Unit>{ //val result = arrayListOf<Unit>() val units = this.units.filter { it.type != unit.type } .filter { (Math.abs(it.x - unit.x) + Math.abs(it.y - unit.y)) == 1 } .filter { it.alive } .sortedWith(compareBy({ it.y }, { it.x })) .sortedBy { it.hp } return units } fun type(x: Int, y: Int): Int{ try { var result = -1 val type = map[y][x] when(type){ '#' -> result = 101 '.' -> result = 100 } if(result == 100){ for(u in units){ if(u.alive && u.x == x && u.y == y){ result = u.type break } } } return result }catch (e: Exception){ return -1 } } class Unit(var x: Int, var y: Int, val type: Int){ var intersectionCount = 0 var alive = true var hp = 200 override fun toString(): String { var result = "" if(x < 0){ result += "${x}x" } else { result += " ${x}x" } if(y < 0){ result += "${y}y" } else { result += " ${y}y" } if(type == 0){ result += " G($hp)" } else { result += " E($hp)" } return result } } class Vec(val x: Int, val y: Int){ var distToOrigin = -1 var distToTarget = -1 var pathCost = 0 get() = distToOrigin + distToTarget var parent: Vec? = null var length = 99999 fun getPassableAdjacents(//excludeType: Int?, mapVecs: Array<Array<Vec?>>, map: Array<CharArray>, units: ArrayList<Unit>): List<Vec>{ return listOf( getTile(y + 1, x, mapVecs), getTile(y, x + 1, mapVecs), getTile(y - 1, x, mapVecs), getTile(y, x - 1, mapVecs)) .filterNot { it == null } .filter { type(it!!.x, it!!.y, map, units) == 100 } //.filterNot { it?.terrainType == excludeType } .requireNoNulls() } fun getTile(y: Int, x: Int, mapVecs: Array<Array<Vec?>>): Vec?{ if(y < 0 || x < 0) return null //can't have negative indices return try { mapVecs[y][x]!! } catch (e: NullPointerException){ null } } fun getDeltaTo(destination: Vec): Int{ if(destination == this) return 0 return (Math.abs(y - destination.y) + Math.abs(x - destination.x)) } fun type(x: Int, y: Int, map: Array<CharArray>, units: ArrayList<Unit>): Int{ try { var result = -1 val type = map[y][x] when(type){ '#' -> result = 101 '.' -> result = 100 } if(result == 100){ for(u in units){ if(u.alive && u.x == x && u.y == y){ result = u.type break } } } return result }catch (e: Exception){ return -1 } } fun resetPathVars(){ distToOrigin = -1 distToTarget = -1 parent = null //length = 99999 } override fun toString(): String { var result = "" if(x < 0){ result += "${x}x" } else { result += " ${x}x" } if(y < 0){ result += "${y}y" } else { result += " ${y}y" } return result } } }
0
Kotlin
0
0
e510e4a9801c228057cb107e3e7463d4a946bdae
18,752
advent-of-code-2018
MIT License
src/year_2022/day_07/Day07.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_07 import readInput import java.util.Stack sealed class IFile { data class Directory( val name: String, var files: MutableList<IFile> = mutableListOf() ): IFile() { fun totalSize(): Int { return files.sumOf { file -> when (file) { is Directory -> file.totalSize() is File -> file.size } } } override fun toString(): String { return "$name - ${totalSize()}" } } data class File( val fileName: String, val size: Int ): IFile() { override fun toString(): String { return "$fileName - $size" } } } object Day07 { /** * @return */ fun solutionOne(text: List<String>): Int { val (_, directoryMap) = buildFileSystem(text) return directoryMap .map { it.value.totalSize() } .filter { it <= 100_000 } .sumOf { it } } /** * @return */ fun solutionTwo(text: List<String>): Int { val (fileStructure, directoryMap) = buildFileSystem(text) val maxDiskSize = 70_000_000 val requiredEmptySpace = 30_000_000 val amountToClear = requiredEmptySpace - (maxDiskSize - fileStructure.totalSize()) return directoryMap .map { it.value.totalSize() } .filter { it >= amountToClear } .minByOrNull { it }!! } private fun buildFileSystem(text: List<String>): Pair<IFile.Directory, Map<String, IFile.Directory>> { val rootDirectory = IFile.Directory("/") val mutableDirectoryMap = mutableMapOf<String, IFile.Directory>() mutableDirectoryMap["/"] = rootDirectory var currentDirectory = Stack<IFile.Directory>() currentDirectory.add(rootDirectory) text.forEach { line -> val split = line.split(" ") if (line.startsWith("$")) { val command = split[1] if (command == "cd") { val directoryName = split[2] if (directoryName == "..") { currentDirectory.pop() } else if (directoryName == "/") { currentDirectory = Stack<IFile.Directory>() currentDirectory.add(rootDirectory) } else { val fullPathName = "${currentDirectory.toTypedArray().joinToString("/") { it.name }}/$directoryName" val exists = mutableDirectoryMap[fullPathName] if (exists != null) { currentDirectory.push(exists) } else { val directory = IFile.Directory(directoryName) mutableDirectoryMap[fullPathName] = directory currentDirectory.push(directory) } } } else if (command == "ls") { // no-op } else { println("$line - UNKNOWN COMMAND") } } else { if (split[0] == "dir") { val directoryName = split[1] val fullPathName = "${currentDirectory.toTypedArray().joinToString("/") { it.name }}/$directoryName" val exists = mutableDirectoryMap[fullPathName] if (exists != null) { currentDirectory.push(exists) } else { val directory = IFile.Directory(directoryName) mutableDirectoryMap[fullPathName] = directory currentDirectory.peek().files.add(directory) } } else { val size = Integer.parseInt(split[0]) val fileName = split[1] val file = IFile.File( fileName = fileName, size = size ) currentDirectory.peek().files.add(file) } } } return rootDirectory to mutableDirectoryMap } private fun printFileSystem(directory: IFile.Directory, indentation: Int = 0) { var indentationString = "" for (i in 0 until indentation) { indentationString += "\t" } println("dir: $indentationString${directory.name}\t${directory.totalSize()}") directory.files.forEach { file -> when (file) { is IFile.Directory -> printFileSystem(file, indentation + 1) is IFile.File -> println("file: $indentationString\t${file.fileName}\t${file.size}") } } } } fun main() { val inputText = readInput("year_2022/day_07/Day08.txt") val solutionOne = Day07.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day07.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
5,124
advent_of_code
Apache License 2.0
src/Day08.kt
valerakostin
574,165,845
false
{"Kotlin": 21086}
fun main() { fun parseArray(input: List<String>): Array<IntArray> { val row = input.size val column = input[0].length val array = Array(row) { IntArray(column) } for (r in 0 until row) { val line = input[r] for (c in 0 until column) { array[r][c] = line[c].digitToInt() } } return array } fun part1(input: Array<IntArray>): Int { val row = input.size val column = input[0].size val field = Array(row) { BooleanArray(column) } for (r in 0 until row) { var max = Integer.MIN_VALUE for (c in 0 until column) { if (input[r][c] > max) { field[r][c] = true max = input[r][c] } } } for (c in 0 until column) { var max = Integer.MIN_VALUE for (r in 0 until row) { if (input[r][c] > max) { field[r][c] = true max = input[r][c] } } } for (r in 0 until row) { var max = Integer.MIN_VALUE for (c in column - 1 downTo 0) { if (input[r][c] > max) { field[r][c] = true max = input[r][c] } } } for (c in 0 until column) { var max = Integer.MIN_VALUE for (r in row - 1 downTo 0) { if (input[r][c] > max) { field[r][c] = true max = input[r][c] } } } var sum = 0 for (i in 0 until row) { for (j in 0 until column) { if (field[i][j]) sum++ } } return sum } fun getScenicScore(r: Int, c: Int, input: Array<IntArray>): Long { val v = input[r][c] val row = input.size val column = input[0].size var left = 0L for (i in c - 1 downTo 0) { left++ if (input[r][i] >= v) break } var right = 0L for (i in c + 1 until column) { right++ if (input[r][i] >= v) break } var top = 0L for (i in r - 1 downTo 0) { top++ if (input[i][c] >= v) break } var down = 0L for (i in r + 1 until row) { down++ if (input[i][c] >= v) break } return left * right * top * down } fun part2(input: Array<IntArray>): Long { val row = input.size val column = input[0].size var score = 0L for (r in 0 until row) { for (c in 0 until column) { val currentScore = getScenicScore(r, c, input) score = score.coerceAtLeast(currentScore) } } return score } check(part1(parseArray(readInput("Day08_test"))) == 21) println(part1(parseArray(readInput("Day08")))) check(part2(parseArray(readInput("Day08_test"))) == 8L) println(part2(parseArray(readInput("Day08")))) }
0
Kotlin
0
0
e5f13dae0d2fa1aef14dc71c7ba7c898c1d1a5d1
3,272
AdventOfCode-2022
Apache License 2.0