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/com/github/solairerove/algs4/leprosorium/sorting/MergeSortBU.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.sorting import kotlin.math.min fun main() { val items = mutableListOf(5, 6, 4, 3, 10, 9, 5, 6, 7) print("items: $items \n") mergeSort(items) print("items: $items \n") } // O(nlog(n)) time | O(n) space private fun mergeSort(arr: MutableList<Int>) { val n = arr.size val aux = MutableList(n) { i -> i } var len = 1 while (len < n) { for (low in 0 until n - len step 2 * len) { val mid = low + len - 1 val high = min(low + 2 * len - 1, n - 1) merge(arr, aux, low, mid, high) } len *= 2 } } private fun merge(arr: MutableList<Int>, aux: MutableList<Int>, low: Int, mid: Int, high: Int) { for (k in low..high) { aux[k] = arr[k] } var i = low var j = mid + 1 for (k in low..high) { when { i > mid -> arr[k] = aux[j++] j > high -> arr[k] = aux[i++] aux[j] < aux[i] -> arr[k] = aux[j++] else -> arr[k] = aux[i++] } } }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,059
algs4-leprosorium
MIT License
hacker-rank/sorting/MergeSortCountingInversions.kt
piazentin
62,427,919
false
{"Python": 34824, "Jupyter Notebook": 29307, "Kotlin": 19570, "C++": 2465, "R": 2425, "C": 158}
import java.lang.StringBuilder private fun IntArray.toNiceString(): String { val sb = StringBuilder().append("[") this.forEach { sb.append(it).append(",") } if (sb.length > 1) sb.deleteCharAt(sb.lastIndex).append("]") return sb.toString() } private val IntRange.size: Int get() = this.last - this.first private val IntRange.half: Int get() = this.first + (this.size / 2) fun main() { val queries = readLine().orEmpty().trim().toInt() val arrays = Array(queries) { readLine() // ignore first line readLine().orEmpty().trim().split(" ").map { l -> l.toInt() }.toIntArray() } arrays.forEach { println(countSwaps(it)) } } fun countSwaps(array: IntArray): Long { return sort(array, 0 .. array.size, IntArray(array.size)) } fun sort(array: IntArray, range: IntRange, temp: IntArray): Long { if (range.size <= 1) return 0 val leftHalf = range.first .. range.half val rightHalf = range.half .. range.last return sort(array, leftHalf, temp) + sort(array, rightHalf, temp) + merge(array, leftHalf, rightHalf, temp) } fun merge(array: IntArray, leftHalf: IntRange, rightHalf: IntRange, temp: IntArray): Long { var left = leftHalf.first var right = rightHalf.first var index = left var swaps = 0L while (left < leftHalf.last && right < rightHalf.last) { if (array[left] <= array[right]) temp[index] = array[left++] else { swaps += right - index temp[index] = array[right++] } index++ } while (left < leftHalf.last) temp[index++] = array[left++] while (right < rightHalf.last) temp[index++] = array[right++] for (i in leftHalf.first until rightHalf.last) array[i] = temp[i] return swaps }
0
Python
0
0
db490b1b2d41ed6913b4cacee1b4bb40e15186b7
1,776
programming-challenges
MIT License
2023/src/main/kotlin/Day21.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import java.util.* object Day21 { fun part1(input: String, steps: Int): Long { check(steps % 2 == 0) { "Number of steps must be even" } val (grid, start) = parse(input) return explore(grid, start, steps).even } fun part2(input: String, steps: Int): Long { val (grid, start) = parse(input) // This algorithm relies on certain properties of the input; define them via checks check(steps % 2 == 1) { "Number of steps must be odd" } check(grid.size == grid[0].length) { "Input grid must be square" } check(grid.size % 2 == 1) { "Grid size must be odd" } check(start.x == grid.size / 2 && start.y == grid.size / 2) { "Start must be in center of square" } check((start.x + start.y) % 2 == 0) { "Start must be an even position" } check(steps % grid.size == grid.size / 2) { "Num steps allows one to go straight to the center of another square" } check(grid.first().all { it != '#' }) { "Horizontal top line must be clear of rocks" } check(grid[grid.size / 2].all { it != '#' }) { "Horizontal midline must be clear of rocks" } check(grid.last().all { it != '#' }) { "Horizontal bottom line must be clear of rocks" } check(grid.all { it[grid.size / 2] != '#' }) { "Vertical midline must be clear of rocks" } check(grid.all { it.first() != '#' }) { "Vertical left line must be clear of rocks" } check(grid.all { it.last() != '#' }) { "Vertical right line must be clear of rocks" } // FYI, there must be a clear diamond shape inside as well, no easy way to check though // Pre-calculate all the possible grids (named on where you start) val tipSteps = grid.size - 1 val smallCornerSteps = grid.size / 2 val largeCornerSteps = (grid.size - 1) + (grid.size / 2) val filled = explore(grid, Pos(start.x, 130), Int.MAX_VALUE) val north = explore(grid, Pos(start.x, 0), tipSteps) val northEastSmall = explore(grid, Pos(grid.size - 1, 0), smallCornerSteps) val northEastLarge = explore(grid, Pos(grid.size - 1, 0), largeCornerSteps) val east = explore(grid, Pos(grid.size - 1, start.y), tipSteps) val southEastSmall = explore(grid, Pos(grid.size - 1, grid.size - 1), smallCornerSteps) val southEastLarge = explore(grid, Pos(grid.size - 1, grid.size - 1), largeCornerSteps) val south = explore(grid, Pos(start.x, grid.size - 1), tipSteps) val southWestSmall = explore(grid, Pos(0, grid.size - 1), smallCornerSteps) val southWestLarge = explore(grid, Pos(0, grid.size - 1), largeCornerSteps) val west = explore(grid, Pos(0, start.y), tipSteps) val northWestSmall = explore(grid, Pos(0, 0), smallCornerSteps) val northWestLarge = explore(grid, Pos(0, 0), largeCornerSteps) // Calculate number of each type of grid based on number of grids traveled val numGridsTraveled = (steps / grid.size).toLong() // One of each tip val tips = north.odd + south.odd + west.odd + east.odd // Small corners val smallCorners = numGridsTraveled * (northEastSmall.even + southEastSmall.even + southWestSmall.even + northWestSmall.even) // Large corners val largeCorners = (numGridsTraveled - 1) * (northEastLarge.odd + southEastLarge.odd + southWestLarge.odd + northWestLarge.odd) // Number of odd and even filled grids val numOddFilledGrids = (numGridsTraveled - 1) * (numGridsTraveled - 1) val numEvenFilledGrids = numGridsTraveled * numGridsTraveled // Sum it all up return (numOddFilledGrids * filled.odd) + (numEvenFilledGrids * filled.even) + tips + smallCorners + largeCorners } private fun explore(grid: List<String>, start: Pos, steps: Int): Stats { val queue = ArrayDeque<Step>() queue.add(Step(start, steps)) val visited = HashSet<Pos>() while (queue.isNotEmpty()) { val (pos, stepsRemaining) = queue.poll() if (pos in visited) { continue } visited.add(pos) if (stepsRemaining == 0) { continue } queue.addAll( Direction.entries .map { pos.move(it) } .filter { it !in visited && it.x in grid[0].indices && it.y in grid.indices && grid[it.y][it.x] != '#' } .map { Step(it, stepsRemaining - 1) } ) } val oddCount = visited.count { it.isOdd() }.toLong() return Stats(odd = oddCount, even = visited.size - oddCount) } private data class Pos(val x: Int, val y: Int) { fun move(direction: Direction) = when (direction) { Direction.NORTH -> copy(y = y - 1) Direction.EAST -> copy(x = x + 1) Direction.SOUTH -> copy(y = y + 1) Direction.WEST -> copy(x = x - 1) } // Note that this is relative based on the starting position of the walk fun isOdd() = (x + y) % 2 == 1 } private enum class Direction { NORTH, EAST, SOUTH, WEST } private data class Step(val pos: Pos, val count: Int) private data class Stats(val even: Long, val odd: Long) private data class Config(val grid: List<String>, val start: Pos) private fun parse(input: String): Config { val grid = input.splitNewlines() val start = grid.indices.firstNotNullOf { y -> val x = grid[y].indexOf('S') if (x == -1) null else Pos(x, y) } return Config(grid, start) } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
5,237
advent-of-code
MIT License
src/main/kotlin/day08/map.kt
cdome
726,684,118
false
{"Kotlin": 17211}
package day08 import java.io.File fun main() { val file = File("src/main/resources/day08-map").readLines() val instructions = file[0] val map = file.stream().skip(2).map { line -> val (def, dirs) = line.split(" = ") val (l, r) = dirs.split(", ") def.trim() to Pair(l.removePrefix("("), r.removeSuffix(")")) }.toList().toMap() fun step(steps: Long, current: String): String { val direction = instructions[(steps % instructions.length).toInt()] return if (direction == 'L') map[current]!!.first else map[current]!!.second } var steps = 0L var current = "AAA" while (current != "ZZZ") { current = step(steps++, current) } println("Steps: $steps") val stepsList = map.keys .filter { it.endsWith("A") } .map { steps = 0 current = it while (!current.endsWith("Z")) { current = step(steps++, current) } steps } val lcm = stepsList.reduce { acc, i -> lcm(acc, i) } println("Simultaneous Steps: $lcm") } fun lcm(a: Long, b: Long): Long = a * b / gcd(a, b) fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
0
Kotlin
0
0
459a6541af5839ce4437dba20019b7d75b626ecd
1,228
aoc23
The Unlicense
test/leetcode/NestingDepthOfParentheses.kt
andrej-dyck
340,964,799
false
null
package leetcode import lib.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.* import org.junit.jupiter.params.provider.* /** * https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/ * * 1614. Maximum Nesting Depth of the Parentheses * [Easy] * * A string is a valid parentheses string (denoted VPS) if it meets one of the following: * * It is an empty string "", or a single character not equal to "(" or ")", * It can be written as AB (A concatenated with B), where A and B are VPS's, or * It can be written as (A), where A is a VPS. * * We can similarly define the nesting depth depth(S) of any VPS S as follows: * - depth("") = 0 * - depth(C) = 0, where C is a string with a single character not equal to "(" or ")". * - depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's. * - depth("(" + A + ")") = 1 + depth(A), where A is a VPS. * * For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), * and ")(" and "(()" are not VPS's. * * Given a VPS represented as string s, return the nesting depth of s. * * Constraints * - 1 <= s.length <= 100 * - s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'. * - It is guaranteed that parentheses expression s is a VPS. */ fun maxNestingDepth(vps: String) = vps .map { when (it) {'(' -> 1; ')' -> -1; else -> 0 } } .runningReduce(Int::plus) .maxOr { 0 } /** * Unit tests */ class NestingDepthOfParenthesesTest { @ParameterizedTest @CsvSource( "1, 0", "(1), 1", "(1+(2*3)+((8)/4))+1, 3", "(1)+((2))+(((3))), 3", "1+(2*3)/(2-1), 1" ) fun `max nesting depth of parentheses`(text: String, expectedDepth: Int) { assertThat( maxNestingDepth(text) ).isEqualTo( expectedDepth ) } }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
1,884
coding-challenges
MIT License
2021/five.kt
charlottemach
433,765,865
false
{"D": 7911, "Haxe": 5698, "Go": 5682, "Julia": 5361, "R": 5032, "Kotlin": 4670, "Dockerfile": 4516, "C++": 4312, "Haskell": 4113, "Scala": 4080, "OCaml": 3901, "Raku": 3680, "Erlang": 3436, "Swift": 2863, "Groovy": 2861, "Vala": 2845, "JavaScript": 2735, "Crystal": 2210, "Python": 2197, "Clojure": 2172, "Ruby": 2163, "Perl": 2035, "Rust": 2018, "C": 1649, "Nim": 1611, "PHP": 1562, "Java": 1516, "Awk": 1204, "Dart": 1198, "Elixir": 1120, "Racket": 841, "Standard ML": 824, "Shell": 152}
import java.io.File import kotlin.math.abs fun main() { val input = File("five.txt").readText() val coord = input.trim().split("\n").map{ it.split(" -> ")} val mat = Array(1000) {Array(1000) {0} } //val mat = Array(10) {Array(10) {0} } for (c in coord) { val start = c.first().split(","); val stop = c.last().split(",") val x1 = start.first().toInt(); val y1 = start.last().toInt() val x2 = stop.first().toInt(); val y2 = stop.last().toInt() if (x1 == x2) { val mnY = minOf(y1,y2); val mxY = maxOf(y1,y2) for (y in mnY..mxY) { mat[y][x1] += 1 } } else if (y1 == y2) { val mnX = minOf(x1,x2); val mxX = maxOf(x1,x2) for (x in mnX..mxX) { mat[y1][x] += 1 } // Part B } else { for (i in 0..abs(x1-x2)) { if (y1 < y2) { if (x1 < x2) { mat[y1 + i][x1 + i] += 1 } else { mat[y1 + i][x1 - i] += 1 } } else { if (x1 < x2) { mat[y1 - i][x1 + i] += 1 } else { mat[y1 - i][x1 - i] += 1 } } } } } //mPrint(mat) print(mCount(mat)) } fun mPrint(mat: Array<Array<Int>>) { for (array in mat) { for (value in array) { print(value) } println() } } fun mCount(mat: Array<Array<Int>>) : Int { var count = 0 for (array in mat) { for (value in array) { if (value >= 2){ count += 1 } } } return(count) }
0
D
0
0
dc839943639282005751b68a7988890dadf00f41
1,793
adventofcode
Apache License 2.0
src/Lesson7StacksAndQueues/Brackets.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
import java.util.Stack /** * 100/100 * @param S * @return */ fun solution(S: String): Int { if (S.length == 0) return 1 if (S.length % 2 != 0) return 0 val stack: Stack<Char> = Stack<Char>() for (i in 0 until S.length) { val character = S[i] when (character) { ')' -> if (!stack.isEmpty() && stack.peek() == '(') { stack.pop() } else { return 0 } ']' -> if (!stack.isEmpty() && stack.peek() == '[') { stack.pop() } else { return 0 } '}' -> if (!stack.isEmpty() && stack.peek() == '{') { stack.pop() } else { return 0 } else -> stack.push(character) } } return if (stack.size == 0) { 1 } else 0 } /** * A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: * * S is empty; * S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; * S has the form "VW" where V and W are properly nested strings. * For example, the string "{[()()]}" is properly nested but "([)()]" is not. * * Write a function: * * class Solution { public int solution(String S); } * * that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise. * * For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [0..200,000]; * string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")". */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
1,794
Codility-Kotlin
Apache License 2.0
src/Lesson4CountingElements/PermCheck.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
/** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { val uniqueCheck = IntArray(A.size) for (i in A.indices) { val current = A[i] - 1 if (A[i] > A.size) return 0 uniqueCheck[current]++ if (uniqueCheck[current] > 1) return 0 } return 1 } /** * A non-empty array A consisting of N integers is given. * * A permutation is a sequence containing each element from 1 to N once, and only once. * * For example, array A such that: * * A[0] = 4 * A[1] = 1 * A[2] = 3 * A[3] = 2 * is a permutation, but array A such that: * * A[0] = 4 * A[1] = 1 * A[2] = 3 * is not a permutation, because value 2 is missing. * * The goal is to check whether array A is a permutation. * * Write a function: * * class Solution { public int solution(int[] A); } * * that, given an array A, returns 1 if array A is a permutation and 0 if it is not. * * For example, given array A such that: * * A[0] = 4 * A[1] = 1 * A[2] = 3 * A[3] = 2 * the function should return 1. * * Given array A such that: * * A[0] = 4 * A[1] = 1 * A[2] = 3 * the function should return 0. * * 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 within the range [1..1,000,000,000]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
1,401
Codility-Kotlin
Apache License 2.0
2021/src/test/kotlin/Day14.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import java.lang.IllegalStateException import kotlin.test.Test import kotlin.test.assertEquals class Day14 { @Test fun `run part 01`() { val (template, insertions) = getInstructions() val result = template .toInitialPairs() .processPairInsertions(insertions, 10) .calcCommonElementsDiff() assertEquals(2435, result) } @Test fun `run part 02`() { val (template, insertions) = getInstructions() val result = template .toInitialPairs() .processPairInsertions(insertions, 40) .calcCommonElementsDiff() assertEquals(2587447599164, result) } private fun String.toInitialPairs() = this.windowed(2, 1).associateWith { 1L } private fun Map<String, Long>.processPairInsertions(insertions: Map<String, Char>, steps: Int) = generateSequence(this) { pairs -> pairs .flatMap { val insert = insertions[it.key]?.toString() ?: throw IllegalStateException() listOf( (it.key.first() + insert) to it.value, (insert + it.key.last()) to it.value ) } .groupBy { it.first } .map { it.key to it.value.sumOf { count -> count.second } } .toMap() } .take(steps.inc()) .last() private fun Map<String, Long>.calcCommonElementsDiff() = this .map { it.key.last() to it.value } .groupBy { it.first } // This is not completely correct, the totals for the first pair should be counted for both characters. // Fortunately, by chance, the first character is not the one we are interested in, so fine here. .map { it.key to it.value.sumOf { count -> count.second } } .let { it.maxOf { count -> count.second } - it.minOf { count -> count.second } } private fun getInstructions() = Util.getInputAsListOfString("day14-input.txt") .let { paper -> paper.mapNotNull { if (!it.contains("->")) it else null } .single { it.isNotEmpty() } to paper.mapNotNull { if (it.contains("->")) it .split("->") .let { s -> Pair(s[0].trim(), s[1].trim().first()) } else null } .toMap() } }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,569
adventofcode
MIT License
src/main/kotlin/common/Utils.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package common import common.Collections.transpose import common.Misc.next import common.Space2D.Direction.* import common.Space2D.Point import common.Space2D.toLoggable import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import java.math.BigInteger import java.security.MessageDigest import java.util.* import kotlin.math.absoluteValue import kotlin.math.sign object Math { fun List<Long>.toLowestCommonMultiple(): Long = this.fold(first()) { acc, l -> lowestCommonMultiple(acc, l) } private fun lowestCommonMultiple(x: Long, y: Long): Long { val increment = maxOf(x, y) val maxCommonMultiple = x * y return generateSequence(increment) { current -> when { current >= maxCommonMultiple || current.isCommonMultipleOf(x, y) -> null else -> current + increment } }.last() } private fun Long.isCommonMultipleOf(x: Long, y: Long): Boolean = this % x == 0L && this % y == 0L } object Space3D { enum class Direction3D { Right, Down, Left, Up, Forward, Back } data class Point3D( val x: Int, val y: Int, val z: Int, ) { fun move(direction3D: Direction3D, by: Int = 1): Point3D = when (direction3D) { Direction3D.Up -> copy(y = y + by) Direction3D.Right -> copy(x = x + by) Direction3D.Down -> copy(y = y - by) Direction3D.Left -> copy(x = x - by) Direction3D.Forward -> copy(z = z + by) Direction3D.Back -> copy(z = z - by) } fun neighbors(): Set<Point3D> = Direction3D.entries.map { this.move(it) }.toSet() } object Parser { fun String.toPoint3D(): Point3D = this.split(",") .map { it.filter { it.isDigit() || it == '-' }.toInt() } .let { Point3D(it[0], it[1], it[2]) } fun Regex.valuesFor(input: String): List<String> = find(input)?.groupValues?.drop(1)!! } } object Space2D { object Parser { fun String.toPoint(): Point = this.split(",") .map { it.filter { it.isDigit() || it == '-' }.toInt() } .let { Point(it[0], it[1]) } fun List<String>.toPointToChars(): List<Pair<Point, Char>> { val max = this.size return mapIndexed { y, s -> s.mapIndexed { x, c -> Pair(Point(x, max - y), c) } }.flatten() } fun List<String>.toPointChars(): List<PointChar> { val max = this.size return mapIndexed { y, s -> s.mapIndexed { x, c -> PointChar(Point(x, max - y), c) } }.flatten() } } data class PointChar(val point: Point, val char: Char) fun List<PointChar>.getFor(point: Point): PointChar? = this.singleOrNull { it.point == point } enum class Direction { East, South, West, North; } fun Direction.opposite(): Direction = when (this) { East -> West South -> North West -> East North -> South } val clockWiseDirections = listOf(East, South, West, North) fun Direction.turn(side: Side): Direction = clockWiseDirections.let { val i = it.indexOf(this) + side.toInt() it[(i % it.size + it.size) % it.size] } private fun Side.toInt(): Int = when (this) { Side.Right -> +1 Side.Left -> -1 } enum class Side { Right, Left } data class Point( val x: Int, val y: Int ) : Comparable<Point> { fun move(direction: Direction, by: Int = 1): Point = when (direction) { North -> copy(y = y + by) East -> copy(x = x + by) South -> copy(y = y - by) West -> copy(x = x - by) } fun adjacent(): Set<Point> = Direction.entries.map { this.move(it) }.toSet() fun adjacentWithDiagonal(): Set<Point> = Direction.entries.flatMap { direction -> this.move(direction).let { moved -> listOf(moved) + listOf(moved.move(direction.next())) } }.toSet() fun distanceTo(other: Point): Int = listOf(x - other.x, y - other.y).map { it.absoluteValue }.sum() fun directionTo(other: Point): Direction { val xDelta = (other.x - x).sign val yDelta = (other.y - y).sign return when { yDelta > 0 -> North xDelta > 0 -> East yDelta < 0 -> South xDelta < 0 -> West else -> error("no direction") } } fun lineTo(other: Point): List<Point> { val steps = this.distanceTo(other) val direction = this.directionTo(other) return (1..steps).scan(this) { last, _ -> last.move(direction) } } operator fun plus(other: Point): Point = Point(this.x + other.x, this.y + other.y) operator fun minus(other: Point): Point = Point(this.x - other.x, this.y - other.y) override fun compareTo(other: Point): Int = y.compareTo(other.y) .takeIf { it != 0 } ?: x.compareTo(other.x) } context(Collection<Point>) private fun Point.isEdge(): Boolean = this in toMaxPoints() context(Collection<Point>) fun Point.nextIn(direction: Direction): Point? = when (direction) { East -> filter { it.y == this.y && it.x > this.x }.minByOrNull { it.x } South -> filter { it.x == this.x && it.y < this.y }.maxByOrNull { it.y } West -> filter { it.y == this.y && it.x < this.x }.maxByOrNull { it.x } North -> filter { it.x == this.x && it.y > this.y }.minByOrNull { it.y } } context(Collection<Point>) fun Point.lastIn(direction: Direction): Point = when (direction) { East -> Point(Axis.X.max(), this.y) South -> Point(this.x, Axis.Y.min()) West -> Point(Axis.X.min(), this.y) North -> Point(this.x, Axis.Y.max()) } val Collection<Point>.topLeft: Point get() = Point( x = Axis.X.min(), y = Axis.Y.max() ) val Collection<Point>.bottomRight: Point get() = Point( x = Axis.X.max(), y = Axis.Y.min() ) enum class Axis { X, Y } context(Collection<Point>) fun Axis.toRange(): IntRange { return min()..max() } context(Collection<Point>) fun Axis.min(): Int = minByOrNull { it.axisValue(this) }?.axisValue(this) ?: 0 context(Collection<Point>) fun Axis.max(): Int = maxByOrNull { it.axisValue(this) }?.axisValue(this) ?: 0 private fun Point.axisValue(axis: Axis): Int = when (axis) { Axis.X -> this.x Axis.Y -> this.y } fun Collection<Point>.toLoggable( highlight: Set<Point>? = null, highlightWith: String = "*", edges: Set<Point> = emptySet(), showEdge: Boolean = false ): String { return Axis.Y.toRange().reversed().joinToString(System.lineSeparator()) { y -> Axis.X.toRange().joinToString("") { x -> val point = Point(x, y) when { highlight?.contains(point) == true -> highlightWith point in this -> "#" point in edges -> when { showEdge -> "#" else -> "." } else -> "." } } } } fun Map<Point, Char>.toLoggable( highlight: Set<Point>? = null, highlightWith: String = "*", ): String { return with(this.keys) { Axis.Y.toRange().reversed().joinToString(System.lineSeparator()) { y -> Axis.X.toRange().joinToString("") { x -> val point = Point(x, y) when { highlight?.contains(point) == true -> highlightWith else -> this@toLoggable[point].toString() } } } } } interface HasPoints { val points: Collection<Point> fun move(direction: Direction, by: Int = 1): HasPoints fun Collection<Point>.move(direction: Direction, by: Int = 1): Collection<Point> = map { it.move(direction, by) } } fun Collection<Point>.height(): Int = maxOf { it.y } fun Collection<Point>.toEdges(): Collection<Point> { val minX = this.minOfOrNull { it.x } val maxX = this.maxOfOrNull { it.x } val minY = this.minOfOrNull { it.y } val maxY = this.maxOfOrNull { it.y } return toMaxPoints().filter { it.x == minX || it.x == maxX || it.y == minY || it.y == maxY } } fun Collection<Point>.toMaxPoints(): Collection<Point> { val minX = this.minOfOrNull { it.x } ?: return this val maxX = this.maxOfOrNull { it.x } ?: return this val minY = this.minOfOrNull { it.y } ?: return this val maxY = this.maxOfOrNull { it.y } ?: return this return (minX..maxX).flatMap { x -> (minY..maxY).map { y -> Point(x, y) } } } } object Collections { inline fun <reified T> List<List<T>>.transpose(): List<List<T>> { val cols = this[0].size val rows = size return Array(cols) { j -> Array(rows) { i -> this[i][j] }.toList() }.toList() } fun List<String>.partitionedBy(delimiter: String): List<List<String>> { val indexes = this.indexesOf(delimiter) .takeIf { it.isNotEmpty() } ?: return listOf(this) val first = this.subList(0, indexes.first()) val last = this.subList(indexes.last() + 1, this.lastIndex + 1) return listOf(first) + partitionAt(indexes) + listOf(last) } private fun <T> List<T>.indexesOf(delimiter: T) = mapIndexedNotNull { index, t -> index.takeIf { t == delimiter } } private fun <T> List<T>.partitionAt(indexes: List<Int>): List<List<T>> = indexes.zipWithNext { a, b -> this.subList(a + 1, b) } fun List<Int>.product(): Int = reduce { acc, i -> acc * i } fun List<Long>.product(): Long = reduce { acc, i -> acc * i } } object Misc { fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16).padStart(32, '0') fun <T> T.log(): T = also { println("") if (this is Iterable<*>) this.forEach { println(it) } else println(this) } fun String.capitalise(): String = this.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } inline fun <reified T : Enum<T>> T.next(): T { val values = enumValues<T>() val nextOrdinal = (ordinal + 1) % values.size return values[nextOrdinal] } fun String.assertEqualTo(other: String) { // https://stackoverflow.com/questions/10934743/formatting-output-so-that-intellij-idea-shows-diffs-for-two-texts error("expected: $other but was: $this") } } object Maps { infix fun <T> Map<T, Int>.plusInt(other: Map<T, Int>): Map<T, Int> = this.operate(other) { first, second -> first + second } infix fun <T> Map<T, Int>.minusInt(other: Map<T, Int>): Map<T, Int> = this.operate(other) { first, second -> first - second } private fun <T> Map<T, Int>.operate(other: Map<T, Int>, fn: (Int, Int) -> Int): Map<T, Int> = this.map { it.key to fn(it.value, other.getOrDefault(it.key, 0)) }.toMap() } object Monitoring { interface Monitor<T> : (T) -> Unit { fun toLoggable(): List<String> } class PointCharMonitor( private val canvas: Map<Point, Char> = mapOf(), private val edges: Set<Point> = setOf(), private val highlightWith: String = "*", ) : Monitor<Map<Point, Char>> { private val frames: MutableList<Set<Point>> = mutableListOf() override fun toLoggable(): List<String> = frames.map { frame -> canvas.toLoggable( highlight = frame, highlightWith = highlightWith, ) } override fun invoke(p1: Map<Point, Char>) { TODO("Not yet implemented") } operator fun invoke(frame: Set<Point>) { frames.add(frame) } } open class PointMonitor( private val canvas: Set<Point> = setOf(), private val edges: Set<Point> = setOf(), private val highlightWith: String = "*", private val showEdge: Boolean = false, ) : Monitor<Set<Point>> { private val frames: MutableList<Set<Point>> = mutableListOf() override fun invoke(frame: Set<Point>) { this.frames += frame } override fun toLoggable(): List<String> = frames.map { frame -> (this.canvas).toLoggable( highlight = frame, highlightWith = highlightWith, edges = edges, showEdge = showEdge, ) } } } object Strings { fun String.replaceFirst(toReplace: Char, replacement: Char): String = replaceAt(this.indexOfFirst { it == toReplace }, replacement) fun String.replaceAt(index: Int, replacement: Char) = this.substring(0, index) + replacement + this.substring(index + 1) fun List<String>.transpose(): List<String> = map { it.toList() } .transpose() .map { it.joinToString() } } object Parallel { fun <T> Iterable<T>.forEachParallel(fn: suspend (T) -> Unit): Unit = runBlocking { forEach { async(Dispatchers.Default) { fn(it) } } } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
14,401
aoc
Apache License 2.0
algorithms/src/main/kotlin/com/thepyprogrammer/ktlib/math/types/Complex.kt
terminalai
312,471,067
false
null
package com.thepyprogrammer.ktlib.math.types import kotlin.math.* data class Complex(val re: Double, val im: Double = 0.0, val isUnit: Boolean = false) { constructor(value: Complex): this(value.re, value.im, value.isUnit) constructor(mag: Double, arg: Angle) : this(cos(arg.angle) * mag, sin(arg.angle) * mag, mag == 1.0) infix operator fun plus(x: Complex) = Complex(re + x.re, im + x.im) infix operator fun plus(x: Double) = Complex(re + x, im) infix operator fun plus(x: Float) = Complex(re + x.toDouble(), im) infix operator fun plus(x: Int) = Complex(re + x, im) infix operator fun minus(x: Complex) = Complex(re - x.re, im - x.im) infix operator fun minus(x: Double) = Complex(re - x, im) infix operator fun minus(x: Float) = Complex(re - x.toDouble(), im) infix operator fun minus(x: Int) = Complex(re - x, im) infix operator fun times(x: Double) = Complex(re * x, im * x) infix operator fun times(x: Int) = Complex(re * x, im * x) infix operator fun times(x: Float) = times(x.toDouble()) infix operator fun times(x: Complex) = Complex(re * x.re - im * x.im, re * x.im + im * x.re) infix operator fun div(x: Double) = Complex(re / x, im / x) infix operator fun div(x: Float) = div(x.toDouble()) infix operator fun div(x: Int) = Complex(re / x, im / x) infix operator fun div(x: Complex) = Complex(mag / x.mag, arg - x.arg) val exp by lazy { Complex( cos(im), sin(im) ) * ( cosh(re) + sinh(re) ) } var timesConj = re * re + im * im var mag = sqrt(timesConj) var unit = if (!isUnit) if (mag != 0.0) Complex(re / mag, im / mag, true) else Complex(0.0, 0.0, true) else this var alpha = abs(asin(unit.im)) var arg = Angle( when { (im == 0.0 && re >= 0) -> 0.0 (im == 0.0 && re < 0) -> com.thepyprogrammer.ktlib.math.PI (re == 0.0 && im > 0) -> com.thepyprogrammer.ktlib.math.PI / 2 (re == 0.0 && im < 0) -> -com.thepyprogrammer.ktlib.math.PI / 2 (re > 0 && im > 0) -> alpha (re > 0 && im < 0) -> -alpha (re < 0 && im > 0) -> com.thepyprogrammer.ktlib.math.PI - alpha else -> alpha - com.thepyprogrammer.ktlib.math.PI } ) override fun toString() = when { b == "0.000" -> a a == "0.000" -> b + 'i' im > 0 -> a + " + " + b + 'i' else -> a + " - " + b + 'i' } private val a = "%1.3f".format(re) private val b = "%1.3f".format(abs(im)) }
1
Jupyter Notebook
4
10
2064375ddc36bf38f3ff65f09e776328b8b4612a
2,578
GaitMonitoringForParkinsonsDiseasePatients
MIT License
src/Day11.kt
roxanapirlea
572,665,040
false
{"Kotlin": 27613}
import kotlin.math.floor private enum class Operation { MULTIPLY, ADD, SQUARE } private data class Monkey( val items: MutableList<Long> = mutableListOf(), val operation: Pair<Operation, Int> = Pair(Operation.ADD, 0), val testDivider: Int = 1, val monkeyTrue: Int = -1, val monkeyFalse: Int = -1 ) fun main() { fun List<String>.monkeyList(): List<Monkey> { val monkeys = mutableListOf<Monkey>() var monkey = Monkey() forEach { line -> val trimmed = line.trim() if (trimmed.isEmpty()) { monkeys.add(monkey) } else if (trimmed.startsWith("Starting items: ")) { val items = trimmed.substringAfter(": ") .split(", ") .map { it.toLong() } .toMutableList() monkey = monkey.copy(items = items) } else if (trimmed.startsWith("Operation: ")) { val (opType, opValue) = trimmed.split(" ").takeLast(2) monkey = when (opType) { "+" -> monkey.copy(operation = Pair(Operation.ADD, opValue.toInt())) "*" -> if (opValue == "old") monkey.copy(operation = Pair(Operation.SQUARE, 1)) else monkey.copy(operation = Pair(Operation.MULTIPLY, opValue.toInt())) else -> throw IllegalArgumentException() } } else if (trimmed.startsWith("Test: ")) monkey = monkey.copy(testDivider = trimmed.split(" ").last().toInt()) else if (trimmed.startsWith("If true: ")) monkey = monkey.copy(monkeyTrue = trimmed.split(" ").last().toInt()) else if (trimmed.startsWith("If false: ")) monkey = monkey.copy(monkeyFalse = trimmed.split(" ").last().toInt()) else if (trimmed.startsWith("Monkey")) { monkey = Monkey() } else throw IllegalArgumentException() } monkeys.add(monkey) return monkeys } fun List<Monkey>.visit(): Long { val visits = MutableList(size) { 0 } repeat(20) { for (i in indices) { val items = this[i].items val newItems = items.map { item -> val worry = when (this[i].operation.first) { Operation.MULTIPLY -> item * this[i].operation.second Operation.ADD -> item + this[i].operation.second Operation.SQUARE -> item * item } val newItem = floor(worry / 3.0).toLong() val testTrue = newItem % this[i].testDivider == 0L newItem to testTrue } this[this[i].monkeyTrue].items.addAll(newItems.filter { it.second }.map { it.first }) this[this[i].monkeyFalse].items.addAll(newItems.filter { !it.second }.map { it.first }) visits[i] = visits[i] + this[i].items.size this[i].items.clear() } } val (max1, max2) = visits.sortedDescending().take(2) return max1.toLong() * max2.toLong() } fun List<Monkey>.visitPart2(): Long { val totalDivider = this.map { it.testDivider }.reduce { acc, d -> acc * d } val visits = MutableList(size) { 0 } repeat(10000) { for (i in indices) { val items = this[i].items val newItems = items.map { item -> var remainder = item when (this[i].operation.first) { Operation.MULTIPLY -> { remainder *= this[i].operation.second if (remainder > totalDivider) { remainder %= totalDivider } } Operation.ADD -> { remainder += this[i].operation.second if (remainder > totalDivider) { remainder -= totalDivider } } Operation.SQUARE -> { remainder *= remainder } } val testTrue = remainder % this[i].testDivider == 0L remainder to testTrue } this[this[i].monkeyTrue].items.addAll(newItems.filter { it.second }.map { it.first }) this[this[i].monkeyFalse].items.addAll(newItems.filter { !it.second }.map { it.first }) visits[i] = visits[i] + this[i].items.size this[i].items.clear() } } val (max1, max2) = visits.sortedDescending().take(2) return max1.toLong() * max2.toLong() } fun part1(input: List<String>): Long { return input.monkeyList().visit() } fun part2(input: List<String>): Long { return input.monkeyList().visitPart2() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6c4ae6a70678ca361404edabd1e7d1ed11accf32
5,459
aoc-2022
Apache License 2.0
src/test/kotlin/be/brammeerten/y2022/Day14Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2022 import be.brammeerten.Co import be.brammeerten.readFile import be.brammeerten.y2022.Tile.* import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import kotlin.math.max import kotlin.math.min class Day14Test { @Test fun `part 1a`() { val map = Cave(scanCave("2022/day14/exampleInput.txt")) simulate(map, print = true) Assertions.assertEquals(24, map.sandCount()) } @Test fun `part 1b`() { val map = Cave(scanCave("2022/day14/input.txt")) simulate(map) Assertions.assertEquals(592, map.sandCount()) } @Test fun `part 2a`() { val map = Cave(scanCave("2022/day14/exampleInput.txt"), infiniteFloor = true) simulate(map, print = true) Assertions.assertEquals(93, map.sandCount()) } @Test fun `part 2b`() { val map = Cave(scanCave("2022/day14/input.txt"), infiniteFloor = true) simulate(map) Assertions.assertEquals(30367, map.sandCount()) } } val DOWN_LEFT = Co.DOWN + Co.LEFT val DOWN_RIGHT = Co.DOWN + Co.RIGHT fun simulate(cave: Cave, print: Boolean = false) { var sand = cave.source while (cave.isInBounds(sand)) { val tryDirections = listOf(Co.DOWN, DOWN_LEFT, DOWN_RIGHT) var direction: Co? = null for (dir in tryDirections) { if (!cave.isInBounds(sand + dir) || cave[sand + dir] == AIR) { direction = dir break } } if (direction == null) { cave[sand] = SAND if (print) cave.print() if (sand == cave.source) break else sand = cave.source } else { sand += direction } } } fun scanCave(file: String): List<List<Pair<Int, Int>>> { return readFile(file) .map { it.split(" -> ") } .map { cos -> cos.map { it.split(",")[0].toInt() to it.split(",")[1].toInt() } } } class Cave(scans: List<List<Pair<Int, Int>>>, val infiniteFloor: Boolean = false) { val source: Co = Co(0, 500) val map: HashMap<Co, Tile> = HashMap() val bottomFloor: Int init { var topLeft = source var bottomRight = source val rocks = scans.flatMap { it .windowed(2) .flatMap { (p1, p2) -> if (p1.first == p2.first) (min(p1.second, p2.second)..max(p1.second, p2.second)) .map { sec -> p1.first to sec } else (min(p1.first, p2.first)..max(p1.first, p2.first)) .map { first -> first to p1.second } } }.map { (col, row) -> Co(row, col) } rocks.forEach { co -> topLeft = topLeft.min(co) bottomRight = bottomRight.max(co) map[co] = ROCK } bottomFloor = bottomRight.row - topLeft.row + (if (infiniteFloor) 2 else 0) } operator fun set(co: Co, value: Tile) { map.put(co, value) } operator fun get(co: Co): Tile { if (infiniteFloor && co.row == bottomFloor) return ROCK return map[co] ?: AIR } fun isInBounds(co: Co): Boolean { return co.row <= bottomFloor } fun sandCount(): Int { return map.filter { (_, value) -> value == SAND }.count() } fun print() { for (row in 0 .. bottomFloor) { for (col in source.col-15 until source.col+15) { print(when(get(Co(row, col))) { ROCK -> "#" AIR -> "." SAND -> "O" }) } println() } println() } } enum class Tile { ROCK, AIR, SAND }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
3,792
Advent-of-Code
MIT License
solutions/src/solutions/y20/day 16.kt
Kroppeb
225,582,260
false
null
@file:Suppress("PackageDirectoryMismatch") package solutions.y20.d16 import grid.Clock import helpers.* val xxxxx = Clock(6, 3); private fun part1(data: Data) { val rules = data.takeWhile { it.isNotBlank() }.map{ it.split(": ")[1].split(" or ").map{it.getPosInts()}.map{(a,b)->a..b} } val rem = data.drop(rules.size + 5).map{it.getInts()} val mine = data[rules.size + 2] val r = rules.flatten() val err = rem.flatten().filter{ !r.any{i -> it in i} } err.sum().log() } private fun part2(data: Data) { val rules = data.takeWhile { it.isNotBlank() }.map{ val (x,y) = it.split(": ") x to y.split(" or ").map{it.getPosInts()}.map{(a,b)->a..b} }.toMap().toMutableMap() val rem = data.drop(rules.size + 5).map{it.getInts()} val mine = data[rules.size + 2].getInts() val r = rules.values.flatten() val good = rem.filter{ it.all{r.any{i -> it in i}} } println(good) val pos = MutableList(rules.size){rules.keys.toMutableSet()} for (card in good) { for (idx in pos.indices) { val bad = mutableSetOf<String>() val cur = pos[idx] for (re in cur) { if (rules[re]!!.all { card[idx] !in it }) { bad.add(re) } } cur.removeAll(bad) } } val found = mutableMapOf<String,Int>() repeat(500) { for (idx in pos.indices) { val bad = mutableSetOf<String>() val cur = pos[idx] for (re in cur) { if (rules[re]?.any{ good.any{card -> card[idx] !in it} } != true) { bad.add(re) } } cur.removeAll(bad) } for(i in pos.indices){ if(pos[i].size == 1){ val n = pos[i].toList()[0] found[n] = i rules.remove(n) } } println(pos.sumBy { it.count() }) } var ans = 1L for(k in found.keys){ if(k.startsWith("departure")){ ans *= mine[found[k]!!] } } println(found) ans.log() } private typealias Data = Lines fun main() { val data: Data = getLines(2020_16) part1(data) part2(data) } fun Any?.log() = println(this)
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
1,926
AdventOfCodeSolutions
MIT License
src/main/kotlin/fraug/droid/features/Leaderboard.kt
paug
252,267,402
false
null
package fraug.droid.features import fraug.droid.Attempt import fraug.droid.Fish data class Score( val found: Int, val errors: Int, val first: Int ) object Leaderboard { fun asString(scores: Map<String, Score>, limit: Int = Int.MAX_VALUE): String { return "position. username: score (found - errors - first)\n" + scores.entries.sortedByDescending { val r = it.value.found - it.value.errors if (r != 0) { return@sortedByDescending r } it.value.first }.mapIndexed { index, entry -> "$index. ${entry.key}: ${entry.value.found - entry.value.errors} (${entry.value.found}-${entry.value.errors}-${entry.value.first})" }.take(limit) .joinToString("\n") } fun asString(): String { return asString(compute()) } fun summary(scores: Map<String, Score>, limit: Int = Int.MAX_VALUE): String { return scores.entries.sortedByDescending { (it.value.found - it.value.errors) * 1000 + it.value.first }.mapIndexed { index, entry -> "$index. ${entry.key} (${entry.value.found - entry.value.errors})" }.take(limit) .joinToString(", ") } fun summary(): String { return summary(compute(), 10) } fun compute(): Map<String, Score> { val fishes = fishQueries.selectAllFish().executeAsList().sortedBy { it.start } val attempts = fishQueries.selectAllAttempts().executeAsList().sortedBy { it.timestamp } return compute(fishes, attempts) } fun compute(fishes: List<Fish>, attempts: List<Attempt>): Map<String, Score> { val scores = mutableMapOf<String, Score>() val lastFish = mutableMapOf<String, Long>() var currentFishIndex = 0 var first = 1 for (currentAttemptIndex in attempts.indices) { val attempt = attempts[currentAttemptIndex] while (currentFishIndex < fishes.size) { val fish = fishes[currentFishIndex] if (attempt.timestamp < fish.start) { // error scores.compute(attempt.username) { key, old -> old?.copy(errors = old.errors + 1) ?: Score(0, 1, 0) } break } else if ( fish.end == null && attempt.timestamp >= fish.start || attempt.timestamp >= fish.start && attempt.timestamp <= fish.end!! ) { // good val lastFishId = lastFish.get(attempt.username) if (lastFishId != null && lastFishId == fish.id) { // duplicate fish break } lastFish.put(attempt.username, fish.id) scores.compute(attempt.username) { key, old -> if (old == null) { Score(1, 0, first) } else { old.copy( found = old.found + 1, first = old.first + first ) } } first = 0 break } else { currentFishIndex++ first = 1 } } if (currentFishIndex == fishes.size) { // error scores.compute(attempt.username) { key, old -> old?.copy(errors = old.errors + 1) ?: Score(0, 1, 0) } } } return scores } }
0
Kotlin
1
2
b9b820c98e283a11d4286255dd41363baaac7933
3,733
fraugdroid
MIT License
src/Day05.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
class Stack{ val elements: MutableList<Char> = mutableListOf() fun isEmpty() = elements.isEmpty() fun size() = elements.size fun push(item: Char) = elements.add(item) fun insert(item: Char) = elements.add(0, item) fun pop() : Char { val item = elements.last() if (!isEmpty()){ elements.removeAt(elements.size -1) } return item } fun peek() : Char = elements.last() override fun toString(): String = elements.toString() } fun main() { fun part1(input: List<String>): String { val head = mutableListOf<String>() val tail = mutableListOf<String>() var numberFound = false input.forEach { if (!numberFound) { if (it.substring(0, 2) == " 1") { numberFound = true } else { head.add(it) } } else if (!it.isBlank()) { tail.add(it) } } val stacks = mutableListOf<Stack>() head.forEach { line -> line.forEachIndexed { index, c -> // 1 5 9 if ((index) % 4 == 1) { if (index / 4 > stacks.lastIndex) stacks.add(Stack()) if (c.isLetter()) stacks[index / 4].insert(c) } } } // stacks.forEach { println(it) } // println(tail) tail.forEach { val (quantity, _, from, _, to) = it.removePrefix("move ").split(" ").map { it.toIntOrNull() ?: 0 } repeat(quantity) { stacks[to - 1].push(stacks[from - 1].pop()) } } // stacks.forEach { println(it) } var sum = "" stacks.forEach { val c = it.peek() if (c.isLetter()) sum += c } return sum } fun part2(input: List<String>): String { val head = mutableListOf<String>() val tail = mutableListOf<String>() var numberFound = false input.forEach { if (!numberFound) { if (it.substring(0, 2) == " 1") { numberFound = true } else { head.add(it) } } else if (!it.isBlank()) { tail.add(it) } } val stacks = mutableListOf<Stack>() head.forEach { line -> line.forEachIndexed { index, c -> // 1 5 9 if ((index) % 4 == 1) { if (index / 4 > stacks.lastIndex) stacks.add(Stack()) if (c.isLetter()) stacks[index / 4].insert(c) } } } // stacks.forEach { println(it) } // println(tail) tail.forEach { val (quantity, _, from, _, to) = it.removePrefix("move ").split(" ").map { it.toIntOrNull() ?: 0 } val temp = Stack() repeat(quantity) { temp.push(stacks[from - 1].pop()) } repeat(quantity) { stacks[to - 1].push(temp.pop()) } } // stacks.forEach { println(it) } var sum = "" stacks.forEach { val c = it.peek() if (c.isLetter()) sum += c } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") // println(part1(testInput)) check(part1(testInput) == "CMZ") // println(part2(testInput)) check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
3,691
AoC-2022
Apache License 2.0
src/year2022/day05/Solution.kt
LewsTherinTelescope
573,240,975
false
{"Kotlin": 33565}
package year2022.day05 import utils.runIt import utils.splitOnBlankLines fun main() = runIt( testInput = """ [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2 """.trimIndent(), ::part1, testAnswerPart1 = "CMZ", ::part2, testAnswerPart2 = "MCD", ) fun part1(input: String) = input.parseMoveInstructions() .let { (crates, instructions) -> crates apply9000 instructions } .joinToString("", transform = List<Crate>::last) fun part2(input: String) = input.parseMoveInstructions() .let { (crates, instructions) -> crates apply9001 instructions } .joinToString("", transform = List<Crate>::last) @JvmInline value class Crate(val label: String) : CharSequence by label data class MoveInstruction( val count: Int, val source: Int, val destination: Int, ) operator fun <T> List<T>.component6() = this[5] fun String.parseMoveInstructions() = splitOnBlankLines().let { (cratesStr, instructionsStr) -> // drop numbers row at end val crates = cratesStr.split("\n") .dropLast(1) .map { row -> row.chunked(4) } .rotated { Crate(it.trim().removeSurrounding("[", "]")) } .map { column -> column.toMutableList().apply { removeIf(CharSequence::isEmpty) reverse() } } .toMutableList() val instructions = instructionsStr.split("\n") .map { line -> line.split(" ").let { (_, count, _, source, _, destination) -> MoveInstruction(count.toInt(), source.toInt(), destination.toInt()) } } crates to instructions } fun <T> List<List<T>>.rotated(): List<List<T>> = rotated { it } inline fun <T, R> List<List<T>>.rotated( transform: (T) -> R, ): List<List<R>> = fold(MutableList(first().size) { mutableListOf<R>() }) { acc, it -> it.forEachIndexed { index, value -> acc[index].add(transform(value)) } acc } @Suppress("NOTHING_TO_INLINE") inline infix fun MutableList<MutableList<Crate>>.apply9000(instructions: List<MoveInstruction>) = applyPatches(instructions, preserveOrder = false) @Suppress("NOTHING_TO_INLINE") inline infix fun MutableList<MutableList<Crate>>.apply9001(instructions: List<MoveInstruction>) = applyPatches(instructions, preserveOrder = true) fun MutableList<MutableList<Crate>>.applyPatches( instructions: List<MoveInstruction>, preserveOrder: Boolean, ) = apply { instructions.forEach { instruction -> val (count, source, destination) = instruction val src = this[source - 1] val dest = this[destination - 1] if (preserveOrder) { val toMove = src.takeLast(count) for (i in 0 until count) { src.removeLast() } dest.addAll(toMove) } else { for (i in 0 until count) { dest.add(src.removeLast()) } } } }
0
Kotlin
0
0
ee18157a24765cb129f9fe3f2644994f61bb1365
2,704
advent-of-code-kotlin
Do What The F*ck You Want To Public License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions56.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round0.BinaryTreeNode fun test56() { val testTree1 = binarySearchTreeTestCase() printlnResult(testTree1, 13) printlnResult(testTree1, 8) val testTree2 = binarySearchTreeTestCase2() printlnResult(testTree2, 12) printlnResult(testTree2, 22) } /** * Questions 56: Judge if two nodes that the sum of twos equals k in a binary search tree */ private infix fun BinaryTreeNode<Int>.isSumEquals(k: Int): Boolean { var pointer = this while (k < pointer.value) pointer.left?.let { pointer = it } ?: kotlin.run { return false } val startIterator = BSTIterator(pointer) var start = startIterator.next() val endIterator = BSTIteratorBigger(pointer) var end = endIterator.next() while (start < end) { val sum = start + end when { sum > k -> { if (endIterator.hasNext()) end = endIterator.next() else return false } sum < k -> { if (startIterator.hasNext()) start = startIterator.next() else return false } else -> return true } } return false } fun binarySearchTreeTestCase2() = BinaryTreeNode( value = 8, left = BinaryTreeNode( value = 6, left = BinaryTreeNode(value = 5), right = BinaryTreeNode(value = 7), ), right = BinaryTreeNode( value = 10, left = BinaryTreeNode(value = 9), right = BinaryTreeNode(value = 11), ) ) private fun printlnResult(root: BinaryTreeNode<Int>, k: Int) = println("The binary search tree ${root.inOrderList()}(inorder), are there two nodes that the sum of them equals $k: ${root isSumEquals k}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,953
Algorithm
Apache License 2.0
src/main/kotlin/g0601_0700/s0638_shopping_offers/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0638_shopping_offers // #Medium #Array #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask #Memoization // #2023_02_10_Time_195_ms_(100.00%)_Space_35.1_MB_(100.00%) class Solution { fun shoppingOffers( price: List<Int>, special: List<List<Int>>, needs: List<Int> ): Int { val map: MutableMap<List<Int>, Int> = HashMap() shoppingOffersUtil(price, special, needs, map) return map[needs]!! } private fun shoppingOffersUtil( price: List<Int>, special: List<List<Int>>, needs: List<Int>, map: MutableMap<List<Int>, Int> ): Int { if (map.containsKey(needs)) { return map[needs]!! } var ans = computePrice(price, needs) for (i in special.indices) { if (verify(special[i], needs)) { ans = Math.min( special[i][needs.size] + shoppingOffersUtil( price, special, updatedNeeds(needs, special[i]), map ), ans ) } } map[needs] = ans return (map[needs])!! } private fun updatedNeeds(needs: List<Int>, special: List<Int>): List<Int> { val updatedNeeds: MutableList<Int> = ArrayList(needs) for (i in needs.indices) { updatedNeeds[i] = updatedNeeds[i] - special[i] } return updatedNeeds } private fun verify(special: List<Int>, needs: List<Int>): Boolean { for (i in needs.indices) { if (special[i] > needs[i]) { return false } } return true } private fun computePrice(price: List<Int>, needs: List<Int>): Int { var ans = 0 for (i in needs.indices) { ans += (needs[i] * price[i]) } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,019
LeetCode-in-Kotlin
MIT License
src/y2016/Day01.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2016 import util.Cardinal import util.Turn import util.plus import util.readInput import util.times import kotlin.math.abs object Day01 { private fun parse(input: List<String>): List<Pair<Turn, Int>> { return input.first().split(", ").map { Turn.fromChar(it.first()) to it.drop(1).toInt() } } fun part1(input: List<String>): Int { val directions = parse(input) var currentPos = 0 to 0 var currentDirection = Cardinal.NORTH directions.forEach { currentDirection = currentDirection.turn(it.first) currentPos += (currentDirection.relativePos * it.second) } return abs(currentPos.first) + abs(currentPos.second) } fun part2(input: List<String>): Int { val directions = parse(input) var currentPos = 0 to 0 var currentDirection = Cardinal.NORTH val visited = mutableSetOf(currentPos) directions.forEach { currentDirection = currentDirection.turn(it.first) repeat(it.second) { currentPos = currentDirection.of(currentPos) if (!visited.add(currentPos)) { return abs(currentPos.first) + abs(currentPos.second) } } } error("missed crossing") } } fun main() { val testInput = """ R8, R4, R4, R8 """.trimIndent().split("\n") println("------Tests------") println(Day01.part1(testInput)) println(Day01.part2(testInput)) println("------Real------") val input = readInput("resources/2016/day01") println(Day01.part1(input)) println(Day01.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,681
advent-of-code
Apache License 2.0
src/main/kotlin/y2021/Day03.kt
jforatier
432,712,749
false
{"Kotlin": 44692}
package y2021 class Day03(private val data: List<String>) { class Report(private val data: List<String>) { fun gamma(): String { // Using first line to determine limits of my browse (indices of line 1 will tell me I can look through column 0 to 4) // Then for each column (0 to 4), I count 1, if there are in majority we return 1 else 0 // Last we generate final binary number with "10101" return data.first().indices.map { column -> if (data.count { it[column] == '1' } > data.size / 2) '1' else '0' }.joinToString("") } fun epsilon(): String { // The epsilon is the just a binary revert for gamma return gamma().map { if (it == '1') '0' else '1' }.joinToString("") } fun oxygen(): Int { return browse { ones, zeros -> if (ones.size >= zeros.size) ones else zeros } } fun co2(): Int { return browse { ones, zeros -> if (zeros.size <= ones.size) zeros else ones } } private fun browse( compare: (ones: List<String>, zeros: List<String>) -> List<String> ) = data.first().indices .fold(data) { acc, index -> if (acc.size == 1) { acc } else { val ones = acc.filter { it[index] == '1' } val zeros = acc.filter { it[index] == '0' } compare(ones, zeros) } } .joinToString("") .toInt(2) } fun part1(): Int { val report = Report(data) return report.gamma().toInt(2) * report.epsilon().toInt(2) } fun part2(): Int { val report = Report(data) return report.co2() * report.oxygen() } }
0
Kotlin
0
0
2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae
1,832
advent-of-code-kotlin
MIT License
src/year_2022/day_14/Day14.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_14 import readInput import util.connect import util.down import util.downLeft import util.downRight sealed class DropSandResult { object Infinity: DropSandResult() data class Stopped(val at: Pair<Int, Int>): DropSandResult() } object Day14 { private val sandStartingPosition = 500 to 0 /** * @return */ fun solutionOne(text: List<String>): Int { val rockLocations = parseText(text) val sandLocations = mutableSetOf<Pair<Int, Int>>() while (true) { when (val dropSandResult = dropSand(sandStartingPosition, rockLocations, sandLocations)) { is DropSandResult.Infinity -> break is DropSandResult.Stopped -> sandLocations.add(dropSandResult.at) } } return sandLocations.size } /** * @return */ fun solutionTwo(text: List<String>): Int { val rockLocations = parseText(text) val sandLocations = mutableSetOf<Pair<Int, Int>>() while (true) { when (val dropSandResult = dropSandToFloor(sandStartingPosition, rockLocations, sandLocations)) { is DropSandResult.Infinity -> { sandLocations.add(sandStartingPosition) break } is DropSandResult.Stopped -> sandLocations.add(dropSandResult.at) } } return sandLocations.size } private fun parseText(text: List<String>): Set<Pair<Int, Int>> { return text.flatMap { line -> line .split(" -> ") .windowed(size = 2, step = 1) .flatMap { (left, right) -> stringToIntPair(left).connect(stringToIntPair(right)) } }.toSet() } private fun stringToIntPair(text: String): Pair<Int, Int> { val ints = text.split(",") .map { Integer.parseInt(it) } return ints[0] to ints[1] } private fun dropSand(from: Pair<Int, Int>, rockLocations: Set<Pair<Int, Int>>, sandLocations: Set<Pair<Int, Int>>): DropSandResult { if (from.down().second > rockLocations.maxOfOrNull { it.second }!!) { return DropSandResult.Infinity } return when { from.down() !in rockLocations && from.down() !in sandLocations -> return dropSand(from.down(), rockLocations, sandLocations) from.downLeft() !in rockLocations && from.downLeft() !in sandLocations -> return dropSand(from.downLeft(), rockLocations, sandLocations) from.downRight() !in rockLocations && from.downRight() !in sandLocations -> return dropSand(from.downRight(), rockLocations, sandLocations) else -> DropSandResult.Stopped(from) } } private fun dropSandToFloor(from: Pair<Int, Int>, rockLocations: Set<Pair<Int, Int>>, sandLocations: Set<Pair<Int, Int>>): DropSandResult { if (from.down().second > rockLocations.maxOfOrNull { it.second }!! + 1) { return DropSandResult.Stopped(from) } val combinedLocations = rockLocations + sandLocations return when { from.down() !in combinedLocations -> return dropSandToFloor(from.down(), rockLocations, sandLocations) from.downLeft() !in combinedLocations -> return dropSandToFloor(from.downLeft(), rockLocations, sandLocations) from.downRight() !in combinedLocations -> return dropSandToFloor(from.downRight(), rockLocations, sandLocations) from == sandStartingPosition -> DropSandResult.Infinity else -> DropSandResult.Stopped(from) } } private fun printBoard(rockLocations: Set<Pair<Int, Int>>, sandLocations: Set<Pair<Int, Int>>) { val maxY = rockLocations.maxOfOrNull { it.second }!! + 1 val minX = rockLocations.minOfOrNull { it.first }!! - maxY val maxX = rockLocations.maxOfOrNull { it.first }!! + maxY for (y in 0..maxY) { for (x in minX..maxX) { if (x to y == sandStartingPosition) { print("+") } else if (x to y in rockLocations) { print("#") } else if (x to y in sandLocations) { print("o") } else { print(".") } } println("") } } } fun main() { val inputText = readInput("year_2022/day_14/Day14.txt") val solutionOne = Day14.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day14.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
4,664
advent_of_code
Apache License 2.0
Coding Challenges/Advent of Code/2021/Day 4/part1.kt
Alphabeater
435,048,407
false
{"Kotlin": 69566, "Python": 5974}
import java.io.File import java.util.Scanner import kotlin.system.exitProcess const val DIM = 5 class BingoBoard { private val size = DIM val board = Array(size) { IntArray(size) } //this represents a single bingo board[x][x]. val found = Array(size) { Array(size){ false } } //this represents what numbers have been guessed so far. } fun getLottoNumbers(scanner: Scanner): List<Int> { //reads and stores the lotto numbers. return scanner.nextLine().split(",").map{ it.toInt() } } fun getBingoBoards(scanner: Scanner): MutableList<BingoBoard> { val boards: MutableList<BingoBoard> = mutableListOf() var boardCount = -1 var count = 0 while (scanner.hasNext()) { var line = scanner.nextLine() if (line.isBlank()) { //this happens when a new line is found in the input. boards += BingoBoard() boardCount++ count = 0 continue } if (line.first() == ' ') line = line.drop(1) //prevent an error if the first character is a spacebar. val values = line.split(" +".toRegex()).map{ it.toInt() } for (i in 0 until DIM) { boards[boardCount].board[count][i] = values[i] //the values of each bingo board are stored. } count++ } return boards } fun drawLottoNumber(boards: MutableList<BingoBoard>, number: Int): MutableList<BingoBoard> { boards.forEach { for (j in 0 until DIM) for (k in 0 until DIM) if (it.board[j][k] == number) it.found[j][k] = true //set the found number on each board. } return boards } fun checkWinner(boards: MutableList<BingoBoard>): BingoBoard? { //returns the position of the winner board. var countHorizontal = 0 var countVertical = 0 boards.forEach { bingoBoard -> for (j in 0 until DIM) { for (k in 0 until DIM) { if (bingoBoard.found[j][k]) countHorizontal++ if (bingoBoard.found[k][j]) countVertical++ } if (countHorizontal == 5 || countVertical == 5) return bingoBoard countHorizontal = 0 countVertical = 0 } } return null } fun getWinner(bingoBoard: BingoBoard, number: Int): Int { var sum = 0 for (i in 0 until DIM) { for (j in 0 until DIM) { if (!bingoBoard.found[i][j]) sum += bingoBoard.board[i][j] } } return sum * number } fun main() { val file = File("src/input.txt") val scanner = Scanner(file) val numbers = getLottoNumbers(scanner) var boards = getBingoBoards(scanner) for (number in numbers) { boards = drawLottoNumber(boards, number) val board = checkWinner(boards) if (board != null) { println(getWinner(board, number)) exitProcess(1) } } }
0
Kotlin
0
0
05c8d4614e025ed2f26fef2e5b1581630201adf0
2,846
Archive
MIT License
src/main/kotlin/days_2021/Day5.kt
BasKiers
434,124,805
false
{"Kotlin": 40804}
package days_2021 import util.Day import kotlin.math.absoluteValue class Day5 : Day(5) { val lines: List<Pair<Pair<Int, Int>, Pair<Int, Int>>> = inputList.map { line -> val (from, to) = line.split(" -> ") val (fromX, fromY) = from.split(",").map(String::toInt) val (toX, toY) = to.split(",").map(String::toInt) (fromX to fromY) to (toX to toY) } class Diagram(width: Int, height: Int) { val points: MutableList<MutableList<Int>> = MutableList(height) { MutableList(width) { 0 } } fun drawLine(fromPair: Pair<Int, Int>, toPair: Pair<Int, Int>): Diagram { val (x1, y1) = fromPair val (x2, y2) = toPair if (x1 == x2) { for (y in minOf(y1, y2)..maxOf(y1, y2)) { points[y][x1] += 1 } } else if (y1 == y2) { for (x in minOf(x1, x2)..maxOf(x1, x2)) { points[y1][x] += 1 } } else if (x1 - x2 != 0 && (x1 - x2).absoluteValue == (y1 - y2).absoluteValue) { val xDir = if (x2 - x1 < 0) -1 else +1 val yDir = if (y2 - y1 < 0) -1 else +1 println("$fromPair, $toPair, $xDir, $yDir") for (i in 0..maxOf(x1 - x2, x2 - x1)) { points[y1 + yDir * i][x1 + xDir * i] += 1 } } return this } override fun toString() = "\n" + points.map { row -> row.map { if (it == 0) '.' else it.toString() }.joinToString("") } .joinToString("\n") } override fun partOne(): Any { val diagram = Diagram(1000, 1000) return lines.fold(diagram) { target, (from, to) -> target.drawLine( from, to ) }.points.fold(0) { acc, row -> acc + row.count { it >= 2 } } } override fun partTwo(): Any { return "bar" } }
0
Kotlin
0
0
870715c172f595b731ee6de275687c2d77caf2f3
1,972
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/GenerateTrees.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 /** * Unique Binary Search Trees 2 */ fun invoke(n: Int): MutableList<TreeNode?> { var res: MutableList<TreeNode?> = ArrayList() if (n <= 0) return res res.add(null) // insert i into tree that stores values from n to i+1 for (i in n downTo 1) { // `next` stores all possible trees that store values from n to i val next: MutableList<TreeNode?> = ArrayList() for (node in res) { /* Case 1: put n on the root, * and the original @node tree is its right tree * since i is the smallest value in the @node tree (from n to i+1) */ val root = TreeNode(i) root.right = node next.add(root) /* Other Cases: put n on root.left, root.left.left, root.left....left, * the root of the new tree is still @node, * i put on insertParent.left, * and the original left tree of the insertParent is set as the right subtree of the new node since i is * small than values in the subtree. */ var insertParent = node while (insertParent != null) { // Step 1: generate a new tree from the @node tree val cRoot = TreeNode(node?.value!!) // clone left subtree since we need to change it by inserting i cRoot.left = node.left.clone() // reusing the right tree since it is fixed cRoot.right = node.right // Step 2: insert i into the new tree val insertParentInNewTree = getValNode(cRoot, insertParent.value) val tmp = insertParentInNewTree?.left insertParentInNewTree?.left = TreeNode(i) insertParentInNewTree?.left?.right = tmp next.add(cRoot) insertParent = insertParent.left } } res = next } return res } private fun getValNode(n: TreeNode, value: Int): TreeNode? { // find the cutoff node in the new tree var node: TreeNode? = n while (node != null) { if (node.value == value) break node = node.left } return node }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,845
kotlab
Apache License 2.0
src/main/kotlin/g1801_1900/s1879_minimum_xor_sum_of_two_arrays/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1879_minimum_xor_sum_of_two_arrays // #Hard #Array #Dynamic_Programming #Bit_Manipulation #Bitmask // #2023_06_22_Time_173_ms_(100.00%)_Space_36.9_MB_(100.00%) class Solution { fun minimumXORSum(nums1: IntArray, nums2: IntArray): Int { val l = nums1.size val dp = IntArray(1 shl l) dp.fill(-1) dp[0] = 0 return dfs(dp.size - 1, l, nums1, nums2, dp, l) } private fun dfs(state: Int, length: Int, nums1: IntArray, nums2: IntArray, dp: IntArray, totalLength: Int): Int { if (dp[state] >= 0) { return dp[state] } var min = Int.MAX_VALUE val currIndex = totalLength - length var i = 0 var index = 0 while (i < length) { if (state shr index and 1 == 1) { val result = dfs(state xor (1 shl index), length - 1, nums1, nums2, dp, totalLength) min = Math.min(min, (nums2[currIndex] xor nums1[index]) + result) i++ } index++ } dp[state] = min return min } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,102
LeetCode-in-Kotlin
MIT License
src/main/kotlin/org/cryptobiotic/mixnet/Permutation.kt
JohnLCaron
754,705,115
false
{"Kotlin": 363510, "Java": 246365, "Shell": 7749, "C": 5751, "JavaScript": 2517}
package org.cryptobiotic.mixnet import java.security.SecureRandom /** psi: {0..N-1} -> {0..N-1} for any vector e, pe = psi.permute(e). then e_i = pe_j, where j = psi.inv(i), i = psi.of(j) so e[idx] = pe[psi.inv(idx)]; you have an element in e, and need to get the corresponding element from pe so pe[jdx] = e[ps.of(jdx)]; you have an element in pe, and need to get the corresponding element from e (ie) <- invert (e) permute -> (pe) (ie) permute -> (e) <- invert (pe) */ data class Permutation(private val psi: IntArray) { val n = psi.size private val inverse: Permutation by lazy { val result = IntArray(n) for (idx in psi) { result[psi[idx]] = idx } Permutation(result) } fun of(idx:Int) = psi[idx] fun inv(jdx:Int) = inverse.of(jdx) fun <T> permute(list: List<T>): List<T> = List(list.size) { idx -> list[psi[idx]] } fun <T> invert(list: List<T>): List<T> = List(list.size) { idx -> list[inverse.of(idx)] } fun inverse() = inverse // Let Bψ be the permutation matrix of ψ, which consists of bij = 1 if ψ(i) == j, else 0 fun makePermutationMatrix(): PermutationMatrix { val elems = mutableListOf<IntArray>() repeat (n) { row -> elems.add( IntArray(n) { col -> if (psi[row] == col) 1 else 0 }) } return PermutationMatrix(elems) } companion object { fun random(n: Int) : Permutation { val result = MutableList(n) { it } result.shuffle(SecureRandom.getInstanceStrong()) return Permutation(result.toIntArray()) } } } data class PermutationMatrix( val elems: List<IntArray> ) { val n = elems.size // right multiply by a column vector // psi(x) = B * x fun rmultiply(colv: List<Int>) : List<Int> { val result = elems.map{ row -> var sum = 0 row.forEachIndexed{ idx, it -> sum += it * colv[idx] } sum } return result } fun column(col : Int) : List<Int> { return elems.map{ it[col] } } override fun toString(): String { return buildString { elems.forEach { append("${it.contentToString()}\n") } } } }
0
Kotlin
0
0
63de19eb8ca2fb2b2d3286213b71c71097ab1d85
2,273
egk-mixnet-vmn
MIT License
src/commonMain/kotlin/ai/hypergraph/kaliningraph/theory/Theory.kt
breandan
245,074,037
false
{"Kotlin": 1482924, "Haskell": 744, "OCaml": 200}
package ai.hypergraph.kaliningraph.theory import ai.hypergraph.kaliningraph.* import ai.hypergraph.kaliningraph.sampling.randomMatrix import ai.hypergraph.kaliningraph.sampling.sample import ai.hypergraph.kaliningraph.tensor.* import ai.hypergraph.kaliningraph.types.* // https://en.wikipedia.org/wiki/Barab%C3%A1si%E2%80%93Albert_model#Algorithm tailrec fun <G : IGraph<G, E, V>, E : IEdge<G, E, V>, V : IVertex<G, E, V>> IGraph<G, E, V>.prefAttach( graph: G = this as G, numVertices: Int = 1, degree: Int = 3, attach: G.(Int) -> G = { degree -> this + V( if (vertices.isEmpty()) emptySet() else degMap.sample().take(degree.coerceAtMost(size)).toSet() ).graph } ): G = if (numVertices <= 0) graph else prefAttach(graph.attach(degree), numVertices - 1, degree, attach) /* (A')ⁿ[a, b] counts the number of walks between vertices a, b of * length n. Let i be the smallest natural number such that (A')ⁱ * has no zeros. i is the length of the longest shortest path in G. */ tailrec fun <G : IGraph<G, E, V>, E : IEdge<G, E, V>, V : IVertex<G, E, V>> IGraph<G, E, V>.slowDiameter( i: Int = 1, walks: BooleanMatrix = A_AUG ): Int = if (walks.isFull) i else slowDiameter(i = i + 1, walks = walks * A_AUG) // Based on Booth & Lipton (1981): https://doi.org/10.1007/BF00264532 tailrec fun <G : IGraph<G, E, V>, E : IEdge<G, E, V>, V : IVertex<G, E, V>> IGraph<G, E, V>.diameter( i: Int = 1, prev: BooleanMatrix = A_AUG, next: BooleanMatrix = prev ): Int = if (next.isFull) slowDiameter(i / 2, prev) else diameter(i = 2 * i, prev = next, next = next * next) /* Weisfeiler-Lehman isomorphism test: * http://www.jmlr.org/papers/volume12/shervashidze11a/shervashidze11a.pdf#page=6 * http://davidbieber.com/post/2019-05-10-weisfeiler-lehman-isomorphism-test/ * https://breandan.net/2020/06/30/graph-computation/#weisfeiler-lehman */ tailrec fun <G : IGraph<G, E, V>, E : IEdge<G, E, V>, V : IVertex<G, E, V>> IGraph<G, E, V>.wl( k: Int = 5, label: (V) -> Int = { histogram[it]!! } ): Map<V, Int> { val updates = associateWith { it.neighbors.map(label).sorted().hashCode() } return if (k <= 0 || all { label(it) == updates[it] }) updates else wl(k - 1) { updates[it]!! } } /* IGraph-level GNN implementation * https://www.cs.mcgill.ca/~wlh/grl_book/files/GRL_Book-Chapter_5-GNNs.pdf#page=6 * H^t := σ(AH^(t-1)W^(t) + H^(t-1)W^t) * * TODO: * Pooling: https://www.cs.mcgill.ca/~wlh/grl_book/files/GRL_Book-Chapter_5-GNNs.pdf#page=18 * Convolution: https://arxiv.org/pdf/2004.03519.pdf#page=2 */ tailrec fun <G : IGraph<G, E, V>, E : IEdge<G, E, V>, V : IVertex<G, E, V>> IGraph<G, E, V>.gnn( // Message passing rounds t: Int = diameter() * 10, // Matrix of node representations ℝ^{|V|xd} H: DoubleMatrix = ENCODED, // (Trainable) weight matrix ℝ^{dxd} W: DoubleMatrix = randomMatrix(H.numCols), // Bias term ℝ^{dxd} b: DoubleMatrix = randomMatrix(size, H.numCols), // Nonlinearity ℝ^{*} -> ℝ^{*} σ: (DoubleMatrix) -> DoubleMatrix = ACT_TANH, // Layer normalization ℝ^{*} -> ℝ^{*} z: (DoubleMatrix) -> DoubleMatrix = NORM_AVG, // Message ℝ^{*} -> ℝ^{*} m: (DoubleMatrix) -> DoubleMatrix = { σ(z(A * it * W + it * W + b)) } ): DoubleMatrix = if (t == 0) H else gnn(t = t - 1, H = m(H), W = W, b = b) // https://fabianmurariu.github.io/posts/scala3-typeclassery-graphs/ // https://doisinkidney.com/pdfs/algebras-for-weighted-search.pdf // https://www.youtube.com/watch?v=n6oS6X-DOlg tailrec fun <G : IGraph<G, E, V>, E : IEdge<G, E, V>, V : IVertex<G, E, V>> IGraph<G, E, V>.dfs( init: V = random(), cond: (V) -> Boolean ): V = TODO() tailrec fun <G : IGraph<G, E, V>, E : IEdge<G, E, V>, V : IVertex<G, E, V>> IGraph<G, E, V>.bfs( init: V = random(), cond: (V) -> Boolean ): V = TODO() tailrec fun <G : IGraph<G, E, V>, E : IEdge<G, E, V>, V : IVertex<G, E, V>> IGraph<G, E, V>.beamsearch( init: V = random(), cond: (V) -> Boolean ): V = TODO()
0
Kotlin
8
100
c755dc4858ed2c202c71e12b083ab0518d113714
3,981
galoisenne
Apache License 2.0
src/PuzzleSolver.kt
JosephPrichard
477,595,077
false
null
/* * Implements AStar algorithm to solve the puzzle * 4/16/20 */ package src import java.util.* import kotlin.math.abs /** * * @author <NAME> */ class PuzzleSolver(private val boardSize: Int) { private val goalState: PuzzleState init { // creates the goal state for the specified board size var num = 1 val goalPuzzle = Array(boardSize){ IntArray(boardSize) } for (i in 0 until boardSize) { goalPuzzle[i] = IntArray(boardSize) for (j in 0 until boardSize) { goalPuzzle[i][j] = num num++ } } goalPuzzle[boardSize - 1][boardSize - 1] = 0 goalState = PuzzleState(goalPuzzle) } private fun heuristic(puzzleState: PuzzleState): Int { val puzzle = puzzleState.puzzle var h = 0 // compute the heuristic against the goal state (we calculate the goal values rather than read since it is faster) for (i in 0 until boardSize) { for (j in 0 until boardSize) { if (puzzle[i][j] != 0) { h += manhattanDistance(i, j, puzzle[i][j] / boardSize, puzzle[i][j] % boardSize) } } } return h } fun findSolution(initialState: PuzzleState): ArrayList<PuzzleState> { // creates the closed set to stores nodes we've already expanded val closedSet = HashSet<PuzzleState>(10000) closedSet.add(initialState) // creates the open set to choose the closest state to the solution at each iteration val openSet = PriorityQueue<PuzzleState>(10000) openSet.add(initialState) // iterate until we find a solution or are out of puzzle states while (!openSet.isEmpty()) { // pop the closest state off the priority queue val currentState = openSet.poll() closedSet.add(currentState) // check if we've reached the goal state, if so we can return the solution if (currentState == goalState) { return reconstructPath(currentState) } // expand our search by getting the neighbor states for the current state val neighborStates = neighborStates(currentState) // for each neighbor, if it isn't already visited update the FScore for ranking and add it to the open set for (neighborState in neighborStates) { if (!closedSet.contains(neighborState)) { neighborState.f = neighborState.g + heuristic(neighborState) openSet.add(neighborState) } } } return ArrayList() } private fun neighborStates(current: PuzzleState): ArrayList<PuzzleState> { val neighborStates = ArrayList<PuzzleState>() val upPuzzle = current.shiftUp() if (upPuzzle != null) { neighborStates.add(upPuzzle) } val downPuzzle = current.shiftDown() if (downPuzzle != null) { neighborStates.add(downPuzzle) } val rightPuzzle = current.shiftRight() if (rightPuzzle != null) { neighborStates.add(rightPuzzle) } val leftPuzzle = current.shiftLeft() if (leftPuzzle != null) { neighborStates.add(leftPuzzle) } return neighborStates } private fun reconstructPath(bottomLeaf: PuzzleState?): ArrayList<PuzzleState> { var current = bottomLeaf val list = ArrayList<PuzzleState>() // traverse tree up through parents until we reach the root while (current != null) { list.add(current) current = current.parent } // reverse the list since we traversed from goal state to initial list.reverse() return list } fun generateRandomSolvable(): PuzzleState { val moves = Utils.rand(15, 20) var currentState = goalState for (i in 0 until moves) { val neighborStates = neighborStates(currentState) val move = Utils.rand(0, neighborStates.size - 1) currentState = neighborStates[move] } currentState.unlink() return currentState } fun isSolvable(puzzleState: PuzzleState): Boolean { val invCount = countInversions(puzzleState) return if (puzzleState.getBoardSize() % 2 == 0) { // even board size val zeroStart = puzzleState.find0Position() (zeroStart + invCount) % 2 != 0 } else { // odd board size invCount % 2 == 0 } } private fun countInversions(puzzleState: PuzzleState): Int { val puzzle = IntArray(boardSize * boardSize) // copy the 2D puzzle arrays to a laid out 1D array var counter = 0 for (i in 0 until boardSize) { for (j in 0 until boardSize) { puzzle[counter] = puzzleState.puzzle[i][j] counter++ } } // counts the number of inversions in the puzzle // an inversion is any pair i and j where i < j but i appears after j on the solved state var inversions = 0 for (i in puzzle.indices) { if (puzzle[i] == 0) { continue } for (j in i + 1 until puzzle.size) { if (puzzle[j] == 0) { continue } if (puzzle[i] > puzzle[j]) { inversions++ } } } return inversions } companion object { fun manhattanDistance(row: Int, col1: Int, row2: Int, col2: Int): Int { return abs(row2 - row) + abs(col2 - col1) } } }
0
Kotlin
0
1
9075414576cf92e23c3c0ad6bb222591f0d05d14
5,822
SlidingPuzzle
MIT License
day02/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.io.File import java.lang.IllegalStateException fun main() { val input = readInputFile() println("Part I: the solution is ${solvePartI(input)}.") println("Part II: the solution is ${solvePartII(input)}.") } fun readInputFile(): List<String> { return File(ClassLoader.getSystemResource("input.txt").file).readLines() } fun solvePartI(ids: List<String>): Int { val numberOfIdsBySizeOfRepeat = ids.flatMap { id -> id.groupingBy { it }.eachCount().values.toSet() } .groupingBy { it } .eachCount() return numberOfIdsBySizeOfRepeat[2]!! * numberOfIdsBySizeOfRepeat[3]!! } fun solvePartII(ids: List<String>): String { val idLength = ids[0].length for (i in 0 until ids.size - 2) { for (j in (i + 1) until (ids.size - 1)) { val sharedLetters = getSharedLetters(ids[i], ids[j]) if (sharedLetters.length == idLength - 1) { return sharedLetters } } } throw IllegalStateException("This line should not be reached.") } fun getSharedLetters(id1: String, id2: String): String { var result = "" for (i in 0..(id1.length - 1)) { if (id1[i] == id2[i]) { result += id1[i] } } return result }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
1,272
AdventOfCode2018
MIT License
solutions/src/MinTimeToCollectAllApples.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/ */ class MinTimeToCollectAllApples { fun minTime(n: Int, edges: Array<IntArray>, hasApple: List<Boolean>) : Int { val edgeMap = edges.map { Pair(it[0],it[1]) }.groupBy { it.first }.mapValues { entry -> entry.value.map { it.second } } return if (n > 1 && hasApple.any { it }) { dfs(setOf(0),edgeMap,hasApple,0)-2 } else { 0 } } private fun dfs(visited: Set<Int>, edgeMap: Map<Int,List<Int>>, hasApple: List<Boolean>, node: Int ) : Int { val connections = edgeMap.getOrDefault(node, listOf()).filter { !visited.contains(it) } return if (connections.isEmpty() && hasApple[node]) { 2 } else if (connections.isEmpty() && !hasApple[node]) { 0 } else { val sum = connections.map { dfs(visited+node,edgeMap,hasApple,it) }.sum() if (sum > 0) { sum+2 } else if (sum == 0 && hasApple[node]) { 2 } else { 0 } } } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,169
leetcode-solutions
MIT License
Algorithms/432 - All O one Data Structure/src/Solution2.kt
mobeigi
202,966,767
false
null
/** * Solution2 * * We use two maps to allow us to lookup keys by string in O(1) and lookup by frequency in O(1). * This solution does NOT meet the requirements as getMaxKey and getMinKey are both O(N) functions. * However, this solution is simple to read and understand and is quite performant nevertheless. */ class AllOne2 { private val freq = HashMap<String, Long>() private val countMap = HashMap<Long, MutableSet<String>>() fun inc(key: String) { val prevCount = freq.getOrDefault(key, 0) val newCount = prevCount + 1 freq[key] = newCount removePreviousCountMap(key, prevCount) addNewCountMap(key, newCount) } fun dec(key: String) { val prevCount = freq[key]!! val newCount = prevCount - 1 removePreviousCountMap(key, prevCount) if (newCount == 0L) { freq.remove(key) } else { freq[key] = newCount addNewCountMap(key, newCount) } } private fun removePreviousCountMap(key: String, prevCount: Long) { countMap[prevCount]?.remove(key) if (countMap[prevCount].isNullOrEmpty()) { countMap.remove(prevCount) } } private fun addNewCountMap(key: String, newCount: Long) { val newSet = countMap.getOrDefault(newCount, mutableSetOf()) newSet.add(key) countMap[newCount] = newSet } fun getMaxKey(): String { return countMap.maxBy { it.key }?.value?.first() ?: "" } fun getMinKey(): String { return countMap.minBy { it.key }?.value?.first() ?: "" } }
0
Kotlin
0
0
e5e29d992b52e4e20ce14a3574d8c981628f38dc
1,673
LeetCode-Solutions
Academic Free License v1.1
solutions/src/KnightDialer.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
class KnightDialer { /** * https://leetcode.com/problems/knight-dialer/ */ fun knightDialer(n: Int) : Int { val MOD = 1000000007 val dialerDP = Array(n){LongArray(12) { 0 } } for (i in 0..11) { if (i != 9 && i != 11) { dialerDP[0][i] = 1; } } for (i in dialerDP.indices) { if (i != dialerDP.lastIndex) { for (j in dialerDP[0].indices) { if (j != 9 && j != 11) { val possibleMoves = calculateIndicies(j); possibleMoves.forEach { dialerDP[i+1][it] = (dialerDP[i+1][it]+dialerDP[i][j]) % MOD } } } } } return (dialerDP.last().sum() % MOD).toInt(); } private fun calculateIndicies(currentIndex: Int) : List<Int> { var iIndex = currentIndex/3; var jIndex = currentIndex % 3; return listOf( Pair(iIndex-2,jIndex-1), Pair(iIndex-2,jIndex+1), Pair(iIndex+2,jIndex-1), Pair(iIndex+2,jIndex+1), Pair(iIndex+1,jIndex-2), Pair(iIndex+1,jIndex+2), Pair(iIndex-1,jIndex-2), Pair(iIndex-1,jIndex+2) ).filter { it.second >= 0 && it.first >= 0 && it.second < 3 && it.first < 4 && it != Pair(3,0) && it != Pair(3,2) }.map { it.first*3 + it.second } } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,560
leetcode-solutions
MIT License
src/Day03.kt
bkosm
572,912,735
false
{"Kotlin": 17839}
import dev.forkhandles.result4k.partition import kotlin.math.roundToInt object Day03 : DailyRunner<Int, Int> { @JvmInline private value class Prio private constructor(val value: Int) { companion object { private val PriorityMap = ((('a'..'z') zip (1..26)) + (('A'..'Z') zip (27..52))).toMap() fun of(char: Char) = Prio(PriorityMap[char]!!) } } private fun common(a: String, b: String) = a.toSet().intersect(b.toSet()) private fun common(a: String, b: String, c: String) = common(a, b).joinToString("").let { common(it, c) } override fun do1(input: List<String>, isTest: Boolean): Int = input.sumOf { line -> val aSize = (line.length / 2.0).roundToInt() val bSize = line.length - aSize val a = line.dropLast(bSize) val b = line.drop(aSize) common(a, b).sumOf { Prio.of(it).value } } override fun do2(input: List<String>, isTest: Boolean): Int = input.windowed(3, 3).map { elves -> val (a, b, c) = elves common(a, b, c).run { if (size == 1) Prio.of(first()).left() else map { Prio.of(it) }.right() } }.partition().run { val certain = first.sumOf { it.value } val pool = second.flatten().toMutableSet() val fitted = second.sumOf { possiblePrios -> possiblePrios.random().also { check(pool.remove(it)) { "Pick $it was already missing in the pool" } }.value } certain + fitted } } fun main() { Day03.run() }
0
Kotlin
0
1
3f9cccad1e5b6ba3e92cbd836a40207a2f3415a4
1,565
aoc22
Apache License 2.0
src/Day01.kt
jarmstrong
572,742,103
false
{"Kotlin": 5377}
fun main() { fun calorieCountsByElf(input: List<String>): Map<Int, Int> { var currentElfIndex = 0 val elfCalorieCounts = mutableMapOf<Int, Int>() input.forEach { if (it.isEmpty()) { currentElfIndex++ return@forEach } val currentCalorieCount = elfCalorieCounts.getOrDefault(currentElfIndex, 0) elfCalorieCounts[currentElfIndex] = currentCalorieCount + it.toInt() } return elfCalorieCounts } fun part1(input: List<String>): Int { return calorieCountsByElf(input).values.max() } fun part2(input: List<String>): Int { return calorieCountsByElf(input).values.sorted().takeLast(3).sum() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bba73a80dcd02fb4a76fe3938733cb4b73c365a6
918
aoc-2022
Apache License 2.0
src/Day09.kt
ixtryl
575,312,836
false
null
import java.util.* import kotlin.math.abs fun main() { // if (DAY09().run("Day09_test", 2) != 13) { // throw RuntimeException("Fail: Expected 13") // } // if (DAY09().run("Day09", 2) != 6081) { // throw RuntimeException("Fail: Expected 6081") // } if (DAY09().run("Day09_test2", 10) != 36) { throw RuntimeException("Fail: Expected 1") } // if (DAY09().run("Day09", 10) != 278) { // throw RuntimeException("Fail: Expected 278") // } } private const val START_ROW = 0 private const val START_COL = 0 private class DAY09 { fun run(fileName: String, knotsCount: Int): Int { val knots = initializeKnots(knotsCount) val lines = readInput(fileName) val moves = getMoves(lines) executeMoves(knots, moves) val tail = knots[knotsCount - 1] println(tail.visited) dumpTrace(tail) println() println(tail.visited.size) return tail.visited.size } private fun dumpTrace(knot: Knot) { var maxRow = 0 var minRow = 0 var maxCol = 0 var minCol = 0 knot.visited.forEach { if (it.row > maxRow) maxRow = it.row if (it.row < minRow) minRow = it.row if (it.col > maxCol) maxCol = it.col if (it.col < minCol) minCol = it.col } var offsetRow = 0 var offsetCol = 0 if (minRow < 0) offsetRow = 0 - minRow if (minCol < 0) offsetCol = 0 - minCol val rangeRow = offsetRow + maxRow + 1 val rangeCol = offsetCol + maxCol + 1 val matrix: MutableList<MutableList<Char>> = mutableListOf() for (i in 0 until rangeRow) { matrix.add(ArrayList(Collections.nCopies(rangeCol, '.'))) } knot.visited.forEach { matrix[it.row + offsetRow][it.col + offsetCol] = '#' } matrix[0 + offsetRow][0 + offsetCol] = 's' println() matrix.reverse() matrix.forEach { row -> println() row.forEach { col -> print(col) } } println() println() } private fun initializeKnots(knotsCount: Int): List<Knot> { val knots = mutableListOf<Knot>() for (i in 1..knotsCount) { knots.add(Knot(Position(START_ROW, START_COL))) } return knots } private fun executeMoves(knots: List<Knot>, moves: List<Move>) { val head = knots[0] for ((direction, steps) in moves) { for (i in 1..steps) { head.move(direction) for (j in 1 until knots.size) { if (knots[j].inProximityOf(knots[j - 1]).not()) { knots[j].moveTowards(knots[j - 1]) } } } dumpTrace(knots.last()) } } private fun getMoves(lines: List<String>): List<Move> { val moves = mutableListOf<Move>() for (line in lines) { val parts = line.split(" ") moves.add(Move(parts[0].toDirection(), Integer.parseInt(parts[1]))) } return moves } private enum class DIRECTION(val string: String) { UP("U"), DOWN("D"), LEFT("L"), RIGHT("R"); companion object { fun fromString(value: String): DIRECTION { return values().first { it.string == value } } } } private fun String.toDirection(): DIRECTION { return DIRECTION.fromString(this) } private data class Move(val direction: DIRECTION, val steps: Int) private class Knot(startPosition: Position) { val visited = mutableSetOf<Position>() var pos: Position = startPosition set(value) { visited.add(value) field = value } val row get() = pos.row val col get() = pos.col init { this.visited.add(startPosition) } fun move(direction: DIRECTION) { pos = when (direction) { DIRECTION.UP -> Position(row + 1, col) DIRECTION.DOWN -> Position(row - 1, col) DIRECTION.LEFT -> Position(row, col - 1) DIRECTION.RIGHT -> Position(row, col + 1) } } fun inProximityOf(other: Knot): Boolean = pos.inProximityOf(other.pos) override fun toString(): String = "(${pos.row}, ${pos.col})" fun moveTowards(other: Knot) { var rows = 0 var cols = 0 if (row + 1 < other.row && abs(col - other.col) < 2) { rows += 1 if (col < other.col) { cols += 1 } if (col > other.col) { cols -= 1 } } if (row - 1 > other.row && abs(col - other.col) < 2) { rows -= 1 if (col < other.col) { cols += 1 } if (col > other.col) { cols -= 1 } } if (col + 1 < other.col && abs(row - other.row) < 2) { cols += 1 if (row < other.row) { rows += 1 } if (row > other.row) { rows -= 1 } } if (col - 1 > other.col && abs(row - other.row) < 2) { cols -= 1 if (row < other.row) { rows += 1 } if (row > other.row) { rows -= 1 } } pos = Position(pos.row + rows, pos.col + cols) } } private data class Position(val row: Int, val col: Int) { fun inProximityOf(other: Position): Boolean = row in (other.row - 1)..(other.row + 1) && col in (other.col - 1)..(other.col + 1) } }
0
Kotlin
0
0
78fa5f6f85bebe085a26333e3f4d0888e510689c
5,955
advent-of-code-kotlin-2022
Apache License 2.0
Retos/Reto #4 - PRIMO, FIBONACCI Y PAR [Media]/kotlin/westwbn.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
import kotlin.math.sqrt fun main() { print("Ingresa un numero : ") val n = readln().toInt() evaluateNumber(n) } fun evaluateNumber(number:Int){ if (number < 0){ println("Ingresa un numero entero") } else { println("$number ${isPrime(number)}, ${isFibonacci(number)} y ${isPar(number)}") } } fun isPrime(n: Int): String { if (n == 2) { return "es primo" } else if (n < 2 || n % 2 == 0) { return "no es primo" } for (i in 3..sqrt(n.toDouble()).toInt() step 2) { if (n % i == 0) return "no es primo" } return "es primo" } fun isFibonacci(n:Int):String{ var a = 0 var b = 1 var c = a + b while (c <= n){ if (c == n){ return "es fibonacci" } else { a = b b = c c = a + b } } return "no es fibonacci" } fun isPar(n:Int):String{ if (n % 2 == 0){ return "es par" } return "es impar" }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
989
retos-programacion-2023
Apache License 2.0
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day13/Game.kt
jrhenderson1988
289,786,400
false
{"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37}
package com.github.jrhenderson1988.adventofcode2019.day13 class Game(private val intCodeComputer: IntCodeComputer) { fun totalBlocksOnScreen(): Int { val cpu = intCodeComputer return generateSequence { Pair(cpu.execute()!!, cpu.execute()!!) to (Tile.fromValue(cpu.execute()!!)) } .takeWhile { !cpu.terminated } .toMap() .count { it.value == Tile.BLOCK } } fun play(): Long { val cpu = intCodeComputer cpu.instructions[0] = 2 return generateSequence(State()) { it.update( cpu.execute(it.input())!!, cpu.execute(it.input())!!, cpu.execute(it.input())!! ) } .takeWhile { !cpu.terminated } .last() .score } data class State( val board: Map<Pair<Long, Long>, Tile> = mapOf(), val score: Long = 0L, val ballPosition: Pair<Long, Long>? = null, val paddlePosition: Pair<Long, Long>? = null ) { companion object { const val PADDLE_POSITION_NEUTRAL = 0L const val PADDLE_POSITION_LEFT = -1L const val PADDLE_POSITION_RIGHT = 1L } fun input() = when { paddlePosition == null || ballPosition == null -> PADDLE_POSITION_NEUTRAL paddlePosition.first < ballPosition.first -> PADDLE_POSITION_RIGHT paddlePosition.first > ballPosition.first -> PADDLE_POSITION_LEFT else -> PADDLE_POSITION_NEUTRAL } fun update(x: Long, y: Long, t: Long) = when { x == -1L && y == 0L -> State(board, t, ballPosition, paddlePosition) Tile.fromValue(t) == null -> this t == Tile.BALL.id -> State(board.plus(Pair(x, y) to Tile.BALL), score, Pair(x, y), paddlePosition) t == Tile.PADDLE.id -> State(board.plus(Pair(x, y) to Tile.PADDLE), score, ballPosition, Pair(x, y)) else -> State(board.plus(Pair(x, y) to Tile.fromValue(t)!!), score, ballPosition, paddlePosition) } } }
0
Kotlin
0
0
7b56f99deccc3790c6c15a6fe98a57892bff9e51
2,123
advent-of-code
Apache License 2.0
src/main/Main.kt
somei-san
476,528,544
false
{"Kotlin": 12475}
import java.util.* fun main(args: Array<String>) { abc000X() } fun abc000X() { System.err.println("!!!!!!!!!!!テスト!!!!!!!!!") val N = readLine()!! val As = readLine()!!.split(" ").map { it.toInt() }.sorted() System.err.println(As) val sets = mutableListOf<kakeru>() for (k in 0 until As.count() - 2) for (j in k + 1 until As.count() - 1) for (i in j + 1 until As.count()) if (As[i] == As[j] * As[k]) sets.add(kakeru(As[i], As[j], As[k])) sets.forEach { System.err.println(it) } // System.err.println(Ws) println(sets.count() * 2) } data class kakeru(val i: Int, val j: Int, val k: Int) data class waru(val i: Int, val j: Int, val k: Int) fun ng() { println("No") } fun ok() { println("Yes") } // 約数のList fun divisor(value: Long): List<Long> { val max = Math.sqrt(value.toDouble()).toLong() return (1..max) .filter { value % it == 0L } .map { listOf(it, value / it) } .flatten() .sorted() } // 範囲内の素数を取得 // fromだけ指定すると戻り値の個数で素数判定ができる fun prime(from: Long, to: Long = from): List<Long> { return (from..to).filter { i -> val max = Math.sqrt(i.toDouble()).toLong() (2..max).all { j -> i % j != 0L } } } // 渡された値が素数か判定 fun isPrime(source: Int): Boolean { return prime(source.toLong()).any() } // 素因数分解 fun decom(value: Long): List<Long> { if (value == 1L) return listOf(1) val max = Math.sqrt(value.toDouble()).toLong() return prime(2, max).filter { value % it == 0L } } // 最大公約数 fun gcd(a: Long, b: Long): Long { return if (a % b == 0L) b else gcd(b, a % b) } // 文字列を入れ替え fun swap(base: String, a: String, b: String): String { return base.map { when (it) { a.toCharArray()[0] -> b b.toCharArray()[0] -> a else -> it.toString() } }.joinToString() } /** * リストをスタックに変換する * @param list リスト * @return スタック */ fun listToStack(list: List<Int>): Stack<Int> { // スタック val stack = Stack<Int>() for (e in list) { stack.push(e) } return stack } /** * ユークリッドの互除法を用いて、最大公約数を導出する * @param list 最大公約数を求める対象となる数が格納されたリスト * @return 最大公約数 */ fun gcd(list: List<Int>): Int { // 最大公約数を求める対象となる数が格納されたスタック val stack = listToStack(list) // ユークリッドの互除法を用いて、最大公約数を導出する // (最終的にスタック内に1つだけ数が残り、それが最大公約数となる) while (1 < stack.size) { // スタックから2つの数をpop val pops = (0 until 2).map { stack.pop() } // スタックからpopした2つの数のうち、小さい方の数のインデックス val minIndex = if (pops[1] < pops[0]) { 1 } else { 0 } // スタックからpopした2つの数のうち、小さい方の数をpush stack.push(pops[minIndex]) // スタックからpopした2つの数の剰余 val r = pops[(minIndex + 1) % 2] % pops[minIndex] // スタックからpopした2つの数に剰余があるならば、それをpush if (0 < r) { stack.push(r) } } // 最大公約数を返す return stack.pop() } /** * 最小公倍数を導出する * @param list 最小公倍数を求める対象となる数が格納されたリスト * @return 最小公倍数 */ fun lcm(list: List<Int>): Int { // 最大公約数を求める対象となる数が格納されたスタック val stack = listToStack(list) // 最小公倍数を導出する // (最終的にスタック内に1つだけ数が残り、それが最小公倍数となる) while (1 < stack.size) { // スタックから2つの数をpop val pops = (0 until 2).map { stack.pop() } // スタックからpopした2つの数の最小公倍数をpush stack.push(pops[0] * pops[1] / gcd(pops)) } // 最小公倍数を返す return stack.pop() }
0
Kotlin
0
0
43ea45fc0bc135d6d33af1fd0d7de6a7b3b651ec
4,465
atcoder-kotline
MIT License
src/main/kotlin/com/londogard/summarize/summarizers/TfIdfSummarizer.kt
londogard
222,868,849
false
null
package com.londogard.summarize.summarizers import com.londogard.summarize.extensions.mutableSumByCols import smile.nlp.* import kotlin.math.roundToInt internal class TfIdfSummarizer : Summarizer { private fun getSentences(text: String): List<String> = text.normalize().sentences().toList() override fun summarize(text: String, ratio: Double): String { val sentences = getSentences(text) return summarize(sentences, (sentences.size * ratio).roundToInt().coerceAtLeast(1)) } override fun summarize(text: String, lines: Int): String = summarize(getSentences(text), lines) private fun summarize(sentences: List<String>, lines: Int): String { val corpus = sentences.map { it.bag() } // bag includes stemming val words = corpus.flatMap { bag -> bag.keys }.distinct() val bags = corpus.map { vectorize(words.toTypedArray(), it) } val vectors = tfidf(bags) val vector = vectors.mutableSumByCols() val normalizedVector = vector.max() ?.let { max -> List(vector.size) { i -> vector[i] / max } } ?: vector return sentences .asSequence() .map { sen -> sen.words().fold(0.0) { acc, word -> val idx = word.indexOf(word) if (idx == -1) acc + 0 else acc + normalizedVector[idx] } } .withIndex() .sortedByDescending { it.value } .take(lines) .map { it.index to sentences[it.index] } .sortedBy { it.first } .map { it.second } .joinToString("\n") } }
3
Kotlin
0
2
521818ed9057e5ffb58a8ae7b3f0a6c3269e93cc
1,640
summarize-kt
Apache License 2.0
src/Day10.kt
fouksf
572,530,146
false
{"Kotlin": 43124}
import java.lang.Exception import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { var register = 1 var result = 0 var cycle = 1 val cyclesOfInterest = arrayListOf(20, 60, 100, 140, 180, 220) for (line in input) { if (cycle in cyclesOfInterest) { result += cycle * register } if (line == "noop") { cycle++ } else { if (cycle + 1 in cyclesOfInterest) { result += (cycle + 1) * register } cycle += 2 register += line.split(" ")[1].toInt() } } return result } fun draw(screen: List<MutableList<String>>, spriteIndex: Int, cycle: Int) { screen[cycle / 40].add(if (abs(cycle % 40 - spriteIndex) < 2) "#" else ".") } fun part2(input: List<String>): Unit { var spriteIndex = 1 var cycle = 0 val screen = List<MutableList<String>>(6) { mutableListOf() } for (line in input) { draw(screen, spriteIndex, cycle) if (line == "noop") { cycle++ } else { cycle += 1 draw(screen, spriteIndex, cycle) cycle += 1 spriteIndex += line.split(" ")[1].toInt() } } for (line in screen) { println(line.joinToString("")) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") // println(part1(testInput)) part2(testInput) val input = readInput("Day10") // println(part1(input)) part2(input) }
0
Kotlin
0
0
701bae4d350353e2c49845adcd5087f8f5409307
1,730
advent-of-code-2022
Apache License 2.0
src/Day08.kt
kedvinas
572,850,757
false
{"Kotlin": 15366}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { val grid = input.map { it.toCharArray().map { it.digitToInt() } } val visible = Array(grid.size) { Array(grid.size) { 0 } } for (i in 0 until grid.size) { var max = -1 for (j in 0 until grid.size) { if (grid[i][j] > max) { visible[i][j]++ max = grid[i][j] } } } for (i in 0 until grid.size) { var max = -1 for (j in grid.size - 1 downTo 0) { if (grid[i][j] > max) { visible[i][j]++ max = grid[i][j] } } } for (i in 0 until grid.size) { var max = -1 for (j in 0 until grid.size) { if (grid[j][i] > max) { visible[j][i]++ max = grid[j][i] } } } for (i in grid.indices) { var max = -1 for (j in grid.size - 1 downTo 0) { if (grid[j][i] > max) { visible[j][i]++ max = grid[j][i] } } } var sum = 0 for (x in 0 until visible.size) { for (y in 0 until visible.size) { if (visible[x][y] > 0) { sum++ } } } return sum } fun part2(input: List<String>): Int { val grid = input.map { it.toCharArray().map { it.digitToInt() } } var max = 0 for (i in 1 until grid.size - 1) { for (j in 1 until grid.size - 1) { var left = 0 var right = 0 var top = 0 var bottom = 0 for (k in i + 1 until grid.size) { bottom++ if (grid[i][j] <= grid[k][j]) { break } } for (k in i - 1 downTo 0) { top++ if (grid[i][j] <= grid[k][j]) { break } } for (k in j + 1 until grid.size) { right++ if (grid[i][j] <= grid[i][k]) { break } } for (k in j - 1 downTo 0) { left++ if (grid[i][j] <= grid[i][k]) { break } } max = max(max, left * right * top * bottom) } } return max } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
04437e66eef8cf9388fd1aaea3c442dcb02ddb9e
3,063
adventofcode2022
Apache License 2.0
solutions/aockt/y2023/Y2023D25.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.parse import io.github.jadarma.aockt.core.Solution import kotlin.random.Random object Y2023D25 : Solution { /** * The internal wiring of a Snow Machine. * @property nodes The names of the parts. * @property edges Pairs of parts, determining bidirectional connections. */ private class SnowMachineWiring(val nodes: Set<String>, val edges: Set<Pair<String, String>>) /** Parses the [input] and return the [SnowMachineWiring]. */ private fun parseInput(input: String): SnowMachineWiring = parse { val lines = input .lineSequence() .map { line -> line.split(": ", " ").filterNot(String::isBlank) } .toList() val nodes = lines.flatten().toSet() val edges = lines.flatMap { line -> line.drop(1).map { line.first() to it } }.toSet() SnowMachineWiring(nodes, edges) } /** * Finds the two subsets of machine parts, by removing three wires. * * Notes: * - Implemented using [Karger's Algorithm](https://en.wikipedia.org/wiki/Karger%27s_algorithm). * - A solution will eventually be found, but speed depends on luck because graph contractions are chosen at random. * - Implementation adapted from [u/4HbQ](https://old.reddit.com/r/adventofcode/comments/18qbsxs/2023_day_25_solutions/ketzp94/)'s * beautiful Python rendition. * * @param random The random instance to use when deciding which nodes to contract. Has default. * @return The product of the sizes of the two subsets after removing the 3 bridge edges. */ private fun SnowMachineWiring.solve(random: Random = Random): Int { while (true) { // We start by having each node be its own subgroup, nothing interconnected yet. val subgroups: MutableSet<MutableSet<String>> = nodes.map { mutableSetOf(it) }.toMutableSet() val subgroupContaining = { node: String -> subgroups.first { node in it } } // We pick random edges to contract. Since the actual graph has no isolated nodes, it is guaranteed we will // reach two subgroups before we run out of edges, so instead of picking ones at random, we shuffle the // order, to avoid processing the same edge twice. val randomEdge = edges.shuffled(random).map { it.toList() }.iterator() // While we still have more than two subgroups, we contract edges: // - Picking a random edge, check if its nodes are part of the same subgroup. // - If they are, there's nothing to do, as the nodes in that subgroup are already interconnected. // - Otherwise, we now know that every node from s1 has a way of reaching s2 via this edge and vice-versa. // - We can therefore join them in a single subgroup and discard the other, shrinking our subgroup count. while (subgroups.size > 2) { val (s1, s2) = randomEdge.next().map(subgroupContaining) if (s1 === s2) continue s1.addAll(s2) subgroups.removeIf { it === s2 } // subgroups.remove(s2) does NOT work! } // On a correctly partitioned wiring graph, the only edges that cross them are the three wires we need to // cut. If we find a fourth, it means we did not partition correctly and should try again. if (edges.count { (a, b) -> subgroupContaining(a) != subgroupContaining(b) } > 3) continue return subgroups.map { it.size }.reduce(Int::times) } } // Seed unnecessary for solution to work, but this one solves it fast for my input, and it helps with not wasting // time when running unit tests. Without a seed, returns an answer in 5-20 seconds. override fun partOne(input: String) = parseInput(input).solve(Random(seed = -8_285_910_637_769_521_595L)) }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
3,910
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/org/example/e3fxgaming/adventOfCode/aoc2023/day05/Day05.kt
E3FxGaming
726,041,587
false
{"Kotlin": 38290}
package org.example.e3fxgaming.adventOfCode.aoc2023.day05 import org.example.e3fxgaming.adventOfCode.utility.Day import org.example.e3fxgaming.adventOfCode.utility.InputParser import org.example.e3fxgaming.adventOfCode.utility.MultiLineInputParser import java.util.PriorityQueue class Day05(input: String) : Day<Day05.Almanac, Day05.Almanac> { data class Almanac( val seeds: List<Long>, val resourceMaps: List<List<Pair<LongRange, LongRange>>> ) override val partOneParser: InputParser<Almanac> = object : MultiLineInputParser<Almanac>(input) { override fun parseFullInput(fullInput: String): List<Almanac> { val components = fullInput.split(System.lineSeparator().repeat(2)) val seeds = components.first().substringAfter("seeds: ").split(' ').map(String::toLong) val resourceMaps = components.drop(1).map { componentDesc -> val componentLines = componentDesc.split('\n') componentLines.drop(1).map { tripletLine -> tripletLine.split(' ').map(String::toLong).let { (destRangeStart, sourceRangeStart, size) -> sourceRangeStart..<(sourceRangeStart + size) to destRangeStart..<(destRangeStart + size) } }.sortedBy { it.first.first } } return listOf(Almanac(seeds, resourceMaps)) } } override val partTwoParser: InputParser<Almanac> = partOneParser override fun solveFirst(given: List<Almanac>): String = solve(given.first(), given.first().seeds.map { it..it }) private fun List<LongRange>.sortedByStartAndEnd() = sortedWith( compareBy(LongRange::first) .thenComparing(LongRange::last) ) private fun solve(almanac: Almanac, sections: List<LongRange>): String { var currentSections = sections.sortedByStartAndEnd() almanac.resourceMaps.forEach { conversionMap -> //map to next resource currentSections = buildList { val toTransform: PriorityQueue<LongRange> = PriorityQueue(compareBy { it.first }) toTransform.addAll(currentSections) for ((sourceRange, targetRange) in conversionMap) { while (toTransform.isNotEmpty() && toTransform.peek().first <= sourceRange.last) { val currentToTransform = toTransform.remove() //currentToTransform part before sourceRange if (currentToTransform.first < sourceRange.first) { val rangeStart = currentToTransform.first val elementsInCurrentToTransform = currentToTransform.last - currentToTransform.first + 1 val rangeEnd = (rangeStart + elementsInCurrentToTransform - 1) .coerceAtMost(sourceRange.first - 1) add(rangeStart..rangeEnd) } //currentToTransform part in sourceRange if (currentToTransform.last > sourceRange.first) { val subRangeStart = currentToTransform.first.coerceAtLeast(sourceRange.first) val subRangeEnd = currentToTransform.last.coerceAtMost(sourceRange.last) val sourceTargetOffset = targetRange.first - sourceRange.first val translatedStart = subRangeStart + sourceTargetOffset val translatedEnd = subRangeEnd + sourceTargetOffset add(translatedStart..translatedEnd) } //currentToTransform part after sourceRange if (currentToTransform.last > sourceRange.last) { val subRangeStart = sourceRange.last + 1 val subRangeEnd = currentToTransform.last toTransform.add(subRangeStart..subRangeEnd) } } if (toTransform.isEmpty()) break } while (toTransform.isNotEmpty()) { add(toTransform.remove()) } } //condense current ranges currentSections = buildList { currentSections.sortedByStartAndEnd().forEach { when { isNotEmpty() && (it.first in last() || it.first == last().last + 1) -> { val previous = removeLast() add(previous.first..(previous.last.coerceAtLeast(it.last))) } else -> add(it) } } } } return currentSections.first().first.toString() } override fun solveSecond(given: List<Almanac>): String = solve(given.first(), given.first().seeds.chunked(2).map { it[0]..<(it[0] + it[1]) }) } fun main() = Day05( Day05::class.java.getResource("/2023/day05/realInput1.txt")!!.readText() ).runBoth()
0
Kotlin
0
0
3ae9e8b60788733d8bc3f6446d7a9ae4b3dabbc0
5,170
adventOfCode
MIT License
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day13/Day13.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2020.day13 import eu.janvdb.aocutil.kotlin.ChineseRemainderTheoremEquation import eu.janvdb.aocutil.kotlin.ModuloMath import java.math.BigInteger //const val TIME_ = 939L //const val BUSSES = "7,13,x,x,59,x,31,19" const val TIME = 1000052L const val BUSSES = "23,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,37,x,x,x,x,x,863,x,x,x,x,x,x,x,x,x,x,x,19,13,x,x,x,17,x,x,x,x,x,x,x,x,x,x,x,29,x,571,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,41" fun main() { part1() part2() } private fun part1() { val busses = BUSSES.split(",").filter { it != "x" }.map(String::toInt) val earliestStartTimesPerBus = busses.map { Pair(it, (TIME + it - 1) / it * it) } val earliestBus = earliestStartTimesPerBus.minByOrNull { it.second }!! println(earliestBus.first * (earliestBus.second - TIME)) } private fun part2() { val startTimes = BUSSES.split(",") .mapIndexed { index, value -> Pair(index, value) } .filter { it.second != "x" } .map { StartTime(it.second.toLong().toBigInteger(), it.first.toLong().toBigInteger()) } // Equations: (t + 0) mod 7 = 0, (t + 1) mod 13 = 0, (t + 4) mod 59 = 0, (t + 6) mod 31 = 0, (t + 7) mod 19 = 0 // Or: t = 0 (mod 7), t = 12 (mod 13), t = 54 (mod 59), t = 25 (mod 31), t = 12 (mod 19) // Since the values are pairwise coprime, this can be solved with the Chinese Remainder Theorem. val equations = startTimes.map(StartTime::asChineseTheoremEquation) val solution = ModuloMath.solveChineseRemainderTheorem(equations) println(solution) } data class StartTime(val busNumber: BigInteger, val startTime: BigInteger) { fun asChineseTheoremEquation() : ChineseRemainderTheoremEquation { return ChineseRemainderTheoremEquation(ModuloMath.minusModN(busNumber, startTime, busNumber), busNumber) } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,785
advent-of-code
Apache License 2.0
src/main/kotlin/aoc2023/day20/day20Solver.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 94973}
package aoc2023.day20 import lib.* suspend fun main() { setupChallenge().solveChallenge() } fun setupChallenge(): Challenge<List<Module>> { return setup { day(20) year(2023) //input("example.txt") parser { it.readLines() .map { val parts = it.split(" -> ") Module(parts[0][0], parts[0].drop(1), parts[1].split(", ")) } } partOne { modules = it.associateBy { it.name } var outputLows = 0L var outputHighs = 0L repeat(1000) { val toSend = mutableListOf(Signal("button", "roadcaster", SignalType.Low)) while (toSend.any()) { val signal = toSend.first() toSend.remove(signal) if (modules.containsKey(signal.to)) { toSend.addAll(modules[signal.to]!!.handle(signal.from, signal.type)) } else { if(signal.type == SignalType.High) outputHighs++ else outputLows++ } } } ((modules.values.sumOf { it.lowSignals } + outputLows) * (modules.values.sumOf { it.highSignals } + outputHighs)).toString() } partTwo { modules = it.associateBy { it.name } modules.forEach { it.value.initConnections() } //Lots of assumptions here - that our output "rx" is dependent on exactly one conjunction outputting "low"... val toMonitor = modules.values.first { it.destinations.contains("rx") }.inputs!!.keys val iterationTracker = toMonitor.associateWith { 0 }.toMutableMap() var i = 0 while (iterationTracker.any { it.value < 1 }) { i++ val toSend = mutableListOf(Signal("button", "roadcaster", SignalType.Low)) while (toSend.any()) { val signal = toSend.first() toSend.remove(signal) if (modules.containsKey(signal.to)) { if(signal.from in toMonitor && signal.type == SignalType.High) { val prev = iterationTracker[signal.from]!! iterationTracker[signal.from] = i - iterationTracker[signal.from]!! if(prev != 0 && iterationTracker[signal.from] != prev) { throw Exception("Irregularly output frequency") } } toSend.addAll(modules[signal.to]!!.handle(signal.from, signal.type)) } } } iterationTracker.values.fold(1L) {s, n -> s * n}.toString() } } } var modules = mapOf<String, Module>() enum class SignalType { High, Low } data class Signal(val from: String, val to: String, val type: SignalType) data class Module(val ope: Char, val name: String, val destinations: List<String>) { var highSignals = 0L var lowSignals = 0L var state = false var inputs: MutableMap<String, SignalType>? = null fun handle(origin: String, signal: SignalType): List<Signal> { if (signal == SignalType.High) highSignals++ else lowSignals++ val toSend = when (ope) { '%' -> flipFlop(signal) '&' -> conjunction(origin, signal) 'b' -> destinations.map { Signal(name, it, signal) } else -> throw Exception("Unknown operation $ope") } return toSend } fun initConnections() { if(ope == '&') { inputs = modules.filter { it.value.destinations.contains(name) }.keys.associateWith { SignalType.Low } .toMutableMap() } } private fun flipFlop(signal: SignalType): List<Signal> { if (signal == SignalType.High) return listOf() state = !state return destinations.map { Signal(name, it, if (state) SignalType.High else SignalType.Low) } } private fun conjunction(origin: String, signal: SignalType): List<Signal> { if(inputs == null) { initConnections() } inputs!![origin] = signal return destinations.map { Signal( name, it, if (inputs!!.values.all { it == SignalType.High }) SignalType.Low else SignalType.High ) } } }
0
Kotlin
0
0
a77584ee012d5b1b0d28501ae42d7b10d28bf070
4,495
AoC-2023-DDJ
MIT License
src/main/kotlin/day13/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day13 import util.* data class PacketPair(val left: Packet, val right: Packet) open class Packet data class IntValue(val value: Int): Packet() { override fun toString(): String = value.toString() } data class ListValue(val values: List<Packet>): Packet() { constructor(value: Packet): this(listOf(value)) override fun toString(): String = "[${values.joinToString(";")}]" } fun isEmptyList(packet: Packet): Boolean = packet is ListValue && packet.values.isEmpty() fun readListItems(str: String): List<String> { var level = 1 val items = mutableListOf<String>() val buffer = StringBuilder() for (char in str.substring(1, str.length - 1)) { if (char == '[') { level += 1 } else if (char == ']') { level -= 1 } else if (char == ',' && level == 1) { items.add(buffer.toString()) buffer.clear() continue } buffer.append(char) } if (buffer.isNotEmpty()) items.add(buffer.toString()) return items } fun parsePacket(str: String): Packet { return when { str.isBlank() -> throw IllegalArgumentException("Got blank") str == "[]" -> ListValue(emptyList()) str.startsWith("[") -> { val values = readListItems(str).map { parsePacket(it) } if (values.isEmpty()) ListValue(emptyList()) else ListValue(values) } else -> IntValue(str.toInt()) } } fun compareTo(packetPair: PacketPair, level: Int = 0): Int { debug("compare $packetPair", level) if (packetPair.left is ListValue && packetPair.right is ListValue) { for (i in 0 until packetPair.left.values.size) { val leftValue = packetPair.left.values.get(i) val righValue = packetPair.right.values.getOrNull(i) if (leftValue == righValue) { continue } if (isEmptyList(leftValue)) { debug("left side ran out of items, returning true", 2) return 1 } if (righValue == null || isEmptyList(righValue)) { debug("right side ran out of items, returning false", 2) return -1 } val compareToResult = compareTo(PacketPair(leftValue, righValue), level + 1) if (compareToResult == 0) { // value is same, so we need to compare next values continue } return compareToResult } if (level == 0) { debug("left side ran out of items, returning true", 2) return 1 } } else if (packetPair.left is IntValue && packetPair.right is IntValue) { return packetPair.right.value - packetPair.left.value } else if (packetPair.left is IntValue && packetPair.right is ListValue) { debug("mixed types, convert to list", level + 1) return compareTo(PacketPair(ListValue(packetPair.left), packetPair.right), level + 1) } else if (packetPair.left is ListValue && packetPair.right is IntValue) { debug("mixed types, convert to list", level + 1) return compareTo(PacketPair(packetPair.left, ListValue(packetPair.right)), level + 1) } // Comparison of equal items at level deeper than 1. Returning 0 leads to comparing next values. return 0 } fun parsePacketPair(inputLines: List<String>): PacketPair = PacketPair(parsePacket(inputLines[0]), parsePacket(inputLines[1])) fun part1(): Int { val packetPairs = readInput("day13") .chunked(3) .map { parsePacketPair(it) } val correctIndexes = packetPairs.foldIndexed(mutableListOf<Int>()) { index, acc, pair -> if (compareTo(pair) >= 1) acc.add(index + 1) acc } println(correctIndexes) println(correctIndexes.sum()) return correctIndexes.sum() } fun part2(): Int { var packets = readTestInput("day13") .filter { it.isNotBlank() } .map { parsePacket(it) } val divider1 = parsePacket("[[2]]") val divider2 = parsePacket("[[6]]") packets = packets + listOf(divider1, divider2) val sortedPackets = packets.sortedWith { left, right -> compareTo(PacketPair(left, right)) }.reversed() val index1 = sortedPackets.indexOf(divider1) + 1 val index2 = sortedPackets.indexOf(divider2) + 1 return index1 * index2 } fun main() { equals(13, part1()) equals(140, part2()) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
4,461
advent-of-code-2022
MIT License
src/Day01.kt
yturkkan-figure
434,994,594
false
{"Kotlin": 3305}
fun main() { fun part1(input: List<String>): Int { var count = 0 var cur: Int = input[0].toInt() for (i in 1..input.size-1){ if (input[i].toInt() > cur){ count += 1 } cur = input[i].toInt() if (i == input.size-1){ break } } return count } fun part2(input: List<String>): Int { var count = 0 var cur: Int if (input.size < 3) { return 0 } else { cur = input[0].toInt() + input[1].toInt() + input[2].toInt() } for (i in 3..input.size-1){ //1,2,3,4,5,6 val next = cur - input[i - 3].toInt() + input[i].toInt() if (next > cur){ count += 1 } cur = next if (i == input.size-1){ break } } return count } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 7) check(part2(testInput) == 5) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c7bd9bfeba3f31833a0df822ad52add02ec1a0d
1,184
advent-of-code-kotlin-template
Apache License 2.0
kotlin/src/main/kotlin/dev/egonr/leetcode/03_LongestSubstring.kt
egon-r
575,970,173
false
null
package dev.egonr.leetcode /* Medium Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. Constraints: 0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces. */ class LongestSubstring { fun test() { println(lengthOfLongestSubstring("abcabcbb")) // "abc" length 3 println(lengthOfLongestSubstring("bbbbb")) // "b" length 1 println(lengthOfLongestSubstring("pwwkew")) // "wke" length 3 println(lengthOfLongestSubstring(" ")) // " " length 1 println(lengthOfLongestSubstring("au")) // "au" length 2 println(lengthOfLongestSubstring("dvdf")) // "vdf" length 3 println(lengthOfLongestSubstring("anviaj")) // "nviaj" length 5 } fun lengthOfLongestSubstring(s: String): Int { if (s.isEmpty()) { return 0 } var longestSubstrCount = 1 val substr = HashSet<Char>() var checkedUntil = 0 var i = 0 while (i < s.length) { val currentChar = s[i] println("$s -> $currentChar@$i") if (substr.contains(currentChar) && i > checkedUntil) { val substrCount = substr.count() if (substrCount > longestSubstrCount) { longestSubstrCount = substrCount } println(substr) i -= substr.count() i++ checkedUntil = i substr.clear() } else { substr.add(currentChar) i++ } } val substrCount = substr.count() if (substrCount > longestSubstrCount) { println(substr) longestSubstrCount = substrCount } return longestSubstrCount } }
0
Kotlin
0
0
b9c59e54ca2d1399d34d1ee844e03c16a580cbcb
2,211
leetcode
The Unlicense
kotlin/0028-find-the-index-of-the-first-occurrence-in-a-string.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
/* * KMP algorithm */ class Solution { fun strStr(haystack: String, needle: String): Int { if(needle == "") return 0 val lps = IntArray(needle.length) var prevLPS = 0 var i = 1 while(i < needle.length) { if(needle[i] == needle[prevLPS]) { lps[i] = prevLPS + 1 prevLPS++ i++ }else if(prevLPS == 0) { lps[i] = 0 i++ }else{ prevLPS = lps[prevLPS - 1] } } i = 0 var j = 0 while (i < haystack.length) { if(haystack[i] == needle[j]){ i++ j++ }else if(j == 0){ i++ }else{ j = lps[j - 1] } if(j == needle.length) { return i - needle.length } } return -1 } } /* * Rabin-Karp string hashing with bad hash */ class Solution { fun strStr(haystack: String, needle: String): Int { if(needle.length > haystack.length) return -1 var needleHash = 0 var hayHash = 0 for(i in 0..needle.lastIndex) { needleHash += needle[i] - 'a' hayHash += haystack[i] - 'a' } for(i in 0..(haystack.length - needle.length)) { if(hayHash == needleHash) { for(j in 0..needle.lastIndex) { if(haystack[i + j] != needle[j]) break if(j == needle.lastIndex) return i } } if(i == haystack.length - needle.length) break hayHash -= haystack[i] - 'a' hayHash += haystack[i + needle.length] - 'a' } return -1 } } /* * Rabin-karp with proper hash. q should ideally be chosen as an high prime number to avoid no. of collisions. */ class Solution { fun strStr(haystack: String, needle: String): Int { if(needle.length > haystack.length) return -1 val q = 101 val d = 256 var needleHash = 0 var hayHash = 0 var hash = 1 for (i in 0..needle.lastIndex) hash = (hash * d) % q for(i in 0..needle.lastIndex) { needleHash = (d * needleHash + (needle[i] - 'a')) % q hayHash = (d * hayHash + (haystack[i] - 'a')) % q } for(i in 0..(haystack.length - needle.length)) { if(hayHash == needleHash) { for(j in 0..needle.lastIndex) { if(haystack[i + j] != needle[j]) break if(j == needle.lastIndex) return i } } if(i == haystack.length - needle.length) break hayHash = (d * hayHash - ((haystack[i] - 'a') * hash) + (haystack[i + needle.length] - 'a')) % q if(hayHash < 0) hayHash += q } return -1 } } /* * Using Trie to match pattern */ class TrieNode() { val child = arrayOfNulls<TrieNode>(26) var isEnd = false } class Solution { fun strStr(haystack: String, needle: String): Int { if(needle == "") return 0 var root: TrieNode? = TrieNode() var current = root for(c in needle){ if(current?.child?.get(c - 'a') == null) current?.child?.set(c - 'a', TrieNode()) current = current?.child?.get(c - 'a') } current?.isEnd = true var i = 0 while(i < haystack.length + 1 - needle.length) { current = root?.child?.get(haystack[i] - 'a') var j = i while(current != null) { if(current.isEnd == true) return i j++ if(j - i < needle.length) current = current?.child?.get(haystack[j] - 'a') else break } i++ } return -1 } } /* * Brute force */ class Solution { fun strStr(haystack: String, needle: String): Int { if(needle == "") return 0 for(i in 0..(haystack.length - needle.length)) { for(j in 0..needle.lastIndex) { if(haystack[i + j] != needle[j]) break if(j == needle.lastIndex) return i } } return -1 } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
4,565
leetcode
MIT License
src/Day01.kt
AleksanderBrzozowski
574,061,559
false
null
fun main() { val testInput = elves("Day01_test") println(testInput.maxBy { it.calories.sum() }.calories.sum()) val input = elves("Day01") val (first, second, third) = input.map { it.calories.sum() }.sortedByDescending { it } println(first + second + third) } private data class Elf(val calories: List<Int>) private fun elves(name: String): List<Elf> = readInput(name) .fold(listOf(Elf(calories = emptyList()))) { elves, input -> if (input == "") { return@fold elves + Elf(calories = emptyList()) } val currentElf = elves.last() elves.replaceLast(currentElf.copy(calories = currentElf.calories + input.toInt())) }
0
Kotlin
0
0
161c36e3bccdcbee6291c8d8bacf860cd9a96bee
688
kotlin-advent-of-code-2022
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day5/day5.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day5 import kotlin.math.floor class Range(var lowerRange: Int, var upperRange: Int) { fun select(upper: Boolean) { val mid: Int = floor((lowerRange + upperRange) / 2.0).toInt() if (upper) { lowerRange = mid + 1 } else { upperRange = mid } } fun closed(): Boolean { return lowerRange == upperRange } } fun getSeatId(seat: String): Int { val rowRange = Range(0, 127) for (i in 0..7) { when (seat[i]) { 'F' -> rowRange.select(false) 'B' -> rowRange.select(true) } } val colRange = Range(0, 7) for (i in 7..9) { when (seat[i]) { 'L' -> colRange.select(false) 'R' -> colRange.select(true) } } assert(rowRange.closed()) assert(colRange.closed()) return rowRange.lowerRange * 8 + colRange.lowerRange } fun part2(seatsIds: List<Int>): Int? { val seats = seatsIds.sorted() seats.asSequence().windowed(2,1).forEach { if(it[0] + 1 != it[1]){ return it[0]+1 } } return null } fun main() { val seats = {}::class.java.getResource("/day5.in") .readText() .split("\n") assert(getSeatId("BFFFBBFRRR") == 567) assert(getSeatId("FFFBBBFRRR") == 119) assert(getSeatId("BBFFBBFRLL") == 820) val seatsIds = seats.map { getSeatId(it) } println("Answer part 1: ${seatsIds.maxOrNull()}") println("Answer part 2: ${part2(seatsIds)}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
1,524
advent-of-code-2020
Do What The F*ck You Want To Public License
2020/src/year2020/day06/Day06.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2020.day06 import util.readAllLines private fun getAnswers(filename: String): List<Set<Char>> { val result = mutableListOf<Set<Char>>() val set = mutableSetOf<Char>() readAllLines(filename).map { line -> if (line.isBlank()) { if (set.isNotEmpty()) { result.add(set.toSet()) set.clear() } } else { line.forEach { set.add(it) } } } if (set.isNotEmpty()) { result.add(set.toSet()) } return result } private fun getEveryoneAnswers(filename: String): List<Set<Char>> { val result = mutableListOf<Set<Char>>() var set: Set<Char> = setOf() var lineSet: Set<Char> var firstPass = true readAllLines(filename).map { line -> if (line.isBlank()) { result.add(set) firstPass = true } else { lineSet = line.toSet() if (firstPass) { set = lineSet firstPass = false } else if (set.isNotEmpty()) { set = set.intersect(lineSet) } } } result.add(set) return result } fun main() { var count: Int count = getAnswers("test.txt").sumBy { it.size } println(count) count = getAnswers("input.txt").sumBy { it.size } println(count) count = getEveryoneAnswers("test.txt").sumBy { it.size } println(count) count = getEveryoneAnswers("input.txt").sumBy { it.size } println(count) }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
1,519
adventofcode
MIT License
src/medium/ArrayAndStrings/776-3Sum.kt
diov
170,882,024
false
null
fun main() { // val nums = intArrayOf(-1, 0, 1, 2, -1, -4) val nums = intArrayOf(0, 0, 0, 0) // val nums = intArrayOf(-1, 0, 1, 2, -1, -4) // val nums = intArrayOf(3, 0, -2, -1, 1, 2) // val nums = intArrayOf(-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6) println(threeSum(nums)) } fun threeSum(nums: IntArray): List<List<Int>> { val count = nums.count() if (count < 3) { return emptyList() } val result = mutableListOf<List<Int>>() nums.sort() var index = 0 while (index < count) { val i = nums[index] val sum = -i var front = index + 1 var end = count - 1 while (end > front) { when { nums[front] + nums[end] < sum -> front++ nums[front] + nums[end] > sum -> end-- else -> { result.add(listOf(i, nums[front], nums[end])) while (end > front && nums[front + 1] == nums[front]) { front++ } while (end > front && nums[end - 1] == nums[end]) { end-- } front++ end-- } } } while (index + 1 < count && nums[index + 1] == nums[index]) { index++ } index++ } return result }
0
Kotlin
0
0
668ef7d6d1296ab4df2654d5a913a0edabc72a3c
1,396
leetcode
MIT License
src/Day03.kt
Tomcat88
572,566,485
false
{"Kotlin": 52372}
fun main() { fun part1(input: List<String>) = input.sumOf { rucksack -> rucksack.chunked(rucksack.length / 2) .map { it.toSet() } .reduce { acc, e -> acc intersect e } .singleOrNull().priority } fun part2(input: List<String>) = input.chunked(3).sumOf { rucksack -> rucksack.map { it.toSet() } .reduce { acc, e -> acc intersect e } .singleOrNull().priority } val input = readInput("Day03") println(part1(input)) println(part2(input)) } val Char?.priority get() = when(this) { null -> 0 in 'a'..'z' -> code - 'a'.code + 1 in 'A'..'Z' -> code - 'A'.code + 27 else -> error("invalid char: $this") }
0
Kotlin
0
0
6d95882887128c322d46cbf975b283e4a985f74f
799
advent-of-code-2022
Apache License 2.0
2021/src/main/kotlin/de/skyrising/aoc2021/day14/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2021.day14 import de.skyrising.aoc.* import it.unimi.dsi.fastutil.chars.Char2IntOpenHashMap import it.unimi.dsi.fastutil.chars.Char2LongMap import it.unimi.dsi.fastutil.chars.Char2LongOpenHashMap import it.unimi.dsi.fastutil.ints.Int2LongMap import it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap import it.unimi.dsi.fastutil.objects.Object2CharMap import it.unimi.dsi.fastutil.objects.Object2CharOpenHashMap val test = TestInput(""" NNCB CH -> B HH -> N CB -> H NH -> C HB -> C HC -> B HN -> C NN -> C BH -> H NC -> B NB -> B BN -> B BB -> N BC -> B CC -> N CN -> C """) @PuzzleName("Extended Polymerization") fun PuzzleInput.part1v0(): Any { val (start, rules) = parseInput(this) var current = start for (step in 1..10) { val sb = StringBuilder(current.length * 2) for (i in 0 until current.lastIndex) { sb.append(current[i]) val insert = rules.getChar(current.substring(i, i + 2)) if (insert != 0.toChar()) { sb.append(insert) } } sb.append(current.last()) current = sb.toString() } val counts = Char2IntOpenHashMap(26) for (c in current) counts[c]++ val max = counts.maxOf(Map.Entry<Char, Int>::value) val min = counts.minOf(Map.Entry<Char, Int>::value) return max - min } @PuzzleName("Extended Polymerization") fun PuzzleInput.part1v1(): Any { val (start, rules) = parseInput(this) return solveDay14Fast(start, rules, 10) } fun PuzzleInput.part2(): Any { val (start, rules) = parseInput(this) return solveDay14Fast(start, rules, 40) } private fun solveDay14Fast(start: String, rules: Object2CharMap<String>, steps: Int): Long { val lastChar = start.last() var current = Int2LongOpenHashMap(start.length - 1) for (i in 0 until start.lastIndex) { current[pairIndex(start[i], start[i + 1])]++ } //println("start: ${countCharacters(current, lastChar).toSortedMap()}") for (step in 1..steps) { val newCurrent = Int2LongOpenHashMap(current.size * 2) for (e in current.int2LongEntrySet()) { val first = firstOfPair(e.intKey) val last = secondOfPair(e.intKey) val count = e.longValue val middle = rules.getChar(String(charArrayOf(first, last))) if (middle != 0.toChar()) { newCurrent[pairIndex(first, middle)] += count newCurrent[pairIndex(middle, last)] += count } else { newCurrent[e.intKey] += count } } current = newCurrent //println("$step: ${countCharacters(current, lastChar).toSortedMap()}") } val counts = countCharacters(current, lastChar) val max = counts.maxOf(Map.Entry<Char, Long>::value) val min = counts.minOf(Map.Entry<Char, Long>::value) return max - min } private fun pairIndex(a: Char, b: Char) = a.code or (b.code shl 8) private fun firstOfPair(pair: Int) = (pair and 0xff).toChar() private fun secondOfPair(pair: Int) = (pair shr 8).toChar() private fun parseInput(input: PuzzleInput): Pair<String, Object2CharMap<String>> { val start = input.lines[0] val rules = Object2CharOpenHashMap<String>(input.lines.size - 2) for (i in 2 until input.lines.size) { val (a, b) = input.lines[i].split(" -> ") rules[a] = b[0] } return start to rules } private fun countCharacters(pairCounts: Int2LongMap, lastChar: Char): Char2LongMap { val result = Char2LongOpenHashMap() for (e in pairCounts.int2LongEntrySet()) { result[firstOfPair(e.intKey)] += e.longValue } result[lastChar]++ return result }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
3,752
aoc
MIT License
kotlin/structures/FenwickTreeExtended.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package structures object FenwickTreeExtended { // T[i] += value fun add(t: IntArray, i: Int, value: Int) { var i = i while (i < t.size) { t[i] += value i = i or i + 1 } } // sum[0..i] fun sum(t: IntArray, i: Int): Int { var i = i var res = 0 while (i >= 0) { res += t[i] i = (i and i + 1) - 1 } return res } fun createFromArray(a: IntArray): IntArray { val t: IntArray = a.clone() for (i in a.indices) { val j: Int = i or i + 1 if (j < a.size) t[j] += t[i] } return t } // sum[a..b] fun sum(t: IntArray, a: Int, b: Int): Int { return sum(t, b) - sum(t, a - 1) } operator fun get(t: IntArray, i: Int): Int { var i = i var res = t[i] val lca = (i and i + 1) - 1 --i while (i != lca) { res -= t[i] i = (i and i + 1) - 1 } return res } operator fun set(t: IntArray, i: Int, value: Int) { add(t, i, -FenwickTreeExtended[t, i] + value) } /////////////////////////////////////////////////////// // interval add fun add(t: IntArray, a: Int, b: Int, value: Int) { add(t, a, value) add(t, b + 1, -value) } // point query fun get1(t: IntArray, i: Int): Int { return sum(t, i) } /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // interval add fun add(t1: IntArray, t2: IntArray, a: Int, b: Int, value: Int) { add(t1, a, value) add(t1, b, -value) add(t2, a, -value * (a - 1)) add(t2, b, value * b) } // interval query fun sum(t1: IntArray, t2: IntArray, i: Int): Int { return sum(t1, i) * i + sum(t2, i) } /////////////////////////////////////////////////////// // Returns min(p | sum[0,p] >= sum) fun lower_bound(t: IntArray, sum: Int): Int { var sum = sum var pos = 0 var blockSize: Int = Integer.highestOneBit(t.size) while (blockSize != 0) { val p = pos + blockSize - 1 if (p < t.size && t[p] < sum) { sum -= t[p] pos += blockSize } blockSize = blockSize shr 1 } return pos } // Usage example fun main(args: Array<String?>?) { var t = IntArray(10) FenwickTreeExtended[t, 0] = 1 add(t, 9, -2) System.out.println(-1 == sum(t, 0, 9)) t = createFromArray(intArrayOf(1, 2, 3, 4, 5, 6)) for (i in t.indices) System.out.print(FenwickTreeExtended[t, i].toString() + " ") System.out.println() t = createFromArray(intArrayOf(0, 0, 1, 0, 0, 1, 0, 0)) System.out.println(5 == lower_bound(t, 2)) val t1 = IntArray(10) val t2 = IntArray(10) add(t1, t2, 0, 9, 1) add(t1, t2, 0, 0, -2) System.out.println(sum(t1, t2, 9)) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
3,093
codelibrary
The Unlicense
src/main/kotlin/com/nibado/projects/advent/y2020/Day22.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.* object Day22 : Day { private val players = resourceStrings(2020, 22).let { (a, b) -> a.split("\n").drop(1).map { it.toInt() } to b.split("\n").drop(1).map { it.toInt() } } override fun part1(): Int { val (p1, p2) = players.let { (a,b) -> a.toMutableList() to b.toMutableList() } while(p1.isNotEmpty() && p2.isNotEmpty()) { val num1 = p1.removeAt(0) val num2 = p2.removeAt(0) if(num1 > num2) p1.addAll(listOf(num1, num2)) else if(num2 > num1) p2.addAll(listOf(num2, num1)) } return (if(p1.isNotEmpty()) p1 else p2).score() } override fun part2() = combat(players.first, players.second).let { (_, deck) -> deck.score() } private fun combat(one: List<Int>, two: List<Int>) : Pair<Int, Collection<Int>> { val (p1, p2) = (one to two).let { (a,b) -> a.toMutableList() to b.toMutableList() } val p1Decks = mutableSetOf<List<Int>>() val p2Decks = mutableSetOf<List<Int>>() while(p1.isNotEmpty() && p2.isNotEmpty()) { p1Decks += p1.toList() p2Decks += p2.toList() val num1 = p1.removeAt(0) val num2 = p2.removeAt(0) if(p1Decks.contains(p1.toList()) || p2Decks.contains(p2.toList())) { return 1 to emptyList() } val winner = if(num1 <= p1.size && num2 <= p2.size) { combat(p1.toList().take(num1), p2.toList().take(num2)).first } else { when { num1 > num2 -> 1 num2 > num1 -> 2 else -> 0 } } when(winner) { 1 -> p1.addAll(listOf(num1, num2)) 2 -> p2.addAll(listOf(num2, num1)) } } return if(p1.isEmpty()) { 2 to p2.toList() } else { 1 to p1.toList() } } private fun Collection<Int>.score() = reversed().mapIndexed { i, v -> (i + 1) to v } .fold(0) { acc, (a,b) -> acc + a * b} }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
2,184
adventofcode
MIT License
jvm_sandbox/projects/advent_of_code/src/main/kotlin/year2018/Day3.kt
jduan
166,515,850
false
{"Rust": 876461, "Kotlin": 257167, "Java": 139101, "Python": 114308, "Vim Script": 100117, "Shell": 96665, "C": 67784, "Starlark": 23497, "JavaScript": 20939, "HTML": 12920, "Ruby": 5087, "Thrift": 4518, "Nix": 2919, "HCL": 1069, "Lua": 926, "CSS": 826, "Assembly": 761, "Makefile": 591, "Haskell": 585, "Dockerfile": 501, "Scala": 322, "Smalltalk": 270, "CMake": 252, "Smarty": 97, "Clojure": 91}
package year2018.day3 import java.io.File data class Rectangle( val id: Int, val x: Int, val y: Int, val width: Int, val height: Int ) { /** * Return a list of pairs (x, y) that are covered by this rectangle. */ fun coveredCells(): List<Pair<Int, Int>> { val pairs = mutableListOf<Pair<Int, Int>>(); for (i in 0 until width) { for (j in 0 until height) { pairs.add(Pair(x + i, y + j)) } } return pairs } } fun findSquareInches(path: String): Int { val coveredTimes = findAllCoveredSquares(path) var squareInches = 0 for (pair in coveredTimes.keys) { if (coveredTimes[pair]!! > 1) { squareInches++ } } return squareInches } // part 2 fun findSquareId(path: String): Int { val coveredTimes = findAllCoveredSquares(path) val lines = File(path).readLines() for (i in 0 until lines.size) { val rectangle = parseLine(lines[i]) val pairs = rectangle.coveredCells() var flag = true for (pair in pairs) { if (coveredTimes[pair]!! > 1) { flag = false break } } if (flag) { return rectangle.id } } throw Exception("Not found!") } fun findAllCoveredSquares(path: String): Map<Pair<Int, Int>, Int> { val coveredTimes = mutableMapOf<Pair<Int, Int>, Int>() File(path).forEachLine { val rectangle = parseLine(it) val pairs = rectangle.coveredCells() for (pair in pairs) { if (pair in coveredTimes) { coveredTimes[pair] = coveredTimes[pair]!! + 1 } else { coveredTimes[pair] = 1 } } } return coveredTimes } /** * Parse a string like: * #16 @ 859,624: 21x19 * and return a Rectangle object. */ fun parseLine(line: String): Rectangle { val re = """#(\d+)\s+@\s+(\d+),(\d+):\s+(\d+)x(\d+)""".toRegex() val parts = re.find(line)!!.groupValues return Rectangle(parts[1].toInt(), parts[2].toInt(), parts[3].toInt(), parts[4].toInt(), parts[5].toInt()) }
58
Rust
1
0
d5143e89ce25d761eac67e9c357620231cab303e
1,977
cosmos
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day18.kt
clechasseur
568,233,589
false
{"Kotlin": 242914}
package io.github.clechasseur.adventofcode.y2015 import io.github.clechasseur.adventofcode.util.Pt import io.github.clechasseur.adventofcode.y2015.data.Day18Data object Day18 { private val input = Day18Data.input fun part1(): Int = generateSequence(input.toGrid(false)) { it.animate() }.drop(100).first().litCount fun part2(): Int = generateSequence(input.toGrid(true)) { it.animate() }.drop(100).first().litCount private class Grid(val on: Set<Pt>, val stuck: Set<Pt>) { companion object { private val corners = setOf(Pt(0, 0), Pt(0, 99), Pt(99, 0), Pt(99, 99)) } constructor(on: Set<Pt>, faulty: Boolean) : this(on, if (faulty) corners else emptySet()) val litCount: Int get() = (on + stuck).size fun animate(): Grid = Grid((0..99).flatMap { x -> (0..99).map { y -> val pt = Pt(x, y) pt to animate(pt) } }.filter { it.second }.map { it.first }.toSet(), stuck) private fun state(pt: Pt): Boolean = on.contains(pt) || stuck.contains(pt) private fun neighbours(pt: Pt): List<Pt> = (-1..1).flatMap { x -> (-1..1).map { y -> pt + Pt(x, y) } } - pt private fun litNeighbours(pt: Pt): Int = neighbours(pt).count { state(it) } private fun animate(pt: Pt): Boolean = when (state(pt)) { true -> litNeighbours(pt) in 2..3 false -> litNeighbours(pt) == 3 } } private fun String.toGrid(faulty: Boolean): Grid = Grid(lines().flatMapIndexed { y, line -> line.mapIndexed { x, light -> if (light == '#') Pt(x, y) else null } }.filterNotNull().toSet(), faulty) }
0
Kotlin
0
0
e5a83093156cd7cd4afa41c93967a5181fd6ab80
1,736
adventofcode2015
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LetterTilePossibilities.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 /** * 1079. Letter Tile Possibilities * @see <a href="https://leetcode.com/problems/letter-tile-possibilities/">Source</a> */ fun interface LetterTilePossibilities { operator fun invoke(tiles: String): Int } class LetterTilePossibilitiesDFS : LetterTilePossibilities { private var count = 0 override operator fun invoke(tiles: String): Int { val chars = tiles.toCharArray() chars.sort() val visited = BooleanArray(chars.size) dfs(chars, 0, visited) return count } private fun dfs(chars: CharArray, length: Int, visited: BooleanArray) { if (length == chars.size) return for (i in chars.indices) { if (visited[i]) continue if (i - 1 >= 0 && chars[i] == chars[i - 1] && !visited[i - 1]) continue count++ visited[i] = true dfs(chars, length + 1, visited) visited[i] = false } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,585
kotlab
Apache License 2.0
Retos/Reto #3 - EL GENERADOR DE CONTRASEÑAS [Media]/kotlin/masdos.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
fun main() { /* * Escribe un programa que sea capaz de generar contraseñas de forma aleatoria. * Podrás configurar generar contraseñas con los siguientes parámetros: * - Longitud: Entre 8 y 16. * - Con o sin letras mayúsculas. * - Con o sin números. * - Con o sin símbolos. * (Pudiendo combinar todos estos parámetros entre ellos) */ val passwordSize = addPasswordSize(8, 16) val hasUppercase = hasPreference("mayúsculas") val hasNumbers = hasPreference("números") val hasSymbols = hasPreference("símbolos") val password = generatePassword(passwordSize, hasUppercase, hasNumbers, hasSymbols) println(password) } private fun addPasswordSize(minSize: Int, maxSize: Int): Int { var passwordSize = minSize var validSize = false while (!validSize) { println( "¿Cuántos caracteres desea en la contraseña? Siendo $minSize el mínimo y $maxSize el máximo: " ) passwordSize = readln().toInt() if (passwordSize in minSize..maxSize) validSize = true else println( "El parámetro '$passwordSize' no es correcto. Aceptados: $minSize a $maxSize incluidos" ) } return passwordSize } private fun hasPreference(preferenceName: String): Boolean { var preference = false var validPreference = false while (!validPreference) { println("¿Desea tener $preferenceName? (si o no)") when (val response = readln().lowercase()) { "si" -> { preference = true validPreference = true } "no" -> { preference = false validPreference = true } else -> println("El parámetro '$response' no es correcto. Aceptados: si o no") } } return preference } private fun generatePassword( passwordSize: Int, hasUppercase: Boolean, hasNumbers: Boolean, hasSymbols: Boolean ): String { var password = generateLowercasePassword(passwordSize) do { if (hasUppercase) password = addUppercase(password) if (hasNumbers) password = addNumbers(password) if (hasSymbols) password = addSymbols(password) } while (!isValidPassword(password, hasUppercase, hasNumbers, hasSymbols)) return password } fun isValidPassword( password: String, hasUppercase: Boolean, hasNumbers: Boolean, hasSymbols: Boolean ): Boolean { if (!password.any { it in 'a'..'z' }) return false if (hasUppercase && !password.any { it in 'A'..'Z' }) return false if (hasNumbers && !password.any { it in '0'..'9' }) return false if (hasSymbols && !password.any { it in listOf('!', '¡', '?', '¿', '#', '@', '$', '%', '&') }) return false return true } private fun generateLowercasePassword(passwordSize: Int): String { val lowercase = ('a'..'z') var password = "" for (i in 1..passwordSize) password += lowercase.random() return password } private fun addUppercase(password: String): String { val uppercase = ('A'..'Z').toList() return replaceRandomCharacters(password, uppercase) } private fun addNumbers(password: String): String { val numbers = ('0'..'9').toList() return replaceRandomCharacters(password, numbers) } private fun addSymbols(password: String): String { val symbols = listOf('!', '¡', '?', '¿', '#', '@', '$', '%', '&') return replaceRandomCharacters(password, symbols) } private fun replaceRandomCharacters(text: String, newCharacters: List<Char>): String { val lettersToChange = ((Math.random() * (text.length / 2)) + 1).toInt() val lettersChanged = IntArray(lettersToChange) val newText = text.toCharArray() for (i in 0 until lettersToChange) { var positionChange: Int do { positionChange = (Math.random() * text.length).toInt() } while (lettersChanged.any() { it == positionChange }) newText[positionChange] = newCharacters.random() lettersChanged[i] = positionChange } return newText.joinToString("") }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
3,854
retos-programacion-2023
Apache License 2.0
src/main/kotlin/com/github/wakingrufus/aoc/Day3.kt
wakingrufus
159,674,364
false
null
package com.github.wakingrufus.aoc import mu.KLogging class Day3 { companion object : KLogging() fun findContestedArea(claims: List<String>): Int { val claimedPlots: MutableSet<Pair<Int, Int>> = mutableSetOf() val contestedPlots: MutableSet<Pair<Int, Int>> = mutableSetOf() claims.map(::parseClaim) .flatMap(Claim::expand) .forEach { if (!claimedPlots.add(it)) { contestedPlots.add(it) } } return contestedPlots.size } fun part2(claimInput: List<String>) = findNonIntersectingClaim(claimInput) fun findNonIntersectingClaim(claimInput: List<String>): String? { val claimList = claimInput.map { parseClaim(it) } return claimList.find { subject -> claimList.none { subject.id != it.id && subject.intersects(it) } }?.id } } data class Claim(val id: String, val xOffset: Int, val yOffset: Int, val width: Int, val height: Int) fun Claim.expand(): List<Pair<Int, Int>> { return (xOffset until xOffset + width).flatMap { x -> (yOffset until yOffset + height).map { y -> x to y } } } fun Claim.intersects(otherClaim: Claim): Boolean { return this.xOffset < (otherClaim.xOffset + otherClaim.width) && (this.xOffset + this.width) > otherClaim.xOffset && this.yOffset < (otherClaim.yOffset + otherClaim.height) && (this.yOffset + this.height) > otherClaim.yOffset } fun parseClaim(input: String): Claim { val tokens = input .split('#', ':', ',', 'x', ':', '@') .map(String::trim) return Claim(id = tokens[1], xOffset = tokens[2].toInt(), yOffset = tokens[3].toInt(), width = tokens[4].toInt(), height = tokens[5].toInt()) }
0
Kotlin
0
0
bdf846cb0e4d53bd8beda6fdb3e07bfce59d21ea
1,977
advent-of-code-2018
MIT License
src/day04/Day04.kt
PoisonedYouth
571,927,632
false
{"Kotlin": 27144}
package day04 import readInput fun main() { fun splitToRange(input: String): IntRange { val (start, end) = input.split("-") return IntRange( start = start.toInt(), endInclusive = end.toInt() ) } infix fun IntRange.fullyContains(other: IntRange): Boolean { return this.all { other.contains(it) } } infix fun IntRange.overlap(other: IntRange): Boolean { return this.any { other.contains(it) } } fun part1(input: List<String>): Int { return input.count { line -> val (elv1, elv2) = line.split(",") val elv1Range = splitToRange(elv1) val elv2Range = splitToRange(elv2) elv1Range fullyContains elv2Range || elv2Range fullyContains elv1Range } } fun part2(input: List<String>): Int { return input.count { line -> val (elv1, elv2) = line.split(",") val elv1Range = splitToRange(elv1) val elv2Range = splitToRange(elv2) elv1Range overlap elv2Range } } val input = readInput("day04/Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
dbcb627e693339170ba344847b610f32429f93d1
1,178
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/Day5.kt
ivan-gusiev
726,608,707
false
{"Kotlin": 34715, "Python": 2022, "Makefile": 50}
import util.AocDay import util.AocInput import util.AocSequence import kotlin.math.min typealias Day5InputType = List<List<String>>; class Day5 : Runner { // constant that holds the test input val TEST_INPUT: String = """ seeds: 79 14 55 13 seed-to-soil map: 50 98 2 52 50 48 soil-to-fertilizer map: 0 15 37 37 52 2 39 0 15 fertilizer-to-water map: 49 53 8 0 11 42 42 0 7 57 7 4 water-to-light map: 88 18 7 18 25 70 light-to-temperature map: 45 77 23 81 45 19 68 64 13 temperature-to-humidity map: 0 69 1 1 0 69 humidity-to-location map: 60 56 37 56 93 4 """.trimIndent() override fun run() { val day = AocDay("2023".toInt(), "5".toInt()) val lines = AocInput.lines(day) //val lines = TEST_INPUT.split("\n") val blocks = AocSequence.split(lines, "") part1(blocks) part2(blocks) } private fun part1(input: Day5InputType) { val seeds = parseSeedsPart1(input[0].single()) val minLocation = getMinLocation(input, seeds.asSequence()) println("Part 1 Result: $minLocation") } private fun part2(input: Day5InputType) { val seeds = parseSeedsPart2(input[0].single()) val minLocation = getMinLocation(input, seeds) println("Part 2 Result: $minLocation") } data class FoodMapping(val destinationStart: Long, val sourceStart: Long, val length: Long) { companion object { fun parse(input: String): FoodMapping { val parts = input.split(" ") val destinationStart = parts[0].toLong() val sourceStart = parts[1].toLong() val length = parts[2].toLong() return FoodMapping(destinationStart, sourceStart, length) } } override fun toString(): String { return "$sourceStart -> $destinationStart ($length)" } fun map(source: Long): Long { return destinationStart + (source - sourceStart) } } data class FoodMap(val destination: String, val source: String, val mappings: List<FoodMapping>) { companion object { fun parse(input: List<String>): FoodMap { val header = input[0] .replace(" map:", "") .split("-to-") val source = header[0] val destination = header[1] val mappings = input.drop(1).map(FoodMapping::parse) return FoodMap(destination, source, mappings) } } override fun toString(): String { return "$source -> $destination\n" + mappings.joinToString("\n") { " $it" } } fun selectMapping(source: Long): FoodMapping { return mappings.find { it.sourceStart <= source && source < it.sourceStart + it.length } ?: FoodMapping( 0, 0, Long.MAX_VALUE ) } } private fun parseSeedsPart1(input: String): List<Long> { return input .replace("seeds: ", "") .trim() .split(" ") .map(String::toLong) } private fun parseSeedsPart2(input: String): Sequence<Long> = sequence { val seeds = parseSeedsPart1(input) val pairs = seeds.chunked(2) var pairCount = 0 for (pair in pairs) { pairCount++ val start = pair[0] val count = pair[1] println("processing $pairCount/${pairs.count()} [$start, ${start + count}], count=$count") for (i in start..start + count) { yield(i) } } } private fun getMinLocation(input: Day5InputType, seeds: Sequence<Long>): Long { val maps = input.drop(1).map(FoodMap.Companion::parse) val mapMap = maps.associateBy(FoodMap::source) val seedName = "seed" val targetName = "location" var minLocation = Long.MAX_VALUE var progress = 0 for (seed in seeds) { progress++ if (progress % 10_000_000 == 0) { println("${progress / 1_000_000}M seeds processed") } var current = seed var currentName = seedName while (true) { val map = mapMap[currentName]!! val mapping = map.selectMapping(current) current = mapping.map(current) currentName = map.destination if (currentName == targetName) { minLocation = min(minLocation, current) break } } } return minLocation } }
0
Kotlin
0
0
5585816b435b42b4e7c77ce9c8cabc544b2ada18
4,956
advent-of-code-2023
MIT License
src/main/kotlin/cloud/dqn/leetcode/LRUCache.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * Your LRUCache object will be instantiated and called as such: * var obj = LRUCache(capacity) * var param_1 = obj.get(key) * obj.put(key,value) */ /** * https://leetcode.com/problems/lru-cache/discuss/ Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. Follow up: Could you do both operations in O(1) time complexity? Algo0 use hashmap for puts and gets, also to reference nodes in double linked list use doubly linked list for keeping up the freshness */ class LRUCache(capacity: Int) { private class Node { var key: Int var value: Int var newer: Node? var older: Node? constructor(key: Int, value: Int) { this.key = key this.value = value newer = null older = null } override fun equals(other: Any?): Boolean = (other is Node) && (other.key == key) && (other.value == value) override fun hashCode(): Int = "$key:$value".hashCode() fun nullLinks(): Node { newer = null older = null return this } } private class LRUList { private var oldestNode: Node? = null private var newestNode: Node? = null fun makeNewest(node: Node) { remove(node)?.let { insertNew(it) } } fun insertNew(node: Node) { node.nullLinks() if (oldestNode == null && newestNode == null) { oldestNode = node newestNode = node } else { val oNode = newestNode newestNode = node newestNode?.older = oNode oNode?.newer = newestNode } } fun removeOldest(): Node? { return remove(oldestNode) } /** removes the node from the list and corrects the chains */ private fun remove(node: Node?): Node? { if (node != null) { val older = node.older val newer = node.newer newestNode?.let { if (it.equals(node)) { newestNode = node.older } } oldestNode?.let { if (it.equals(node)) { oldestNode = node.newer } } older?.newer = newer newer?.older = older newestNode?.newer = null oldestNode?.older = null } return node?.nullLinks() } } private val keyToNode: HashMap<Int, Node> private val list: LRUList private val capacity: Int // todo handle negative capacity init { keyToNode = HashMap(capacity) list = LRUList() this.capacity = capacity } /** get the value and if found remove it from list and push it to newest @return -1 if not found, value otherwise */ fun get(key: Int): Int { val node = keyToNode[key] if (node == null) { return -1 } else { list.makeNewest(node) return node.value } } // if capacity reached evict from oldestNode unless it is already in hash fun put(key: Int, value: Int) { val existingNode = keyToNode[key] if (existingNode != null) { existingNode.value = value list.makeNewest(existingNode) } else { val newNode = Node(key, value) if (keyToNode.size >= capacity) { list.removeOldest()?.let { oldestNode -> keyToNode.remove(oldestNode.key) } } list.insertNew(newNode) keyToNode[newNode.key] = newNode } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
4,329
cloud-dqn-leetcode
No Limit Public License
src/Day10.kt
rifkinni
573,123,064
false
{"Kotlin": 33155, "Shell": 125}
class Cycle { private var cycle = 1 private var x = 1 private val signalStrengths: MutableList<Int> = ArrayList() val art: StringBuilder = java.lang.StringBuilder() fun run(line: String) { if (line == "noop") { noop() } else if (line.startsWith("addx")) { val value = Integer.parseInt(line.split(" ")[1]) noop(); noop() x += value } } private fun makeArt() { val spritePosition = (cycle - 1) % 40 val symbol = if ((x - 1 .. x + 1).contains(spritePosition)) '#' else '.' art.append(symbol) if (cycle % 40 == 0) { art.append("\n") } } private fun noop() { signalStrengths.add(cycle * x) makeArt() cycle++ } fun getResult(): Int { var sum = 0; var i = 20 while (i < signalStrengths.size) { sum += signalStrengths[i - 1] i += 40 } return sum } } fun main() { fun solve(input: List<String>): Int { val cycle = Cycle() for (line in input) { cycle.run(line) } println(cycle.art.toString()) println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n") return cycle.getResult() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(solve(testInput) == 13140) val input = readInput("Day10") println(solve(input)) }
0
Kotlin
0
0
c2f8ca8447c9663c0ce3efbec8e57070d90a8996
1,509
2022-advent
Apache License 2.0
src/main/kotlin/days/Day22.kt
andilau
433,504,283
false
{"Kotlin": 137815}
package days import kotlin.math.max import kotlin.math.min @AdventOfCodePuzzle( name = "Reactor Reboot", url = "https://adventofcode.com/2021/day/22", date = Date(day = 22, year = 2021) ) class Day22(private val instructions: List<String>) : Puzzle { override fun partOne() = instructions .filter { it.isNotEmpty() } .map { Instruction.parse(it) } .filter { it.volume.inRange(-50..50) } .fold(mutableMapOf(), ::intersectVolumeAndMerge) .entries.sumOf { (volume, times) -> volume.size() * times } override fun partTwo() = instructions .filter { it.isNotEmpty() } .map { Instruction.parse(it) } .fold(mutableMapOf(), ::intersectVolumeAndMerge) .entries.sumOf { (volume, times) -> volume.size() * times } private fun intersectVolumeAndMerge( volumes: MutableMap<Volume, Int>, instruction: Instruction ): MutableMap<Volume, Int> { val volume = instruction.volume volumes .mapNotNull { (otherVolume, times) -> (volume intersect otherVolume)?.let { it to -times } } .groupingBy { it.first }.fold(0) { acc, e -> acc + e.second } .forEach { (volume, times) -> volumes[volume] = volumes.getOrDefault(volume, 0) + times } if (instruction.add) volumes[volume] = volumes.getOrDefault(volume, 0) + 1 return volumes } data class Volume(val xRange: IntRange, val yRange: IntRange, val zRange: IntRange) { private val ranges = listOf(xRange, yRange, zRange).toTypedArray() private fun min(index: Int) = ranges[index].first private fun max(index: Int) = ranges[index].last fun size(): Long = 1L * xRange.length * yRange.length * zRange.length fun inRange(other: IntRange) = ranges.all { it.first in other && it.last in other } infix fun intersect(other: Volume): Volume? { val result = IntArray(6) for (i in 0 until 3) { val min = max(min(i), other.min(i)) val max = min(max(i), other.max(i)) if (max >= min) { // intersects result[2 * i] = min result[2 * i + 1] = max } else return null } return Volume( result[0]..result[1], result[2]..result[3], result[4]..result[5], ) } private val IntRange.length get() = last - first + 1 } data class Instruction(val add: Boolean, val volume: Volume) { companion object { private val INSTRUCTION = Regex("""(on|off) x=(-?\d+)..(-?\d+),y=(-?\d+)..(-?\d+),z=(-?\d+)..(-?\d+)""") fun parse(line: String) = INSTRUCTION.matchEntire(line)?.destructured?.let { (what, x1, x2, y1, y2, z1, z2) -> Instruction( add = what == "on", volume = Volume( x1.toInt()..x2.toInt(), y1.toInt()..y2.toInt(), z1.toInt()..z2.toInt() ) ) } ?: error("Unable to parse: $line") } } }
0
Kotlin
0
0
b3f06a73e7d9d207ee3051879b83e92b049a0304
3,343
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/g2601_2700/s2608_shortest_cycle_in_a_graph/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2608_shortest_cycle_in_a_graph // #Hard #Breadth_First_Search #Graph #2023_07_14_Time_1061_ms_(100.00%)_Space_54.9_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { private var min = Int.MAX_VALUE fun findShortestCycle(n: Int, edges: Array<IntArray>): Int { val adj: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until n) adj.add(ArrayList()) for (edge in edges) { adj[edge[0]].add(edge[1]) adj[edge[1]].add(edge[0]) } for (i in 0 until n) { dfs(adj, HashSet<Int?>(), i) } return if (min == Int.MAX_VALUE) -1 else min } private fun dfs(adj: List<MutableList<Int>>, set: HashSet<Int?>, node: Int) { val queue: Queue<IntArray> = LinkedList() set.add(node) queue.add(intArrayOf(node, node)) val distance = IntArray(adj.size) distance.fill(-1) distance[node] = 0 while (queue.isNotEmpty()) { val arr: IntArray = queue.poll() val topNode = arr[0] val from = arr[1] for (i in adj[topNode]) { if (i == from) continue if (set.contains(i)) { min = min.coerceAtMost(distance[topNode] + distance[i] + 1) continue } set.add(i) distance[i] = distance[topNode] + 1 queue.add(intArrayOf(i, topNode)) } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,530
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ExtraCharactersInString.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 kotlin.math.min /** * 2707. Extra Characters in a String * @see <a href="https://leetcode.com/problems/extra-characters-in-a-string">Source</a> */ fun interface ExtraCharactersInString { operator fun invoke(s: String, dictionary: Array<String>): Int } /** * Approach 1: Top Down Dynamic Programming with Substring Method */ class ExtraCharactersInStringTopDown : ExtraCharactersInString { private lateinit var memo: Array<Int> private lateinit var dictionarySet: HashSet<String> override fun invoke(s: String, dictionary: Array<String>): Int { val n = s.length memo = Array(n) { 0 } dictionarySet = HashSet(dictionary.toList()) return dp(0, n, s) } private fun dp(start: Int, n: Int, s: String): Int { if (start == n) { return 0 } // To count this character as a leftover character // move to index 'start + 1' var ans = dp(start + 1, n, s) + 1 for (end in start until n) { val curr = s.substring(start, end + 1) if (dictionarySet.contains(curr)) { ans = min(ans.toDouble(), dp(end + 1, n, s).toDouble()).toInt() } } return ans.also { memo[start] = it } } } /** * Approach 2: Bottom Up Dynamic Programming with Substring Method */ class ExtraCharactersInStringBottomUp : ExtraCharactersInString { override fun invoke(s: String, dictionary: Array<String>): Int { val n = s.length val dictionarySet = HashSet(dictionary.toList()) val dp = IntArray(n + 1) for (start in n - 1 downTo 0) { dp[start] = dp[start + 1] + 1 for (end in start until n) { val curr = s.substring(start, end + 1) if (dictionarySet.contains(curr)) { dp[start] = dp[start].coerceAtMost(dp[end + 1]) } } } return dp[0] } } /** * Approach 3: Top Down Dynamic Programming with Trie */ class ExtraCharactersInStringTopDownTrie : ExtraCharactersInString { private var root: TrieNode? = null private lateinit var memo: Array<Int> override fun invoke(s: String, dictionary: Array<String>): Int { val n: Int = s.length root = dictionary.buildTrie() memo = Array(n + 1) { 0 } return dp(0, n, s) } private fun dp(start: Int, n: Int, s: String): Int { if (start == n) { return 0 } var node = root // To count this character as a leftover character // move to index 'start + 1' var ans = dp(start + 1, n, s) + 1 for (end in start until n) { val c = s[end] if (node?.children?.containsKey(c) == false) { break } node = node?.children?.get(c) if (node?.isWord == true) { ans = min(ans.toDouble(), dp(end + 1, n, s).toDouble()).toInt() } } return ans.also { memo[start] = it } } } /** * Approach 4: Bottom Up Dynamic Programming with Trie */ class ExtraCharactersInStringBottomUpTrie : ExtraCharactersInString { override fun invoke(s: String, dictionary: Array<String>): Int { val n: Int = s.length val root: TrieNode = dictionary.buildTrie() val dp = IntArray(n + 1) for (start in n - 1 downTo 0) { dp[start] = dp[start + 1] + 1 var node: TrieNode? = root for (end in start until n) { if (node?.children?.containsKey(s[end]) == false) { break } node = node?.children?.get(s[end]) if (node?.isWord == true) { dp[start] = min(dp[start].toDouble(), dp[end + 1].toDouble()).toInt() } } } return dp[0] } } private fun Array<String>.buildTrie(): TrieNode { val root = TrieNode() for (word in this) { var node: TrieNode? = root for (c in word.toCharArray()) { node?.children?.putIfAbsent(c, TrieNode()) node = node?.children?.get(c) } node?.isWord = true } return root } private data class TrieNode( val children: MutableMap<Char?, TrieNode?> = HashMap(), var isWord: Boolean = false, )
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,005
kotlab
Apache License 2.0
src/main/kotlin/day22/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day22 import day22.Direction.* import day22.Grid.TileType.* import util.readTestInput import java.lang.IllegalArgumentException private enum class Direction(val dx: Int, val dy: Int, val symbol: Char, val facingPoints: Int) { UP( 0, -1, '^', 3) { override fun turnLeft() = LEFT override fun turnRight() = RIGHT }, RIGHT( 1, 0, '>', 0) { override fun turnLeft() = UP override fun turnRight() = DOWN }, DOWN( 0, 1, 'v', 1) { override fun turnLeft() = RIGHT override fun turnRight() = LEFT }, LEFT( -1, 0, '<', 2) { override fun turnLeft() = DOWN override fun turnRight() = UP }; abstract fun turnLeft(): Direction abstract fun turnRight(): Direction fun turnOpposite() = turnLeft().turnLeft() } private data class Coord(val x: Int, val y: Int) { fun move(direction: Direction, amount: Int = 1) = Coord(x + amount * direction.dx, y + amount * direction.dy) fun moveUntil(direction: Direction, predicate: (Coord) -> Boolean): Coord { val maxMoves = 1000 var newCoord = this for (n in 0 until maxMoves) { val potentialNewCoord = newCoord.move(direction) if (predicate(potentialNewCoord)) { return newCoord } newCoord = potentialNewCoord } throw IllegalArgumentException("too many moves") } } private interface Instruction private data class Move(val amount: Int): Instruction private object TurnLeft: Instruction private object TurnRight: Instruction private data class Player(val coord: Coord, val direction: Direction) private data class Grid(val inputLines: List<String>) { private enum class TileType(val symbol: String) { BLANK(" "), FLOOR("."), WALL("#"); companion object { fun of(symbol: String) = values().first { it.symbol == symbol } } } private data class Tile(val tileType: TileType, val coord: Coord) { override fun toString() = tileType.symbol } private val tiles: List<List<Tile>> = inputLines.mapIndexed { y , line -> line.mapIndexed { x, symbol -> Tile(TileType.of(symbol.toString()), Coord(x, y))} } private val maxX = tiles.fold(0) { acc, tiles -> acc + tiles.maxBy {it.coord.x}.coord.x } private val maxY = tiles.size - 1 fun isOutOfGrid(coord: Coord) = coord.x < 0 || coord.y < 0 || coord.x > maxX || coord.y > maxY private fun tileAt(coord: Coord): Tile = when { isOutOfGrid(coord) -> Tile(BLANK, coord) coord.x >= tiles[coord.y].size -> Tile(BLANK, coord) else -> tiles[coord.y][coord.x] } fun isBlocked(coord: Coord): Boolean = tileAt(coord).tileType != FLOOR fun jumpsToCoord(coord: Coord, direction: Direction): Coord? { if (tileAt(coord).tileType != BLANK) { return null } val oppositeDirection = direction.turnOpposite() val jumpCoord = coord.moveUntil(oppositeDirection) { isOutOfGrid(it) || tileAt(it).tileType == BLANK } return if (tileAt(jumpCoord).tileType == WALL) null else jumpCoord } fun leftMostFloorCoord(): Coord = tiles[0] .filter { it.tileType == FLOOR } .minBy { tile -> tile.coord.x }.coord fun draw(customDraw: (Coord) -> Char? = {_:Coord -> null}) { val height = tiles.size val width = maxX for (y in 0 until height) { for (x in 0 until width) { val coord = Coord(x, y) val customChar = customDraw(coord) if (customChar != null) print(customChar) else print(tileAt(coord)) } println() } } } private fun parseInstructions(str: String): List<Instruction> { val parts = """\d+|[LR]""".toRegex().findAll(str).map {it.value} return parts.map { part -> when (part) { "L" -> TurnLeft "R" -> TurnRight else -> Move(part.toInt()) } }.toList() } private data class GameState(val grid: Grid, val instructions: List<Instruction>) { var player = Player(grid.leftMostFloorCoord(), RIGHT) // Keep the player states in memory, so that we can visualize the path val playerStates = mutableListOf(player) private fun updatePlayerState(newPlayer: Player) { player = newPlayer playerStates.add(player) } fun movePlayer(instruction: Instruction) { when (instruction) { is Move -> { repeat(instruction.amount) { val newCoord = player.coord.move(player.direction) val jumpsToCoord = grid.jumpsToCoord(newCoord, player.direction) if (jumpsToCoord != null) { updatePlayerState(player.copy(coord = jumpsToCoord)) } else if (!grid.isBlocked(newCoord)) { updatePlayerState(player.copy(coord = newCoord)) } } } is TurnLeft -> updatePlayerState(player.copy(direction = player.direction.turnLeft())) is TurnRight -> updatePlayerState(player.copy(direction = player.direction.turnRight())) } } fun calculatePassword() = 1000 * (player.coord.y + 1) + 4 * (player.coord.x + 1) + player.direction.facingPoints fun draw() { grid.draw { coord -> playerStates.findLast { it.coord == coord }?.direction?.symbol } } } fun part1(inputLines: List<String>): Int { val gridLines = inputLines.takeWhile{ it.isNotBlank() } val instructionLine = inputLines.takeLastWhile { it.isNotBlank() }.first() val instructions = parseInstructions(instructionLine) val grid = Grid(gridLines) val gameState = GameState(grid, instructions) instructions.forEach { gameState.movePlayer(it) } gameState.draw() return gameState.calculatePassword() } fun main() { val inputLines = readTestInput("day22") println(part1(inputLines)) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
6,118
advent-of-code-2022
MIT License
src/Day01.kt
befrvnk
574,229,637
false
{"Kotlin": 15788}
fun List<String>.elves(): List<Int> { val elf = mutableListOf<Int>() val elves = mutableListOf<List<Int>>() forEach { line -> if (line == "") { elves.add(elf.toList()) elf.clear() } else { elf.add(line.toInt()) } } elves.add(elf.toList()) return elves.map { it.sum() } } fun main() { fun part1(input: List<String>): Int { return input.elves().max() } fun part2(input: List<String>): Int { return input.elves().sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
68e5dd5656c052d8c8a2ea9e03c62f4cd2438dd7
845
aoc-2022-kotlin
Apache License 2.0
src/day10/Day10.kt
Puju2496
576,611,911
false
{"Kotlin": 46156}
package day10 import println import readInput import java.util.* import kotlin.math.abs import kotlin.collections.MutableList fun main() { // test if implementation meets criteria from the description, like: val input = readInput("src/day10", "Day10") println("Part1") part1(input) println("Part2") part2(input) } private fun part1(inputs: List<String>) { var result = 0 var sum = 1 var i = 0 var k = 20 inputs.forEach { val value = it.split(" ") when (value[0]) { "addx" -> { for (j in 0..1) { i++ if (k == i) { result += k * sum k += 40 } if (j == 1) sum += value[1].toInt() } } "noop" -> { i++ if (k == i) { result += k * sum k += 40 } } } } println("result - $result") } private fun part2(inputs: List<String>) { val result = StringBuilder("") val sprite: MutableList<Char> = Array(40) { '.' }.also { it[0] = '#' it[1] = '#' it[2] = '#' }.toMutableList() var sum = 1 var i = 0 var type: Char inputs.forEach { val value = it.split(" ") when (value[0]) { "addx" -> { for (j in 0..1) { ++i type = if (i % 40 > 0) sprite[(i % 40) - 1] else sprite[0] result.append(type) println("sprite - i- $i - $it - $sum - $type") if (j == 1) { sum += value[1].toInt() sprite.replaceAll { '.' } sprite[(abs(sum) - 1) % 40] = '#' sprite[abs(sum) % 40] = '#' sprite[(abs(sum) + 1) % 40] = '#' println("sprite -1 - $sprite") } } } "noop" -> { ++i type = if (i % 40 > 0) sprite[(i % 40) - 1] else sprite[0] result.append(type) } } } for (k in 0 until result.length) { print("${result[k]} ") if ((k+1) % 40 == 0) println() } }
0
Kotlin
0
0
e04f89c67f6170441651a1fe2bd1f2448a2cf64e
2,481
advent-of-code-2022
Apache License 2.0
src/main/kotlin/it/prima/pairProgramming/ui/exercise/FrizzBuzz.kt
tonyno92
565,214,953
false
{"Kotlin": 27416}
package it.prima.pairProgramming.ui.exercise import it.prima.pairProgramming.ext.digit class FrizzBuzz { /** * WHAT IS FIZZBUZZ? * * FizzBuzz is a common coding task given during interviews that tasks candidates to write * a solution that prints integers one-to-N, labeling any integers divisible * by three as “Fizz,” integers divisible by five as “Buzz” and integers divisible by both * three and five as “FizzBuzz.” * Understanding how to solve it can help reinforce good coding practices. * */ private var start = 1 private var end = 10 private val range: IntRange by lazy { start..end } init { println("FrizzBuzz") print("Read Start # : ") start = readln().toIntOrNull() ?: start print("Read End # : ") end = readln().toIntOrNull() ?: end if (start > end) throw Exception("End must be smaller than Start") println("Range = $range") } fun basicSolution() { println("Basic solution (not recommended)") range.forEach { num -> println("$num = " + when { isMultipleOf3(num) && isMultipleOf5(num) -> "FrizzBuzz" isMultipleOf3(num) -> "Frizz" isMultipleOf5(num) -> "Buzz" else -> num }) } } /** * Tip : Using string concat instead of multiple time check * */ fun betterSolution() { println("Better solution") val output = Array(range.last + 1) { "" } range.forEach { num -> if (isMultipleOf3(num)) output[num] += "Frizz" if (isMultipleOf5(num)) output[num] += "Buzz" if (output[num].isEmpty()) output[num] = "$num" println("$num = ${output[num]}") } } /** * Tip : if a number is divisible for 15 then is multiple of 3 and 5 at same time * */ fun seniorSolution() { println("Senior solution") range.forEach { num -> println("$num = " + when { num % 15 == 0 -> "FrizzBuzz" (isMultipleOf3(num)) -> "Frizz" (isMultipleOf5(num)) -> "Buzz" else -> num } ) } } private fun isMultipleOf3(num: Int): Boolean { var x = num var sum = 0 while (x > 0) { //sum += x % 10 sum += x.digit() x /= 10 } return sum % 3 == 0 } private fun isMultipleOf5(num: Int): Boolean { return num % 5 == 0 } }
0
Kotlin
0
0
b036cb800c5256e0276f457f4d022907d79affb2
2,728
KotlinAlgorithmsAndAdt
Apache License 2.0
src/main/kotlin/com/sk/set1/135. Candy.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set1 class Solution135 { fun candy(ratings: IntArray): Int { val candies = IntArray(ratings.size) { 1 } for (i in 1..ratings.lastIndex) { if (ratings[i] > ratings[i - 1]) { candies[i] = candies[i - 1] + 1 } } println(candies.toList()) for (i in ratings.lastIndex - 1 downTo 0) { if (ratings[i] > ratings[i + 1]) { candies[i] = maxOf(candies[i], candies[i + 1] + 1) } } println(candies.toList()) return candies.sum() } fun candy2(ratings: IntArray): Int { val candies = IntArray(ratings.size) { 1 } // Give 1 candy to each child, condition-1 var l = 1 var r = ratings.lastIndex - 1 while (l <= ratings.lastIndex) { if (ratings[l] > ratings[l - 1]) { candies[l] = maxOf(candies[l], candies[l - 1] + 1) // Give 1 extra candy compared to left child } if (ratings[r] > ratings[r + 1]) { candies[r] = maxOf(candies[r], candies[r + 1] + 1) // Give 1 extra candy compared to right child } l++ r-- } return candies.sum() } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,244
leetcode-kotlin
Apache License 2.0
src/main/kotlin/day12/part2/main.kt
TheMrMilchmann
225,375,010
false
null
/* * Copyright (c) 2019 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package day12.part2 import utils.* import kotlin.math.* fun main() { val input = readInputText("/day12/input.txt") val positions = input.lineSequence().map { line -> line.removePrefix("<") .removeSuffix(">") .replace(" ", "") .split(',') .let { kvPairs -> kvPairs.map { kvPair -> kvPair.split("=")[1].toInt() } }.let { coords -> Vec(coords[0], coords[1], coords[2]) } } println(run(positions.toList())) } private fun run(positions: List<Vec>): Long { data class Moon(var pos: Vec, var velocity: Vec) val moons = positions.map { Moon(it, Vec(0, 0, 0)) } fun revisitCoordAlongAxis(selector: (Vec) -> Int): Int { val visited = hashMapOf<List<Pair<Int, Int>>, Int>() var coordsAlongAxis: List<Pair<Int, Int>> var step = 0 do { coordsAlongAxis = moons.map { selector(it.pos) to selector(it.velocity) } visited[coordsAlongAxis]?.let { firstVisited -> return step - firstVisited } visited[coordsAlongAxis] = step moons.flatMap { a -> moons.map { b -> a to b } } .filter { it.first !== it.second } .forEach { (a, b) -> a.velocity += Vec( x = (b.pos.x - a.pos.x).sign, y = (b.pos.y - a.pos.y).sign, z = (b.pos.z - a.pos.z).sign ) } moons.forEach { moon -> moon.pos += moon.velocity } step++ } while (true) } val xCycle = revisitCoordAlongAxis(Vec::x) val yCycle = revisitCoordAlongAxis(Vec::y) val zCycle = revisitCoordAlongAxis(Vec::z) fun gcd(a: Long, b: Long): Long { var r = abs(b) var oldR = abs(a) while (r != 0L) { val quotient = oldR / r val tmpR = r r = oldR - quotient * r oldR = tmpR } return oldR } fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b fun lcm(a: Int, b: Int) = lcm(a.toLong(), b.toLong()) fun lcm(a: Int, b: Long) = lcm(a.toLong(), b) return lcm(xCycle, lcm(yCycle, zCycle)) } data class Vec(val x: Int, val y: Int, val z: Int) operator fun Vec.plus(other: Vec) = Vec(x + other.x, y + other.y, z + other.z)
0
Kotlin
0
1
9d6e2adbb25a057bffc993dfaedabefcdd52e168
3,474
AdventOfCode2019
MIT License
src/Day06.kt
BrianEstrada
572,700,177
false
{"Kotlin": 22757}
fun main() { // Test Case val testInput = readInput("Day06_test") println("Part 1 Test") Day06.part1(testInput) println("Part 2 Test") Day06.part2(testInput) // Actual Case val input = readInput("Day06") println("Part 1") Day06.part1(input) println("Part 2") Day06.part2(input) } private object Day06 { fun part1(lines: List<String>): Int { lines.forEachIndexed { index, line -> val answer = line.toCharArray().findAnswer(4) println("$index = $answer") } return 0 } fun part2(lines: List<String>): Int { lines.forEachIndexed { index, line -> val answer = line.toCharArray().findAnswer(14) println("$index = $answer") } return 0 } private fun CharArray.findAnswer(size: Int): Int { val chars = arrayOfNulls<Char>(size) forEachIndexed { index: Int, char: Char -> chars[index % size] = char if (index > (size - 1) && !chars.hasDuplicates(size)) { return index + 1 } } return 0 } fun Array<Char?>.hasDuplicates(size: Int): Boolean { return this.distinct().count() != size } }
1
Kotlin
0
1
032a4693aff514c9b30e979e63560dc48917411d
1,250
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2017/Day25.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2017 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.ints fun main() = Day25.run() data class Rule(val value: Int, val move: String, val nextState: String) object Day25 : Day(2017, 25) { override fun part1(): Int { val parts = input.split("\n\n") var state = lastWord(parts[0].lines()[0]) val steps = ints(parts[0].lines()[1])[0] val stateMachine = buildStateMachine(parts) var pos = 0 val tape = mutableMapOf<Int, Int>().withDefault { 0 } for (i in 0 until steps) { val currVal = tape.getValue(pos) val rule = stateMachine["${state}_${currVal}"] ?: error("Could not find ${state}_${currVal} in state machine.") tape[pos] = rule.value pos += if (rule.move == "right") 1 else -1 state = rule.nextState } return tape.values.sum() } private fun buildStateMachine(parts: List<String>): Map<String, Rule> { val stateMachine = mutableMapOf<String, Rule>() for (i in 1 until parts.size) { val lines = parts[i].lines() val state = lastWord(lines[0]) stateMachine["${state}_0"] = Rule(ints(lines[2])[0], lastWord(lines[3]), lastWord(lines[4])) stateMachine["${state}_1"] = Rule(ints(lines[6])[0], lastWord(lines[7]), lastWord(lines[8])) } return stateMachine; } private fun lastWord(line: String) = line.split(" ").last().replace(".", "").replace(":", "") override fun part2(): Any { return "" } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,602
adventofkotlin
MIT License
y2018/src/main/kotlin/adventofcode/y2018/Day09.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution import java.util.* object Day09 : AdventSolution(2018, 9, "<NAME>") { override fun solvePartOne(input: String) = parse(input).let { (p, m) -> game(p, m) } override fun solvePartTwo(input: String) = parse(input).let { (p, m) -> game(p, m * 100) } //The magic trick: use a deque, also rotate the circle, not a cursor private fun game(players: Int, highestMarble: Int): Long? { val scores = LongArray(players) val circle = ArrayDeque<Int>(highestMarble) circle += 0 for (nextMarble in 1..highestMarble) { if (nextMarble % 23 == 0) { repeat(7) { circle.offerFirst(circle.pollLast()) } scores[nextMarble % scores.size] += nextMarble.toLong() + circle.pollLast().toLong() circle.offerLast(circle.pollFirst()) } else { circle.offerLast(circle.pollFirst()) circle.offerLast(nextMarble) } } return scores.maxOrNull() } private fun parse(input: String): Pair<Int, Int> { val r = "(\\d+) players; last marble is worth (\\d+) points".toRegex() val (players, lastMarble) = r.matchEntire(input)!!.destructured return players.toInt() to lastMarble.toInt() } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,340
advent-of-code
MIT License
kotlin/src/com/s13g/aoc/aoc2021/Day18.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver import kotlin.math.max /** * --- Day 18: Snailfish --- * https://adventofcode.com/2021/day/18 */ class Day18 : Solver { override fun solve(lines: List<String>): Result { val input = lines.map { parseNum(it) } var result = input[0] for (i in 1 until input.size) { result = add(result, input[i]) } var largestSum = Long.MIN_VALUE for (a in 0 until lines.size - 1) { for (b in a + 1 until lines.size) { largestSum = max(largestSum, add(parseNum(lines[a]), parseNum(lines[b])).magnitude()) largestSum = max(largestSum, add(parseNum(lines[b]), parseNum(lines[a])).magnitude()) } } val partA = result.magnitude() val partB = largestSum return Result("$partA", "$partB") } private fun add(x: SfNum, y: SfNum): SfNum { val result = SfPair(x, y) x.parent = result y.parent = result while (result.reduce()) { // Nothing to do here... } return result } private fun parseNum(line: String): SfNum { // Single number, must be a literal. if (line[0] != '[') return SfRegular(line[0].toString().toLong()) // Find the comma-separated left and right substring: val strA = extractComponent(line.substring(1)) val a = parseNum(strA) assert(line[strA.length + 1] == ',') val strB = extractComponent(line.substring(strA.length + 2)) val b = parseNum(strB) val result = SfPair(a, b) a.parent = result b.parent = result return result } private fun extractComponent(str: String): String { var idx = 0 var openGroupsCount = 0 var subStr = "" do { subStr += str[idx] if (str[idx] == '[') openGroupsCount++ if (str[idx] == ']') openGroupsCount-- idx++ } while (openGroupsCount > 0) return subStr } private interface SfNum { var parent: SfPair? fun reduce(): Boolean fun explode(): Boolean fun split(): Boolean fun nestLevel(): Int { var level = 0 var p = parent while (p != null) { p = p.parent level++ } return level } fun rightMostLeaf(): SfNum fun leftMostLeaf(): SfNum fun firstLeftUp(): SfNum? fun firstRightUp(): SfNum? fun magnitude(): Long } private class SfRegular(var num: Long) : SfNum { override var parent: SfPair? = null override fun reduce() = false override fun explode() = false override fun split() = false override fun rightMostLeaf() = this override fun leftMostLeaf() = this override fun firstLeftUp(): SfNum? { error("Should never be called") } override fun firstRightUp(): SfNum? { error("Should never be called") } override fun magnitude() = num override fun toString() = "$num" } private class SfPair(var a: SfNum, var b: SfNum) : SfNum { override var parent: SfPair? = null override fun reduce(): Boolean { if (explode()) return true return split() } override fun explode(): Boolean { if (nestLevel() == 4) { // Explodes assert(a is SfRegular) assert(b is SfRegular) if (parent!!.a == this) { // We're the left node val findLeft = parent!!.firstLeftUp() if (findLeft != null) { val rightMost = findLeft.rightMostLeaf() (rightMost as SfRegular).num += (a as SfRegular).num } val leftMost = parent!!.b.leftMostLeaf() (leftMost as SfRegular).num += (b as SfRegular).num parent!!.a = SfRegular(0) } else if (parent!!.b == this) { // We're the right node val findRight = parent!!.firstRightUp() if (findRight != null) { val leftMost = findRight.leftMostLeaf() (leftMost as SfRegular).num += (b as SfRegular).num } val rightMost = parent!!.a.rightMostLeaf() (rightMost as SfRegular).num += (a as SfRegular).num parent!!.b = SfRegular(0) } return true } if (a.explode()) return true if (b.explode()) return true return false } override fun split(): Boolean { if (a is SfRegular && (a as SfRegular).num > 9) { val aa = SfRegular((a as SfRegular).num / 2) // rounds down val bb = SfRegular((a as SfRegular).num - aa.num) a = SfPair(aa, bb) aa.parent = a as SfPair bb.parent = a as SfPair a.parent = this return true } if (a.split()) return true if (b is SfRegular && (b as SfRegular).num > 9) { val aa = SfRegular((b as SfRegular).num / 2) // rounds down val bb = SfRegular((b as SfRegular).num - aa.num) b = SfPair(aa, bb) aa.parent = b as SfPair bb.parent = b as SfPair b.parent = this return true } if (b.split()) return true return false } override fun firstLeftUp(): SfNum? { if (parent == null) return null if (parent!!.a != this) return parent!!.a return parent!!.firstLeftUp() } override fun firstRightUp(): SfNum? { if (parent == null) return null if (parent!!.b != this) return parent!!.b return parent!!.firstRightUp() } override fun magnitude() = a.magnitude() * 3 + b.magnitude() * 2 override fun rightMostLeaf() = b.rightMostLeaf() override fun leftMostLeaf() = a.leftMostLeaf() override fun toString() = "[$a,$b]" } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
5,519
euler
Apache License 2.0
source/math/src/main/kotlin/de/webis/webisstud/thesis/reimer/math/PostCorrelationUtil.kt
webis-de
261,803,727
false
{"Kotlin": 235840, "Jupyter Notebook": 43040, "Java": 7525}
package de.webis.webisstud.thesis.reimer.math import org.apache.commons.math3.stat.correlation.KendallsCorrelation import org.apache.commons.math3.util.Precision.equals private val kendalls = KendallsCorrelation() internal fun <T : Comparable<T>> List<T>.intersectionKendallTauCorrelation(other: List<T>): Double { return calculateCorrelation(this, other) { xArray, yArray -> kendalls.correlation(xArray, yArray) } } private fun <T : Comparable<T>> calculateCorrelation(firstRanking: List<T>, secondRanking: List<T>, correlation: (DoubleArray, DoubleArray) -> Double): Double { val firstRankingArray = buildCorrelationArray(firstRanking, secondRanking) val secondRankingArray = buildCorrelationArray(secondRanking, firstRanking) return when { firstRankingArray.isEmpty() -> 0.0 firstRankingArray.size == 1 -> { when { equals(firstRankingArray[0], secondRankingArray[0]) -> 1.0 else -> 0.0 } } else -> correlation(firstRankingArray, secondRankingArray) } } private fun <T : Comparable<T>> buildCorrelationArray(firstRanking: List<T>, secondRanking: List<T>): DoubleArray { val firstRankingIds = firstRanking .checkHasNoDuplicates() .toMutableList() .apply { retainAll(secondRanking.checkHasNoDuplicates()) } val indexValues = firstRankingIds.toList() return indexValues .sorted() .map { firstRankingIds.indexOf(it) } .map(Int::toDouble) .toDoubleArray() } private fun <T> List<T>.checkHasNoDuplicates(): List<T> { check(distinct().size == size) { "The list contains duplicates." } return this }
0
Kotlin
2
2
0935389fc7b1d377b203ed7fc4d2a019dcf9d65e
1,740
sigir20-sampling-bias-due-to-near-duplicates-in-learning-to-rank
MIT License
src/main/kotlin/day7/FileSystem.kt
errob37
573,508,650
false
{"Kotlin": 18301}
package day7 class FileSystem(private val totalSize: Long?) { private val root: Directory = Directory("/") fun getRootDirectory() = root override fun toString() = "FileSystem(root=$root)" fun sumOfSizeForDirectoriesBelow(size: Long): Long { return getSubdirectoriesRecursive(root) .map { it.size() } .filter { it <= size } .sum() } private fun getSubdirectoriesRecursive(currentDirectory: Directory): List<Directory> { return currentDirectory.getSubDirectories().map { getSubdirectoriesRecursive(it) + it }.flatten() } fun ensureFreeSpaceOf(atLeast: Long): Long { val toFree = atLeast - (totalSize!! - root.size()) return getSubdirectoriesRecursive(root) .map { it.size() } .filter { it >= toFree } .min() } } interface FileSystemItem { fun name(): String fun size(): Long fun addItem(item: FileSystemItem) fun isDirectory(): Boolean = false } class Directory(private val name: String) : FileSystemItem { private val items: MutableList<FileSystemItem> = mutableListOf() var parent: Directory? = null fun getDirectory(directoryName: String): Directory = items.find { it.name() == directoryName && it is Directory } as Directory override fun name() = name override fun size() = items.map(FileSystemItem::size).sum() override fun addItem(item: FileSystemItem) { if (item is Directory) item.parent = this items.add(item) } override fun isDirectory(): Boolean = true override fun toString() = "Directory(name='$name', items=$items)" fun getSubDirectories() = this.items.filter { it.isDirectory() }.map { it as Directory } } class File(private val name: String, private val size: Long) : FileSystemItem { override fun name() = name override fun size() = size override fun addItem(item: FileSystemItem) {} override fun toString() = "File(name='$name', size=$size)" }
0
Kotlin
0
0
7e84babb58eabbdb636f8cca87fdcf4314fb2af0
2,015
adventofcode-2022
Apache License 2.0
src/Day04.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
fun main() { val input = readInput("Day04") println(Day04.part1(input)) println(Day04.part2(input)) } class Day04 { companion object { fun part1(input: List<String>): Int { return input.filter { it: String -> val (a1, a2, b1, b2) = it.split(",") .map { it.split("-").map { point -> point.toInt() } }.flatten() a1 in b1..b2 || b2 in a1..a2 }.size } fun part2(input: List<String>): Int { return input.filter { it: String -> val (a1, a2, b1, b2) = it.split(",") .map { it.split("-").map { point -> point.toInt() } }.flatten() a1 in b1..b2 || b1 in a1..a2 }.size } } }
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
773
advent-of-code-22
Apache License 2.0
src/Day01.kt
Akhunzaada
573,119,655
false
{"Kotlin": 23755}
fun main() { fun part1(input: List<String>): Int { return input.split { it.isEmpty() } .maxOf { it.sumOf { calories -> calories.toInt() } } } fun part2(input: List<String>): Int { return input.split { it.isEmpty() } .map { it.sumOf { calories -> calories.toInt() } } .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b2754454080989d9579ab39782fd1d18552394f0
680
advent-of-code-2022
Apache License 2.0
advent-of-code-2019/src/test/java/Day12TheNBodyProblem.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import org.assertj.core.api.Assertions.assertThat import org.junit.Test import kotlin.math.absoluteValue class Day12TheNBodyProblem { data class Vector(val x: Int, val y: Int, val z: Int) { operator fun plus(vel: Vector): Vector { return Vector(x + vel.x, y + vel.y, z + vel.z) } } data class Body(val pos: Vector, val vel: Vector) fun parse(input: String): List<Body> { return input.lines() .map { val split = it.split("pos=<x=", "=", ",", ">") Body( Vector( split[1].trim().toInt(), split[3].trim().toInt(), split[5].trim().toInt() ), Vector( split.getOrNull(9)?.trim()?.toInt() ?: 0, split.getOrNull(11)?.trim()?.toInt() ?: 0, split.getOrNull(13)?.trim()?.toInt() ?: 0 ) ) } } @Test fun verifySilverTestInput() { runSimulation(parse(testInput)) .take(11) .toList() .also { val first = parse( """pos=<x= 2, y=-1, z= 1>, vel=<x= 3, y=-1, z=-1> pos=<x= 3, y=-7, z=-4>, vel=<x= 1, y= 3, z= 3> pos=<x= 1, y=-7, z= 5>, vel=<x=-3, y= 1, z=-3> pos=<x= 2, y= 2, z= 0>, vel=<x=-1, y=-3, z= 1>""" ) assertThat(it[1]).isEqualTo(first) } .also { val first = parse( """pos=<x= 5, y=-3, z=-1>, vel=<x= 3, y=-2, z=-2> pos=<x= 1, y=-2, z= 2>, vel=<x=-2, y= 5, z= 6> pos=<x= 1, y=-4, z=-1>, vel=<x= 0, y= 3, z=-6> pos=<x= 1, y=-4, z= 2>, vel=<x=-1, y=-6, z= 2>""" ) assertThat(it[2]).isEqualTo(first) } .also { val first = parse( """pos=<x= 2, y= 1, z=-3>, vel=<x=-3, y=-2, z= 1> pos=<x= 1, y=-8, z= 0>, vel=<x=-1, y= 1, z= 3> pos=<x= 3, y=-6, z= 1>, vel=<x= 3, y= 2, z=-3> pos=<x= 2, y= 0, z= 4>, vel=<x= 1, y=-1, z=-1>""" ) assertThat(it[10]).isEqualTo(first) } .also { assertThat(it.last().sumBy { it.energy() }).isEqualTo(179) } } fun Body.energy(): Int = (pos.x.absoluteValue + pos.y.absoluteValue + pos.z.absoluteValue) * (vel.x.absoluteValue + vel.y.absoluteValue + vel.z.absoluteValue) @Test fun silverTest() { val initial = parse(testInput) println(initial) runSimulation(initial) .take(11) .last() .sumBy { it.energy() } .let { assertThat(it).isEqualTo(179) } } @Test fun silverTest2() { val initial = parse(testInput.trimIndent()) val answer = runSimulation(initial) .drop(1) //.takeWhile { !set.contains(it) } .takeWhile { it != initial } //.onEach { set.add(it) } .count() + 1 assertThat(answer).isEqualTo(2772) } @Test fun silver() { val initial = parse(realInput) println(initial) runSimulation(initial) .take(1001) .last() .sumBy { it.energy() } .let { assertThat(it).isEqualTo(7758) } } @Test fun goldTest() { val initial = parse(testInput) // val initial = parse(testInput.trimIndent()) (0..3).map { index -> val countX = runSimulation(initial) .drop(1) //.takeWhile { !set.contains(it) } .takeWhile { it[index].pos.x != initial[index].pos.x } .count() + 1 val countY = runSimulation(initial) .drop(1) //.takeWhile { !set.contains(it) } .takeWhile { it[index].pos.y != initial[index].pos.y } .count() + 1 val countZ = runSimulation(initial) .drop(1) //.takeWhile { !set.contains(it) } .takeWhile { it[index].pos.z != initial[index].pos.z } .count() + 1 println(countX * countY * countZ) countX } .forEach { println(it) } } // 4686774924 @Test fun goldTest2() { val initial = parse(realInput.trimIndent()) // val initial = parse(testInput.trimIndent()) var lastX: List<Pair<Int, Int>>? = null var lastY: List<Pair<Int, Int>>? = null var lastZ: List<Pair<Int, Int>>? = null val setX = mutableSetOf<List<Pair<Int, Int>>>() runSimulation(initial) .map { moons -> moons.map { moon -> moon.pos.x to moon.vel.x } } .takeWhile { lastX = it it !in setX } .forEach { setX.add(it) } val setY = mutableSetOf<List<Pair<Int, Int>>>() runSimulation(initial) .map { moons -> moons.map { moon -> moon.pos.y to moon.vel.y } } .takeWhile { lastY = it it !in setY } .forEach { setY.add(it) } val setZ = mutableSetOf<List<Pair<Int, Int>>>() runSimulation(initial) .map { moons -> moons.map { moon -> moon.pos.z to moon.vel.z } } .takeWhile { lastZ = it it !in setZ } .forEach { setZ.add(it) } val pX = setX.size.toLong() val pY = setY.size.toLong() val pZ = setZ.size.toLong() println("X size: ${pX}") println("Y size: ${pY}") println("Z size: ${pZ}") // 4686774924 // 2028 2 ∙ 2 ∙ 3 ∙ 13 ∙ 13 // 5898 /2 ∙ /3 ∙ 983 // 4702 /2 ∙ 2351 println(4686774924 / (13L * 13L * 983L * 2351L * 2 * 2 * 3)) // REAL // X size: 113028 /2 ∙ /2 ∙ 3 ∙ 9419 // Y size: 231614 /2 ∙ 115807 // Z size: 108344 2 ∙ 2 ∙ 2 ∙ 29 ∙ 467 println(3L * 9419L * 115807L * 2 * 2 * 2 * 29 * 467) } private fun runSimulation(initial: List<Body>): Sequence<List<Body>> { return generateSequence(initial) { bodies -> // apply gravity val withVelocity = bodies.map { body -> val dX = bodies.minus(body).map { otherBody -> -body.pos.x.compareTo(otherBody.pos.x) }.sum() val dY = bodies.minus(body).map { otherBody -> -body.pos.y.compareTo(otherBody.pos.y) }.sum() val dZ = bodies.minus(body).map { otherBody -> -body.pos.z.compareTo(otherBody.pos.z) }.sum() body.copy(vel = body.vel + Vector(dX, dY, dZ)) } // apply velocity withVelocity.map { body -> body.copy(pos = body.pos + body.vel) } } } val longTest = """ <x=-8, y=-10, z=0> <x=5, y=5, z=10> <x=2, y=-7, z=3> <x=9, y=-8, z=-3> """.trimIndent() val testInput = """ <x=-1, y=0, z=2> <x=2, y=-10, z=-7> <x=4, y=-8, z=8> <x=3, y=5, z=-1> """.trimIndent() val realInput = """ <x=9, y=13, z=-8> <x=-3, y=16, z=-17> <x=-4, y=11, z=-10> <x=0, y=-2, z=-2> """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
7,538
advent-of-code
MIT License
src/Day03.kt
avarun42
573,407,145
false
{"Kotlin": 8697}
import day03.Item import day03.Rucksack import day03.sharedItem fun main() { fun List<String>.toRucksacks(): Sequence<Rucksack> { return this.asSequence() .map { rucksackItems -> rucksackItems.map { Item.fromChar(it) } } .map { Rucksack(it) } } fun part1(input: List<String>): Int { return input.toRucksacks().sumOf { it.sharedItem.priority } } fun part2(input: List<String>): Int { return input.toRucksacks().chunked(3).map { it.sharedItem() }.sumOf { it.priority } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
622d022b7556dd0b2b3e3fb2abdda1c854bfe3a3
821
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/adventofcode/Day01.kt
keeferrourke
434,321,094
false
{"Kotlin": 15727, "Shell": 1301}
package com.adventofcode /** * [https://adventofcode.com/2021/day/1] */ fun sonarSweep(readings: Sequence<Int>, window: Int = 1): Int = readings .windowed(window) .map { it.sum() } .fold(listOf<Pair<Int, DepthChange>>()) { acc, windowedSum -> acc + (acc.lastOrNull()?.let { windowedSum to DepthChange.of(it.first, windowedSum) } ?: (windowedSum to DepthChange.NONE)) } .count { it.second == DepthChange.INCREASE } enum class DepthChange { NONE, INCREASE, DECREASE; companion object { fun of(prev: Int, next: Int): DepthChange { val change = next - prev return when { change > 0 -> INCREASE change < 0 -> DECREASE else -> NONE } } } } fun day01(input: String, args: List<String> = listOf("1")) { val readings = input.lineSequence().map { it.toInt() } val window = args.first().toInt() println(sonarSweep(readings, window)) }
0
Kotlin
0
0
44677c6ae0ba1a8a8dc80dfa68c17b9c315af8e2
912
aoc2021
ISC License
examples/src/main/kotlin/EightQueens.kt
alexbaryzhikov
201,620,351
false
null
import com.alexb.constraints.Problem import kotlin.math.abs import kotlin.system.measureTimeMillis /* The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal. */ fun queens(size: Int): List<Map<Int, Int>> { val problem = Problem<Int, Int>().apply { addVariables((0 until size).toList(), (0 until size).toList()) for (rowA in 0 until size - 1) { for (rowB in rowA + 1 until size) { addConstraint( { colA, colB -> colA != colB && abs(rowB - rowA) != abs(colB - colA) }, listOf(rowA, rowB) ) } } } return problem.getSolutions() } fun main() { val size = 8 lateinit var solutions: List<Map<Int, Int>> val t = measureTimeMillis { solutions = queens(size) } println("Found ${solutions.size} solution(s) in $t ms\n") for ((i, solution) in solutions.withIndex()) { print("Solution ${i + 1}: ") for (j in 0 until size) { print("${solution.getValue(j) + 1} ") } println() } }
0
Kotlin
0
0
e67ae6b6be3e0012d0d03988afa22236fd62f122
1,232
kotlin-constraints
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2022/Day3.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2022 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report class Day3: AdventDay(2022, 3) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day3() report { day.part1() } report { day.part2() } } } val priorityMap = ('a'..'z').flatMap { letter -> val lowerCase = letter to letter.code - 96 val upperchar = letter.uppercaseChar() val upperCase = upperchar to upperchar.code - 38 listOf(lowerCase, upperCase) }.toMap() fun findIntersectionPriorities(input: String): List<Int> { val half = input.length / 2 val (firstCompartment, secondCompartment) = input.chunked(half).map { it.toSet() } return firstCompartment.intersect(secondCompartment).map { priorityMap[it]!! } } fun inputToPriorities(input: List<String>): List<Int> { return input.map { findIntersectionPriorities(it).sum() } } fun badge(list: List<String>): Set<Char> { val (elf, elf2, elf3) = list return elf.toSet().intersect(elf2.toSet()).intersect(elf3.toSet()) } fun badgeSum(badges: List<String>): Int { return badges.chunked(3).flatMap { badge(it) }.sumOf { priorityMap[it]!! } } fun part1(): Int { return inputToPriorities(inputAsLines).sum() } fun part2(): Int { return badgeSum(inputAsLines) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
1,524
adventofcode
MIT License
src/main/kotlin/adventofcode2017/Day25TheHaltingProblem.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2017 class Day25TheHaltingProblem data class StateResult(val writeValue: Int, val nextDirection: Int, val nextState: TuringState) data class StateRule(val ruleOnNull: StateResult, val ruleOnOne: StateResult) sealed class TuringState { object A : TuringState() object B : TuringState() object C : TuringState() object D : TuringState() object E : TuringState() object F : TuringState() companion object { fun fromChar(state: Char): TuringState = when (state) { 'A' -> A 'B' -> B 'C' -> C 'D' -> D 'E' -> E else -> F } } } class TuringMachine(stateRules: List<String>) { val states = mutableMapOf<TuringState, StateRule>() var currentState: TuringState = TuringState.A var currentPosition = 0 val tape = mutableMapOf(0 to 0) val checksum: Int get() = tape.values.sum() init { stateRules.windowed(9, 10) { lines -> states[TuringState.fromChar(lines[0][9])] = parseRule(lines.subList(1, 9)) } } private fun parseRule(input: List<String>): StateRule { /* Sample In state A: If the current value is 0: - Write the value 1. - Move one slot to the right. - Continue with state B. If the current value is 1: - Write the value 0. - Move one slot to the left. - Continue with state D. */ val writeValueOnNull = input[1][22].code - 48 val nextDirectionOnNull = when (input[2][27]) { 'r' -> 1 else -> -1 } val nextStateOnNull = TuringState.fromChar(input[3][26]) val writeValueOnOne = input[5][22].code - 48 val nextDirectionOnOne = when (input[6][27]) { 'r' -> 1 else -> -1 } val nextStateOnOne = TuringState.fromChar(input[7][26]) val resultOnNull = StateResult(writeValueOnNull, nextDirectionOnNull, nextStateOnNull) val resultOnOne = StateResult(writeValueOnOne, nextDirectionOnOne, nextStateOnOne) return StateRule(resultOnNull, resultOnOne) } fun run(numberOfSteps: Int) { repeat(numberOfSteps) { step() } } fun step() { val tapeValue = tape[currentPosition] ?: 0 val currentStateRule = states.get(currentState) require(currentStateRule != null) val nextStateRule = if (tapeValue == 0) currentStateRule.ruleOnNull else currentStateRule.ruleOnOne with(nextStateRule) { tape[currentPosition] = writeValue currentPosition += nextDirection currentState = nextState } } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
2,746
kotlin-coding-challenges
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/PowOfFour.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.ln /** * Given an integer n, return true if it is a power of four. Otherwise, return false. * @see <a href="https://leetcode.com/problems/power-of-four/">Source</a> */ fun interface PowOfFour { fun isPow4(n: Int): Boolean } /** * Approach 1: Brute Force + Precomputations * Time complexity: O(1). * Space complexity: O(1). */ class Pow4BruteForce : PowOfFour { private val n = 15 private val nums: MutableList<Int> = ArrayList() init { var lastNum = 1 nums.add(lastNum) for (i in 1 until n + 1) { lastNum *= 4 nums.add(lastNum) } } override fun isPow4(n: Int): Boolean { return nums.contains(n) } } /** * Approach 2: Math * Time complexity: O(1). * Space complexity: O(1). */ class Pow4Math : PowOfFour { override fun isPow4(n: Int): Boolean { return n > 0 && ln(n.toDouble()) / ln(2.0) % 2 == 0.0 } } /** * Approach 2: Math * Time complexity: O(1). * Space complexity: O(1). */ class Pow4BitManipulation : PowOfFour { override fun isPow4(n: Int): Boolean { return n > 0 && n and n - 1 == 0 && n and -0x55555556 == 0 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,837
kotlab
Apache License 2.0
src/main/kotlin/days/Day12.kt
TheMrMilchmann
725,205,189
false
{"Kotlin": 61669}
/* * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* import java.util.concurrent.ConcurrentHashMap fun main() { val data = readInput().map { line -> line.split(" ").let { (str, groups) -> str to groups.split(',').map(String::toInt) } } data class State(val index: Int, val inGroup: Boolean, val lastGroup: Int, val lastGroupSize: Int) fun String.countMatches( groups: List<Int>, state: State, cache: MutableMap<State, Long> = ConcurrentHashMap() ): Long = cache.getOrPut(state) { when { state.index >= length -> if (groups.lastIndex == state.lastGroup && groups.last() == state.lastGroupSize) 1 else 0 state.lastGroup >= groups.size || (state.lastGroup != -1 && ((state.lastGroupSize > groups[state.lastGroup]) || (!state.inGroup && state.lastGroupSize < groups[state.lastGroup]))) -> 0L else -> when (val token = this[state.index]) { '.' -> countMatches(groups, state.copy(index = state.index + 1, inGroup = false), cache) '#' -> countMatches(groups, state.copy(index = state.index + 1, inGroup = true, lastGroup = state.lastGroup + if (!state.inGroup) 1 else 0, lastGroupSize = if (state.inGroup) state.lastGroupSize + 1 else 1), cache) '?' -> countMatches(groups, state.copy(index = state.index + 1, inGroup = false), cache) + countMatches(groups, state.copy(index = state.index + 1, inGroup = true, lastGroup = state.lastGroup + if (!state.inGroup) 1 else 0, lastGroupSize = if (state.inGroup) state.lastGroupSize + 1 else 1), cache) else -> error("Unexpected token: '$token'") } } } println("Part 1: ${data.sumOf { (str, groups) -> str.countMatches(groups, State(index = 0, inGroup = false, lastGroup = -1, lastGroupSize = 0)) }}") println("Part 2: ${data.map { (str, groups) -> buildList { for (i in 0..4) add(str) }.joinToString(separator = "?") to buildList { for (i in 0..4) addAll(groups) } }.sumOf { (str, groups) -> str.countMatches(groups, State(index = 0, inGroup = false, lastGroup = -1, lastGroupSize = 0)) }}") }
0
Kotlin
0
1
f94ff8a4c9fefb71e3ea183dbc3a1d41e6503152
3,226
AdventOfCode2023
MIT License
src/main/aoc2021/Day17.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 import Pos import kotlin.math.max class Day17(input: List<String>) { private val targetX: IntRange private val targetY: IntRange init { val (x1, x2, y1, y2) = """target area: x=(\d+)..(\d+), y=-(\d+)..-(\d+)""" .toRegex() .find(input.single())!! .destructured targetX = x1.toInt()..x2.toInt() targetY = -y1.toInt()..-y2.toInt() } /** * Check if the given x-velocity will hit the target before it either slows down and stops * moving forward or completely shoots past the target. */ private fun xCanHitTarget(initialVelocity: Int): Boolean { return generateSequence(initialVelocity to 0) { (v, x) -> v - 1 to x + v } .takeWhile { (v, x) -> v >= 0 && x <= targetX.last } .any { it.second in targetX } } /** * Check if the given initial velocity will hit the target at some point. */ private fun yCanHitTarget(initialVelocity: Pos): Boolean { var pos = Pos(0, 0) var velocity = initialVelocity while (pos.y >= targetY.first) { // Loop until it moves past the target if (pos.x in targetX && pos.y in targetY) { return true } pos += velocity velocity = Pos(max(0, velocity.x - 1), velocity.y - 1) } return false } /** * Return the maximum y value the given velocity will result in. */ private fun maxY(initialVelocity: Int): Int { if (initialVelocity <= 0) { return initialVelocity } // Sum of consecutive numbers: n * (first number + last number) / 2. return initialVelocity * (initialVelocity + 1) / 2 } /** * Return a list of all different shots that will hit the target */ private fun findAllShots(): List<Pos> { // Velocity higher than the distance to target will go beyond the target at first step val possibleX = (1..targetX.last).filter { xCanHitTarget(it) } return possibleX.flatMap { x -> // Shooting downward the lower limit of y velocity is the bottom boundary of the // target for the same reason as for x. // // When shooting upwards the probe will have one step at y=0 on the way down. // At this point it will have the negative initial velocity at this point. // So the highest initial velocity allowed to be able to hit the target is // the same as the distance to the end of the target. (targetY.first..-targetY.first) .map { Pos(x, it) } .filter { yCanHitTarget(it) } } } fun solvePart1(): Int { return findAllShots().maxOf { maxY(it.y) } } fun solvePart2(): Int { return findAllShots().size } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,877
aoc
MIT License
2022/Day04/problems.kt
moozzyk
317,429,068
false
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
import java.io.File import kotlin.text.* data class Segment(val from: Int, val to: Int) {} fun main(args: Array<String>) { val lines = File(args[0]).readLines() val regex = Regex("""(\d+)-(\d+),(\d+)-(\d+)""") val segments = lines.map { regex.matchEntire(it)!!.destructured }.map { (s1from, s1to, s2from, s2to) -> Pair(Segment(s1from.toInt(), s1to.toInt()), Segment(s2from.toInt(), s2to.toInt())) } println(problem1(segments)) println(problem2(segments)) } fun contains(s1: Segment, s2: Segment): Boolean = s1.from <= s2.from && s1.to >= s2.to fun overlaps(s1: Segment, s2: Segment): Boolean = !(s2.to < s1.from || s2.from > s1.to) fun problem1(segments: List<Pair<Segment, Segment>>): Int = problem(segments, ::contains) fun problem2(segments: List<Pair<Segment, Segment>>): Int = problem(segments, ::overlaps) fun problem( segments: List<Pair<Segment, Segment>>, operation: (s1: Segment, s2: Segment) -> Boolean ): Int = segments.map { operation(it.first, it.second) || operation(it.second, it.first) }.count { it }
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
1,129
AdventOfCode
MIT License
src/main/kotlin/com/kishor/kotlin/algo/problems/arrayandstrings/LongestBalancedSubstring.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.problems.arrayandstrings import java.util.* import kotlin.math.max class LongestBalancedSubstring { // O(n^3) fun longestBalancedSubstringNaive(string: String): Int { var maxLength = 0 for (i in 0 until string.length) { for (j in i + 2 until string.length + 1 step 2) { if (isBalanced(string.substring(i, j))) { val currentLength = j - i maxLength = max(maxLength, currentLength) } } } return maxLength } fun isBalanced(string: String): Boolean { val stack = Stack<Char>() for(c in string.toCharArray()) { if (c == '(') { stack.push(c) } else if (stack.isNotEmpty()) { stack.pop() } else { return false } } return stack.isEmpty() } // O(n) O(n) fun longestBalancedSubstringWithIndexedStack(string: String): Int { val indexedStack = Stack<Int>() indexedStack.push(-1) var currentLength = 0 var maxLength = 0 for (i in 0 until string.length) { if (string[i] == ')') { indexedStack.pop() if (indexedStack.isEmpty()) { indexedStack.push(i) } else { val balancedSubstringIndex = indexedStack[indexedStack.size - 1] val currentLength = i - balancedSubstringIndex maxLength = max(currentLength, maxLength) } } else { indexedStack.push(i) } } return maxLength } // O(n) O(1) fun longestBalancedSubstringConstSpace(string: String): Int { var openingCount = 0 var closingCount = 0 var currentLength = 0 var maxLength = 0 for (c in string) { if (c == ')') { closingCount++ } else { openingCount++ } if (openingCount == closingCount) { currentLength = 2 * closingCount maxLength = max(currentLength, maxLength) } else if (closingCount > openingCount) { openingCount = 0 closingCount = 0 currentLength = 0 } } openingCount = 0 closingCount = 0 currentLength = 0 for (char in string.toCharArray().size - 1 downTo 0) { val c = string[char] if (c == '(') { openingCount++ } else { closingCount++ } if (openingCount == closingCount) { currentLength = 2 * closingCount maxLength = max(currentLength, maxLength) } else if (openingCount > closingCount) { openingCount = 0 closingCount = 0 currentLength = 0 } } return maxLength } }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
3,094
DS_Algo_Kotlin
MIT License
src/Day04.kt
DiamondMiner88
573,073,199
false
{"Kotlin": 26457, "Rust": 4093, "Shell": 188}
fun main() { d4part1() d4part2() } fun d4part1() { val input = readInput("input/day04.txt") .split("\n") .filter { it.isNotBlank() } .map { it.split(",").map { val range = it.split("-"); (range[0].toInt()..range[1].toInt()) } } var total = 0 for ((elf1, elf2) in input) { if (elf1.first >= elf2.first && elf1.last <= elf2.last) total++ else if (elf2.first >= elf1.first && elf2.last <= elf1.last) total++ } println(total) } fun d4part2() { val input = readInput("input/day04.txt") .split("\n") .filter { it.isNotBlank() } .map { it.split(",").map { val range = it.split("-"); (range[0].toInt()..range[1].toInt()) } } var total = 0 loop@ for ((elf1, elf2) in input) { for (it in elf1) { if (elf2.contains(it)) { total++ continue@loop } } for (it in elf2) { if (elf1.contains(it)) { total++ continue@loop } } } println(total) }
0
Kotlin
0
0
55bb96af323cab3860ab6988f7d57d04f034c12c
1,115
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/niemeyer/aoc2022/Day23.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
/** * Advent of Code 2022, Day 23: Unstable Diffusion * Problem Description: https://adventofcode.com/2022/day/23 */ package de.niemeyer.aoc2022 import de.niemeyer.aoc.direction.CompassDirectionCCS import de.niemeyer.aoc.points.* import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName fun main() { val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt") val puzzleInput = resourceAsList(fileName = "${name}.txt") check(Day23(testInput).part1() == 110) val puzzleResultPart1 = Day23(puzzleInput).part1() println(puzzleResultPart1) check(puzzleResultPart1 == 3_917) check(Day23(testInput).part2() == 20) val puzzleResultPart2 = Day23(puzzleInput).part2() println(puzzleResultPart2) check(puzzleResultPart2 == 988) } class Day23(val input: List<String>) { var elfes = parsePoint2dSetBottomLeft(input).toMutableSet() val directions = ArrayDeque<CompassDirectionCCS>().apply { add(CompassDirectionCCS.North) add(CompassDirectionCCS.South) add(CompassDirectionCCS.West) add(CompassDirectionCCS.East) } fun round(): Boolean { val newElfes = mutableSetOf<Point2D>() val proposes = mutableMapOf<Point2D, MutableList<Point2D>>() elfes.forEach { elf -> if (elf.neighbors.count { it in elfes } == 0) { proposes.getOrPut(elf) { mutableListOf() }.add(elf) // elf has no neighbors, so it does not move } else { val candidate = directions.firstOrNull { direction -> listOf(-45, 0, 45).none { testDir -> elf.move(CompassDirectionCCS.fromDegree(direction.degree + testDir)) in elfes } }?.let { elf.move(it) } ?: elf proposes.getOrPut(candidate) { mutableListOf() }.add(elf) } } var changes = false proposes.forEach { elf, candidates -> if (candidates.size == 1) { newElfes.add(elf) if (elf != candidates[0]) { changes = true } } else { newElfes.addAll(candidates) changes = true } } elfes = newElfes directions.addLast(directions.removeFirst()) return changes } fun part1(): Int { repeat(10) { round() } val xMin = elfes.minOf { it.x } val xMax = elfes.maxOf { it.x } val yMin = elfes.minOf { it.y } val yMax = elfes.maxOf { it.y } val emptyFields = (xMax - xMin + 1) * (yMax - yMin + 1) - elfes.size return emptyFields } fun part2(): Int = generateSequence(true) { round() }.takeWhile { it }.count() }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
2,845
AoC-2022
Apache License 2.0
src/main/kotlin/icfp2019/analyzers/ConservativeDistanceAnalyzer.kt
teemobean
193,117,049
true
{"JavaScript": 797310, "Kotlin": 129405, "CSS": 9434, "HTML": 5859, "Shell": 70}
package icfp2019.analyzers import icfp2019.core.Analyzer import icfp2019.core.DistanceEstimate import icfp2019.model.* import org.jgrapht.Graph import org.jgrapht.alg.connectivity.ConnectivityInspector import org.jgrapht.alg.spanning.PrimMinimumSpanningTree import org.jgrapht.graph.AsSubgraph import org.jgrapht.graph.DefaultEdge data class ConservativeDistance(val estimate: DistanceEstimate, val pathNodes: Set<Point>) object ConservativeDistanceAnalyzer : Analyzer<(position: Point) -> ConservativeDistance> { override fun analyze(initialState: GameState): (robotId: RobotId, state: GameState) -> (position: Point) -> ConservativeDistance { val graphAnalyzer = BoardCellsGraphAnalyzer.analyze(initialState) val shortestPathAnalyzer = ShortestPathUsingDijkstra.analyze(initialState) return { id, state -> val graph: Graph<BoardCell, DefaultEdge> = graphAnalyzer(id, state) val shortestPathAlgorithm = shortestPathAnalyzer(id, state) val unwrappedNodes = AsSubgraph( graph, state.boardState().allStates() .filter { it.isWrapped.not() } .map { state.get(it.point) } .toSet() ) val connectivityInspector = ConnectivityInspector(unwrappedNodes) val connectedGraphs = connectivityInspector.connectedSets(); { point -> val node = initialState.get(point) val randomNodesFromEach = connectedGraphs.map { it.first() }.plus(node).toSet() val elements: List<BoardCell> = connectedGraphs.flatten().map { state.get(it.point) } val map = randomNodesFromEach.windowed(2, step = 1).map { (n1, n2) -> shortestPathAlgorithm.getPath(state.get(n1.point), state.get(n2.point)) } val nodes: Set<BoardCell> = map.flatMap { it.vertexList }.plus(elements).toSet() val connectedUnwrappedNodes = AsSubgraph(graph, nodes) val spanningTree = PrimMinimumSpanningTree(connectedUnwrappedNodes).spanningTree ConservativeDistance( DistanceEstimate(spanningTree.count()), spanningTree.edges.flatMap { listOf( graph.getEdgeSource(it).point, graph.getEdgeTarget(it).point ) }.toSet() ) } } } }
13
JavaScript
12
0
a1060c109dfaa244f3451f11812ba8228d192e7d
2,558
icfp-2019
The Unlicense
src/main/aoc2023/Day01.kt
Clausr
575,584,811
false
{"Kotlin": 65961}
package aoc2023 class Day01(val input: List<String>) { fun solvePart1(): Int { val sum = input.sumOf { addFirstAndLastDigit(it) } return sum } private fun addFirstAndLastDigit(line: String): Int { val first = line.first { it.isDigit() } val last = line.last { it.isDigit() } return "$first$last".toInt() } val words = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9 ) private fun String.possibleWordsAt(startingAt: Int): List<String> = (3..5).map { len -> substring(startingAt, (startingAt + len).coerceAtMost(length)) } fun solvePart2(): Int { val sum = input.sumOf { addFirstAndLastDigit( it.mapIndexedNotNull { index, c -> if (c.isDigit()) c else it.possibleWordsAt(index).firstNotNullOfOrNull {candidate -> words[candidate] } }.joinToString() ) } return sum } }
1
Kotlin
0
0
dd33c886c4a9b93a00b5724f7ce126901c5fb3ea
1,237
advent_of_code
Apache License 2.0
src/Day14.kt
dmarcato
576,511,169
false
{"Kotlin": 36664}
import kotlin.math.max import kotlin.math.min data class CavePos(val x: Int, val y: Int) enum class CaveMaterial { ROCK, SAND } fun CaveMaterial?.symbol() = when (this) { CaveMaterial.ROCK -> "#" CaveMaterial.SAND -> "o" else -> "." } class Cave { private val grid = mutableMapOf<CavePos, CaveMaterial>() private var rangeX = IntRange(500, 500) private var rangeY = IntRange(0, 0) private val floorY: Int get() = rangeY.last + 1 fun addRocks(input: List<String>) { input.forEach { row -> val positions = row.split("->").map { val (x, y) = it.trim().split(",") val pos = CavePos(x.toInt(), y.toInt()) if (pos.x < rangeX.first) rangeX = IntRange(pos.x, rangeX.last) if (pos.x > rangeX.last) rangeX = IntRange(rangeX.first, pos.x) if (pos.y < rangeY.first) rangeY = IntRange(pos.y, rangeY.last) if (pos.y > rangeY.last) rangeY = IntRange(rangeY.first, pos.y) pos } var i = 0 while (i < positions.size - 1) { val p1 = positions[i] val p2 = positions[++i] if (p1.x == p2.x) { (min(p1.y, p2.y) .. max(p1.y, p2.y)).forEach { grid[CavePos(p1.x, it)] = CaveMaterial.ROCK } } else { (min(p1.x, p2.x) .. max(p1.x, p2.x)).forEach { grid[CavePos(it, p1.y)] = CaveMaterial.ROCK } } } } } fun dropSand(withFloor: Boolean = false): Int { var drop = 0 while (true) { var pos = CavePos(500, 0) if (grid[pos] == CaveMaterial.SAND) { return drop } while (grid[pos] == null && (!withFloor || pos.y < floorY)) { pos = pos.copy(y = pos.y + 1) if (!withFloor && !rangeY.contains(pos.y)) { return drop } if (grid[pos] != null) { pos = pos.copy(x = pos.x - 1, y = pos.y) if (grid[pos] != null) { pos = pos.copy(x = pos.x + 2) if (grid[pos] != null) { pos = pos.copy(x = pos.x - 1, y = pos.y - 1) grid[pos] = CaveMaterial.SAND } } } } if (withFloor && pos.y == floorY) { grid[pos] = CaveMaterial.SAND } drop++ } } @Suppress("unused") fun print(withFloor: Boolean = false) { buildString { rangeY.forEach { y -> rangeX.forEach { x -> if (x == 500 && y == 0) append("+") else append(grid[CavePos(x, y)].symbol()) } append("\n") } if (withFloor) { (rangeY.last + 1..floorY).forEach { y -> rangeX.forEach { x -> append(grid[CavePos(x, y)].symbol()) } append("\n") } } }.println() } } fun main() { fun part1(input: List<String>): Int { val cave = Cave() cave.addRocks(input) return cave.dropSand() } fun part2(input: List<String>): Int { val cave = Cave() cave.addRocks(input) return cave.dropSand(withFloor = true) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) { "part1 check failed" } check(part2(testInput) == 93) { "part2 check failed" } val input = readInput("Day14") part1(input).println() part2(input).println() }
0
Kotlin
0
0
6abd8ca89a1acce49ecc0ca8a51acd3969979464
3,954
aoc2022
Apache License 2.0