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
day24/src/main/kotlin/ver_b.kt
jabbalaci
115,397,721
false
null
package b import java.io.File val NOT_FOUND = -1 val LEFT = 0 val RIGHT = 1 data class Component(val id: Int, val line: String) { var left : Int var right : Int init { val parts = line.split("/") left = parts[0].toInt() right = parts[1].toInt() } fun swap() { val tmp = left left = right right = tmp } override fun toString(): String { return "Component($left/$right)" } /* NOT_FOUND: the value is different from left and right LEFT: the value equals the left part RIGHT: the value equals the right part */ fun find(value: Int): Int { if (value == left) { return LEFT } else if (value == right) { return RIGHT } else { return NOT_FOUND } } } object BridgeMaker { val components = mutableListOf<Component>() var strongest = 0 var longest = 0 fun readFile(fname: String) { var id = 0 File(fname).forEachLine { line -> components.add(Component(id, line)) ++id } } fun debug() { for (comp in components) { println(comp) } } fun strength(bridge: List<Component>): Int { var total = 0 for (comp in bridge) { total += comp.left total += comp.right } return total } private fun findBridge(bridge: List<Component>, rest: List<Component>) { val currStrength = strength(bridge) val currLength = bridge.size if (currLength >= longest && currStrength > strongest) { longest = currLength strongest = currStrength } // // println(bridge) // println(rest) // println("Press ENTER...") // readLine() // if (rest.isEmpty()) { return // stop recursion } if (bridge.isEmpty()) { for (comp in rest) { val found = comp.find(0) if (found != NOT_FOUND) { if (found == RIGHT) { comp.swap() } findBridge(listOf(comp), rest.filter { it.id != comp.id }) } } } else { // the bridge is not empty val lastComp = bridge.last() for (comp in rest) { val found = comp.find(lastComp.right) if (found != NOT_FOUND) { if (found == RIGHT) { comp.swap() } findBridge(bridge + comp, rest.filter { it.id != comp.id }) } } } } fun start() { val bridge = mutableListOf<Component>() findBridge(bridge, components) } } fun main(args: Array<String>) { // example // val fname = "example.txt" // production val fname = "input.txt" BridgeMaker.readFile(fname) BridgeMaker.start() println(BridgeMaker.strongest) } //fun deepCopy(li: List<Component>) = // li.map { it.copy() }.toMutableList()
0
Kotlin
0
0
bce7c57fbedb78d61390366539cd3ba32b7726da
3,130
aoc2017
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/TaskScheduler.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT import java.util.PriorityQueue import kotlin.math.max fun interface TaskScheduler { operator fun invoke(tasks: CharArray, n: Int): Int } class TaskSchedulerSimple : TaskScheduler { override operator fun invoke(tasks: CharArray, n: Int): Int { val counter = IntArray(ALPHABET_LETTERS_COUNT) var max = 0 var maxCount = 0 for (task in tasks) { counter[task - 'A']++ if (max == counter[task - 'A']) { maxCount++ } else if (max < counter[task - 'A']) { max = counter[task - 'A'] maxCount = 1 } } val partCount = max - 1 val partLength = n - maxCount.minus(1) val emptySlots = partCount * partLength val availableTasks: Int = tasks.size - max * maxCount val idles = max(0, emptySlots - availableTasks) return tasks.size + idles } } class TaskSchedulerPriorityQueue : TaskScheduler { override operator fun invoke(tasks: CharArray, n: Int): Int { val map: MutableMap<Char, Int> = HashMap() for (i in tasks.indices) { map[tasks[i]] = map.getOrDefault(tasks[i], 0) + 1 // map key is TaskName, and value is number of times to be executed. } val q: PriorityQueue<Map.Entry<Char, Int>> = PriorityQueue { a, b -> if (a.value != b.value) b.value - a.value else a.key - b.key } q.addAll(map.entries) var count = 0 while (q.isNotEmpty()) { var k = n + 1 val tempList: MutableList<Map.Entry<Char, Int>> = ArrayList() while (k > 0 && q.isNotEmpty()) { val top: MutableMap.MutableEntry<Char, Int> = q.poll() as MutableMap.MutableEntry<Char, Int> // most frequency task top.setValue(top.value - 1) // decrease frequency, meaning it got executed tempList.add(top) // collect task to add back to queue k-- count++ // successfully executed task } for (e in tempList) { if (e.value > 0) q.add(e) // add valid tasks } if (q.isEmpty()) break count += k // if k > 0, then it means we need to be idle } return count } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,023
kotlab
Apache License 2.0
src/main/kotlin/com/jaspervanmerle/aoc2020/day/Day07.kt
jmerle
317,518,472
false
null
package com.jaspervanmerle.aoc2020.day class Day07 : Day("289", "30055") { private data class Bag(val color: String, val contents: Map<String, Int>) { fun contains(targetColor: String, bags: Map<String, Bag>): Boolean { return contents.keys.any { it == targetColor || bags.getValue(it).contains(targetColor, bags) } } fun depth(bags: Map<String, Bag>): Int { return contents.entries.sumBy { it.value + it.value * bags.getValue(it.key).depth(bags) } } } private val bags = getInput() .lines() .map { parseBag(it) } .associateBy { it.color } override fun solvePartOne(): Any { return bags.values.count { it.contains("shiny gold", bags) } } override fun solvePartTwo(): Any { return bags.getValue("shiny gold").depth(bags) } private fun parseBag(line: String): Bag { val color = line.substringBefore(" bags") val contents = line .substringAfter("contain ") .substringBefore(".") .split(", ") .filter { it != "no other bags" } .map { val parts = it.split(" ") "${parts[1]} ${parts[2]}" to parts[0].toInt() } .toMap() return Bag(color, contents) } }
0
Kotlin
0
0
81765a46df89533842162f3bfc90f25511b4913e
1,324
advent-of-code-2020
MIT License
src/Day03.kt
ajesh-n
573,125,760
false
{"Kotlin": 8882}
fun main() { fun Char.toPriority(): Int { return if (this.isUpperCase()) { code - 38 } else { code - 96 } } fun part1(input: List<String>): Int { return input.map { it.chunked(it.count() / 2) }.sumOf { it.first().first { itemType -> itemType in it.last() }.toPriority() } } fun part2(input: List<String>): Int { return input.windowed(3, 3).sumOf { compartment -> compartment[0].first { itemType -> itemType in compartment[1] && itemType in compartment[2] }.toPriority() } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2545773d7118da20abbc4243c4ccbf9330c4a187
836
kotlin-aoc-2022
Apache License 2.0
src/Day09.kt
brigittb
572,958,287
false
{"Kotlin": 46744}
fun main() { fun getMoves(input: List<String>) = input .filter { it.isNotEmpty() } .map { Movement( direction = it.substringBefore(" ").first(), step = it.substringAfter(" ").toInt(), ) } fun getSize(moves: List<Movement>, directions: Set<Char>) = moves .filter { it.direction in directions } .maxBy { it.step } .step .plus(1) fun diff(tail: Position, head: Position): Pair<Int, Int> { val xDiff = head.x - tail.x val yDiff = head.y - tail.y return Pair(xDiff, yDiff) } fun move( tail: Position, head: Position, ): Position { val (xDiff, yDiff) = diff(tail, head) val newPosition = when { xDiff == -2 && yDiff <= -1 -> Position(index = tail.index, x = tail.x - 1, y = tail.y - 1) xDiff == -2 && yDiff >= 1 -> Position(index = tail.index, x = tail.x - 1, y = tail.y + 1) xDiff == 2 && yDiff <= -1 -> Position(index = tail.index, x = tail.x + 1, y = tail.y - 1) xDiff == 2 && yDiff >= 1 -> Position(index = tail.index, x = tail.x + 1, y = tail.y + 1) xDiff <= -1 && yDiff == -2 -> Position(index = tail.index, x = tail.x - 1, y = tail.y - 1) xDiff >= 1 && yDiff == -2 -> Position(index = tail.index, x = tail.x + 1, y = tail.y - 1) xDiff <= -1 && yDiff == 2 -> Position(index = tail.index, x = tail.x - 1, y = tail.y + 1) xDiff >= 1 && yDiff == 2 -> Position(index = tail.index, x = tail.x + 1, y = tail.y + 1) xDiff == 2 -> tail.down() xDiff == -2 -> tail.up() yDiff == 2 -> tail.right() yDiff == -2 -> tail.left() else -> tail } return newPosition } fun part1(input: List<String>): Int { val moves = getMoves(input) val x = getSize(moves, setOf('U', 'D')) var head = Position(x = x - 1, y = 0) var tail = Position(x = x - 1, y = 0) val tailPositions = mutableSetOf(tail) moves.forEach { (direction, step) -> when (direction) { 'R' -> { for (i in 1 until step + 1) { head = head.right() tail = move(tail, head) tailPositions.add(tail) } } 'L' -> { for (i in 1 until step + 1) { head = head.left() tail = move(tail, head) tailPositions.add(tail) } } 'U' -> { for (i in 1 until step + 1) { head = head.up() tail = move(tail, head) tailPositions.add(tail) } } 'D' -> { for (i in 1 until step + 1) { head = head.down() tail = move(tail, head) tailPositions.add(tail) } } } } return tailPositions.size } val tailSize = 9 fun moveTail( newPositions: MutableList<Position>, head: Position, tailEndPositions: MutableSet<Position>, ) { newPositions[0] = move(newPositions.first(), head) newPositions .windowed(2) .forEach { (_, current) -> newPositions[current.index] = move( tail = current, head = newPositions[current.index - 1], ) if (current.index == tailSize - 1) tailEndPositions.add(current) } } fun part2(input: List<String>): Int { val moves = getMoves(input) val startPosition = Position(x = getSize(moves, setOf('U', 'D')) - 1, y = 0) var head = startPosition var tail = MutableList(tailSize) { i -> Position(index = i, x = startPosition.x, y = startPosition.y) } val tailEndPositions = mutableSetOf<Position>() moves.forEach { (direction, step) -> val newPositions = tail when (direction) { 'R' -> { for (i in 1 until step + 1) { head = head.right() moveTail(newPositions, head, tailEndPositions) } } 'L' -> { for (i in 1 until step + 1) { head = head.left() moveTail(newPositions, head, tailEndPositions) } } 'U' -> { for (i in 1 until step + 1) { head = head.up() moveTail(newPositions, head, tailEndPositions) } } 'D' -> { for (i in 1 until step + 1) { head = head.down() moveTail(newPositions, head, tailEndPositions) } } } tail = newPositions } return tailEndPositions.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input)) } data class Movement( val direction: Char, val step: Int, ) data class Position( val index: Int = 0, var x: Int, var y: Int, ) { fun right() = Position(index = index, x = x, y = y + 1) fun left() = Position(index = index, x = x, y = y - 1) fun up() = Position(index = index, x = x - 1, y = y) fun down() = Position(index = index, x = x + 1, y = y) }
0
Kotlin
0
0
470f026f2632d1a5147919c25dbd4eb4c08091d6
5,987
aoc-2022
Apache License 2.0
src/main/kotlin/Day03.kt
Vampire
572,990,104
false
{"Kotlin": 57326}
fun main() { val priorities = ('a'..'z') + ('A'..'Z') fun part1(input: List<String>) = input .flatMap { it .chunkedSequence(it.length / 2) .map(String::toCharArray) .reduce { a, b -> a.intersect(b.asIterable().toSet()).toCharArray() } .map(priorities::indexOf) .map(Int::inc) } .sum() fun part2(input: List<String>) = input .asSequence() .chunked(3) .flatMap { it .asSequence() .map(String::toCharArray) .reduce { a, b -> a.intersect(b.asIterable().toSet()).toCharArray() } .map(priorities::indexOf) .map(Int::inc) } .sum() val testInput = readStrings("Day03_test") check(part1(testInput) == 157) val input = readStrings("Day03") println(part1(input)) check(part2(testInput) == 70) println(part2(input)) }
0
Kotlin
0
0
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
995
aoc-2022
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/reverse_nodes_in_k_group/ReverseNodesInKGroup.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.reverse_nodes_in_k_group import katas.kotlin.leetcode.ListNode import katas.kotlin.leetcode.listNodes import datsok.shouldEqual import org.junit.Test class ReverseNodesInKGroupTests { @Test fun `reverse the nodes of a linked list k at a time`() { listNodes(1).reverseGroup(1) shouldEqual listNodes(1) listNodes(1, 2).reverseGroup(1) shouldEqual listNodes(1, 2) listNodes(1, 2, 3).reverseGroup(1) shouldEqual listNodes(1, 2, 3) listNodes(1, 2).reverseGroup(2) shouldEqual listNodes(2, 1) listNodes(1, 2, 3).reverseGroup(2) shouldEqual listNodes(2, 1, 3) listNodes(1, 2, 3, 4).reverseGroup(2) shouldEqual listNodes(2, 1, 4, 3) listNodes(1, 2, 3).reverseGroup(3) shouldEqual listNodes(3, 2, 1) listNodes(1, 2, 3, 4).reverseGroup(3) shouldEqual listNodes(3, 2, 1, 4) listNodes(1, 2, 3, 4, 5).reverseGroup(3) shouldEqual listNodes(3, 2, 1, 4, 5) listNodes(1, 2, 3, 4, 5, 6).reverseGroup(3) shouldEqual listNodes(3, 2, 1, 6, 5, 4) listNodes(1, 2, 3, 4, 5, 6, 7, 8, 9).reverseGroup(3) shouldEqual listNodes(3, 2, 1, 6, 5, 4, 9, 8, 7) } } private fun Array<ListNode?>.writeListNodes(listNode: ListNode) { this[0] = listNode (1 until size).forEach { this[it] = this[it - 1]?.next } } private fun Array<ListNode?>.reverseListNodes() { this[0]?.next = null (1 until size).forEach { this[it]?.next = this[it - 1] } } private inline fun slidingWindow(listNode: ListNode, size: Int, f: (Array<ListNode?>) -> Unit) { val window = arrayOfNulls<ListNode?>(size) var node: ListNode? = listNode while (node != null) { window.writeListNodes(node) node = window.last()?.next f(window) } } private fun ListNode.reverseGroup(size: Int): ListNode { var result: ListNode? = null var lastTip: ListNode? = null slidingWindow(this, size) { window -> if (result == null) result = window.last() if (window.any { it == null }) { lastTip?.next = window[0] return result!! } window.reverseListNodes() lastTip?.next = window.last() lastTip = window[0] } return result!! }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,224
katas
The Unlicense
src/main/kotlin/advent/of/code/day15/Solution.kt
brunorene
160,263,437
false
null
package advent.of.code.day15 import java.io.File import java.util.* import kotlin.collections.LinkedHashSet import kotlin.math.abs data class Position(val x: Int, val y: Int) : Comparable<Position> { override fun compareTo(other: Position): Int { return compareBy<Position>({ it.y }, { it.x }).compare(this, other) } override fun toString(): String { return "(${x.toString().padStart(3, ' ')},${y.toString().padStart(3, ' ')})" } private fun up() = copy(y = y - 1) private fun down() = copy(y = y + 1) private fun left() = copy(x = x - 1) private fun right() = copy(x = x + 1) fun around(near: Position? = null) = listOf(up(), left(), right(), down()) .filter { it.x >= 0 && it.y >= 0 } .sortedWith(compareBy({ it.distance(near ?: it) }, { it.y }, { it.x })) fun distance(b: Position) = abs(x - b.x) + abs(y - b.y) } fun Piece?.isDead() = (this?.hitPoints ?: 0) <= 0 sealed class Piece(open var position: Position, open val symbol: Char, open var hitPoints: Int = 200) : Comparable<Piece> { val y: Int get() = position.y val x: Int get() = position.x override fun compareTo(other: Piece) = position.compareTo(other.position) } abstract class Creature( override var position: Position, open val attack: Int = 3, override val symbol: Char ) : Piece(position, symbol) { fun damage(hit: Int) { hitPoints -= hit } abstract fun enemy(crit: Creature?): Boolean } const val WALL = '#' const val ELF = 'E' const val GOBLIN = 'G' data class Elf(override var position: Position, override val attack: Int = 3, override var hitPoints: Int = 200) : Creature(position, attack, ELF) { override fun enemy(crit: Creature?) = crit is Goblin } data class Goblin(override var position: Position, override val attack: Int = 3, override var hitPoints: Int = 200) : Creature(position, attack, GOBLIN) { override fun enemy(crit: Creature?) = crit is Elf } data class Wall(override var position: Position) : Piece(position, WALL) class GameBoard(initFile: File) { var pieces: MutableSet<Piece> = TreeSet() val elves: Set<Elf> get() = pieces.mapNotNullTo(LinkedHashSet()) { (it as? Elf) } val goblins: Set<Goblin> get() = pieces.mapNotNullTo(LinkedHashSet()) { (it as? Goblin) } val creatures: Set<Creature> get() = pieces.mapNotNullTo(LinkedHashSet()) { (it as? Creature) } init { initFile.readLines().forEachIndexed { y, line -> line.forEachIndexed { x, symbol -> val pos = Position(x, y) when (symbol) { WALL -> Wall(pos) ELF -> Elf(pos) GOBLIN -> Goblin(pos) else -> null }?.let { pieces.add(it) } } } } fun inRange(crit: Creature): Pair<Creature, Set<Position>> = crit to pieces.mapNotNull { it as? Creature } .filter { crit.enemy(it) } .flatMap { it.position.around() } .filterTo(TreeSet()) { (piece(it) !is Creature) and (piece(it) !is Wall) } private fun distance( pos1: Position, pos2: Position, pastPos: MutableList<Position> = mutableListOf(), distance: Int = 0 ): Int? = when { piece(pos1) is Wall -> null (piece(pos1) is Creature) and !piece(pos1).isDead() -> null pos1 in pastPos -> null pos1 == pos2 -> distance else -> pos1.around(pos2) .mapNotNull { distance(it, pos2, pastPos.apply { this += pos1 }, distance + 1) }.min() } fun nearestReachable(data: Pair<Creature, Set<Position>>) = data.second.flatMap { data.first.position.around(it) .map { a -> a to distance(a, it) } .filter { p -> p.second != null } }.minWith(compareBy({ it.second ?: Int.MAX_VALUE }, { it.first.y }, { it.first.x })) ?.first fun buryDead() { pieces = pieces.filterTo(TreeSet()) { it.hitPoints > 0 } } fun piece(pos: Position?) = pieces.firstOrNull { it.position == pos } override fun toString(): String { var output = "" for (y in (0..(pieces.map { it.y }.max() ?: 0))) { for (x in (0..(pieces.map { it.x }.max() ?: 0))) output += piece(Position(x, y))?.symbol ?: '.' output += '\n' } return output } } val input = File("day15-test.txt") fun part1(): Int { val board = GameBoard(input) var round = 0 println("init") println(board) while (board.elves.isNotEmpty() and board.goblins.isNotEmpty()) { round++ for (crit in board.creatures) { if (crit.isDead()) continue //move if (crit.position.around().none { crit.enemy(board.piece(it) as? Creature) }) { val chosenPos = board.nearestReachable(board.inRange(crit)) if (chosenPos != null) crit.position = chosenPos } val target = crit.position.around().filter { crit.enemy(board.piece(it) as? Creature) } .mapNotNull { board.piece(it) as? Creature } .sortedWith(compareBy({ it.hitPoints }, { it.y }, { it.x })) .firstOrNull() target?.damage(crit.attack) } board.buryDead() println("$round (${board.creatures.size}) -> ${round * board.creatures.map { it.hitPoints }.sum()}") println(board) println(board.creatures.joinToString("\n")) println() } return 0 } fun part2() = 2
0
Kotlin
0
0
0cb6814b91038a1ab99c276a33bf248157a88939
5,738
advent_of_code_2018
The Unlicense
lab11/src/main/kotlin/cs/put/pmds/lab11/Main.kt
Azbesciak
153,350,976
false
null
package cs.put.pmds.lab11 import com.carrotsearch.hppc.IntHashSet import cs.put.pmds.lab10.MinHash import cs.put.pmds.lab10.generateMinHashes import cs.put.pmds.lab9.* import java.io.File import java.math.BigDecimal import java.math.RoundingMode import java.util.stream.Stream import kotlin.math.ceil import kotlin.math.ln import kotlin.math.min import kotlin.math.pow import kotlin.streams.asStream import kotlin.system.measureTimeMillis fun main(args: Array<String>) { require(args.size == 2) { "usage: <input path> <output path>" } val (input, output) = args val file = File(input).also { require(it.exists()) { "file does not exist" } } val users = fetchUsersFromFile(file) compute(users) { (total, n, bucketSize, hash, th), usersMinHashes -> val thScaled = BigDecimal(th).setScale(2, RoundingMode.HALF_UP) println("compute lsh for total:$total n:$n rowsPerBucket:$bucketSize hash:$hash, threshold: $thScaled") val lshTime = measureTimeMillis { val lsh = LSH(n, bucketSize, hash) val neighbours = computeByLshNeighbours(lsh, users, usersMinHashes, total) val oName = formatName(output, "lsh_${n}_${bucketSize}_${hash}_$thScaled", total) writeToFile(oName, neighbours) } println("lsh $total $n $bucketSize TH:$thScaled time:$lshTime") } } private fun computeByLshNeighbours(lsh: LSH, users: List<User>, usersMinHashes: List<User>, total: Int): Stream<Pair<Int, List<Pair<Int, Double>>>> { val res = measure("lsh compute($total)") { lsh.compute(usersMinHashes) } val progressCounter = ProgressCounter(total.toLong()) return res .map { it.key to it.value } .sortedBy { it.first } .take(total) .asSequence() .asStream() .parallel() .peek { progressCounter.increment() } .map { it.first to getUserNeighbours(users, it) } } private inline fun compute(users: List<User>, f: (LSHTry, List<User>) -> Unit) { return listOf(100, 10000).forEach { total -> listOf(200, 300).forEach { n -> val minHash = MinHash(n) val usersMinHashes = users.generateMinHashes(minHash) listOf(0.05,0.15) .map { th -> computeBucketSize(n, th) } .filter { it > 2 } .distinct() .forEach { bucket -> val realThreshold = computeThreshold(n, bucket) listOf(31).forEach { hash -> f(LSHTry(total, n, bucket, hash, realThreshold), usersMinHashes) } } } } } fun computeThreshold(n: Int, rowsPerBucket: Int) = (rowsPerBucket.toDouble() / n).pow(1 / rowsPerBucket.toDouble()) data class LSHTry( val total: Int, val n: Int, val rowsPerBucket: Int, val hashInd: Int, val threshold: Double ) fun computeBucketSize(n: Int, threshold: Double): Int { val proposed = min(ceil(ln(1.0 / n) / ln(threshold)).toInt(), n) return findClosestDivider(n, proposed) } private fun findClosestDivider(n: Int, current: Int) = generateSequence(0) { it + 1 } .flatMap { listOf(it, -it).asSequence() } .map { current + it } .filter { it <= n && n > 0 } .first { n % it == 0 } private fun getUserNeighbours(users: List<User>, it: Pair<Int, IntHashSet>): List<Pair<Int, Double>> { val user = users[it.first - 1] return it.second.map { val other = users[it.value - 1] other.id to jaccardCoef(user.favourites, other.favourites) }.sortedByDescending { it.second } .filter { it.second > 0.0 } .take(100) }
0
Kotlin
0
0
f1d3cf4d51ad6588e39583f7b958c92b619799f8
3,822
BigDataLabs
MIT License
src/Day04.kt
olezhabobrov
572,687,414
false
{"Kotlin": 27363}
fun main() { fun part1(input: List<String>): Int { return input.count { line -> val (a, b, c, d) = line.split(",", "-").map { it.toInt() } assert(a <= b && c <= d) a <= c && b >= d || a >=c && b <= d } } fun part2(input: List<String>): Int { return input.count { line -> val (a, b, c, d) = line.split(",", "-").map { it.toInt() } assert(a <= b && c <= d) !(b < c || a > d) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
31f2419230c42f72137c6cd2c9a627492313d8fb
772
AdventOfCode
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2022/day23/Day23.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day23 import com.jacobhyphenated.advent2022.Day /** * Day 23: Unstable Diffusion * * The elves need to spread out to plant new trees. * The puzzle input is all the elves starting locations. * The elves look in a certain order of directions: (north,south,west,east) to determine if they should move or not. * The order changes each round. * * Example, an elf will propose a move north if the north, north-east, and north-west spaces are clear * * Once all the elves have proposed what space to move to, they only move to that space if no other elf has * also proposed moving to that space. Then the round is done. */ class Day23: Day<List<Pair<Int,Int>>> { override fun getInput(): List<Pair<Int, Int>> { return parseInput(readInputFile("day23")) } /** * Simulate 10 rounds of movement. * Then looking at the grid rectangle bounded by a space where an elf occupies the edge, * how many open spaces with no elf are there? */ override fun part1(input: List<Pair<Int, Int>>): Int { var elfLocations = input.toSet() repeat(10){ roundNum -> elfLocations = doRound(elfLocations, roundNum) } val rowMin = elfLocations.minOf { (r, _) -> r } val rowMax = elfLocations.maxOf { (r, _) -> r } val colMin = elfLocations.minOf { (_, c) -> c } val colMax = elfLocations.maxOf { (_, c) -> c } return (rowMin .. rowMax).flatMap { row -> (colMin .. colMax).filter { col -> Pair(row,col) !in elfLocations } }.count() } /** * What is the first round where no elf moves? * Brute force approach solves it in around 1.5 seconds */ override fun part2(input: List<Pair<Int, Int>>): Int { var elfLocations = input.toSet() var round = 0 while (true) { val nextElfLocations = doRound(elfLocations, round) if (nextElfLocations == elfLocations) { break } elfLocations = nextElfLocations round++ } return round + 1 } /** * Simulate a round. Use the round number and some module math to determine the order for the directions. * @return the new list of elf locations at the end of the round */ private fun doRound(elfLocations: Set<Pair<Int, Int>>, roundNum: Int): Set<Pair<Int,Int>> { // step 1 - figure out the proposed movement locations for all elves val proposed = mutableMapOf<Pair<Int,Int>, ProposedMovement>() elfLocations.forEach { val proposedLocation = proposeMovement(roundNum, it, elfLocations) val proposedMovement = proposed.getOrPut(proposedLocation) { ProposedMovement() } proposedMovement.originals.add(it) } // The elves only move to their proposed locations if no other elf also proposes the same location // otherwise those elves doen't mvoe at all return proposed.flatMap { (location, proposedMovement) -> if (proposedMovement.originals.size == 1) { listOf(location) } else { proposedMovement.originals } }.toSet() } /** * Determine what location this current elf should try to move to * @return the new proposed location, or the current location if the elf will not move this round */ private fun proposeMovement(round: Int, current: Pair<Int,Int>, elfLocations: Set<Pair<Int,Int>>): Pair<Int,Int> { val directions = Direction.values() val startIndex = round % directions.size val (row, col) = current // If all 8 spaces surrounding the current space are free, the elf doesn't move val openAdjacent = (row-1 .. row+1).flatMap { r -> (col-1 .. col+1).filter { c -> Pair(r,c) !in elfLocations } } if (openAdjacent.size == 8) { return current } // Look in each direction in the proposed order to see what space to move to val checkSpace = { toMove: Pair<Int,Int>, adjacent: List<Pair<Int,Int>> -> if (adjacent.any { it in elfLocations }) { null } else { toMove } } return directions.indices.firstNotNullOfOrNull { i -> val index = (i + startIndex) % directions.size when(directions[index]) { Direction.NORTH -> checkSpace(Pair(row - 1, col), (col - 1 .. col + 1).map { Pair(row-1, it) }) Direction.SOUTH -> checkSpace(Pair(row + 1, col), (col - 1 .. col + 1).map { Pair(row+1, it) }) Direction.WEST -> checkSpace(Pair(row, col - 1), (row - 1 .. row + 1).map { Pair(it, col-1) }) Direction.EAST -> checkSpace(Pair(row, col + 1), (row - 1 .. row + 1).map { Pair(it, col+1) }) } } ?: current } fun parseInput(input: String): List<Pair<Int,Int>> { return input.lines().flatMapIndexed { row, line -> line.mapIndexed { col, character -> if (character == '#') { Pair(row, col) } else { null } }.filterNotNull() } } } enum class Direction { NORTH, SOUTH, WEST, EAST } class ProposedMovement(val originals: MutableList<Pair<Int,Int>> = mutableListOf())
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
5,272
advent2022
The Unlicense
src/Day14.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
import kotlin.math.max import kotlin.math.min class Location(var x: Int, var y: Int, var type: Char = Type.AIR) { override fun toString(): String { return "($x, $y)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Location) return false else { if (other.x == this.x && other.y == this.y) { return true } } return false } override fun hashCode(): Int = x.hashCode() + y.hashCode() } class Type { companion object { const val ROCK = '#' const val SAND = 'o' const val AIR = '.' const val SOURCE = '+' } } fun main() { val source = Location(500, 0, Type.SOURCE) fun parse(input: String): List<Location> { return " -> ".toRegex().split(input).map { pair -> pair.split(",").let { Location(it[0].toInt(), it[1].toInt()) } } } // fun printCave(cave: MutableSet<Location>) { // for (y in cave.minOf { it.y }..cave.maxOf { it.y }) { // for (x in cave.minOf { it.x }..cave.maxOf { it.x }) { // print(cave.firstOrNull { it.x == x && it.y == y }?.type ?: Type.AIR) // } // println() // } // } fun drawLine(cave: MutableSet<Location>, list: List<Location>) { fun rangeBetween(a: Int, b: Int) = min(a, b) .. max(a, b) for (x in rangeBetween(list[0].x, list[1].x)) { for (y in rangeBetween(list[0].y, list[1].y)) { cave.add(Location(x, y, Type.ROCK)) } } } fun makeCave(input: List<String>): MutableSet<Location> { val cave = mutableSetOf<Location>() input.map { parse(it) }.forEach { pairs -> pairs.windowed(2, 1).forEach { drawLine(cave, it) } } cave.add(source) return cave } fun below(sand: Location) = Location(sand.x, sand.y + 1) fun downLeft(sand: Location) = Location(sand.x - 1, sand.y + 1) fun downRight(sand: Location) = Location(sand.x + 1, sand.y + 1) fun part1(input: List<String>): Int { val cave = makeCave(input) val maxY = cave.maxOf { it.y } val sand = Location(source.x, source.y, Type.SAND) while (sand.y < maxY) { if (!cave.contains(below(sand))) { sand.y += 1 continue } if (!cave.contains(downLeft(sand))) { sand.x -= 1 sand.y += 1 continue } if (!cave.contains(downRight(sand))) { sand.x += 1 sand.y += 1 continue } // sand comes to rest cave.add(Location(sand.x, sand.y, Type.SAND)) sand.x = source.x sand.y = source.y } // printCave(cave) return cave.filter { it.type == Type.SAND }.size } fun part2(input: List<String>): Int { val cave = makeCave(input) val maxY = cave.maxOf { it.y } val sand = Location(source.x, source.y, Type.SAND) while (true) { if (sand.y <= maxY && !cave.contains(below(sand))) { sand.y += 1 continue } if (sand.y <= maxY && !cave.contains(downLeft(sand))) { sand.x -= 1 sand.y += 1 continue } if (sand.y <= maxY && !cave.contains(downRight(sand))) { sand.x += 1 sand.y += 1 continue } // sand comes to rest cave.add(Location(sand.x, sand.y, Type.SAND)) if (sand == source) { break } else { sand.x = source.x sand.y = source.y } } // printCave(cave) return cave.filter { it.type == Type.SAND || it.type == Type.SOURCE }.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
4,316
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g1901_2000/s1923_longest_common_subpath/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1923_longest_common_subpath // #Hard #Array #Binary_Search #Hash_Function #Rolling_Hash #Suffix_Array // #2023_06_20_Time_1142_ms_(100.00%)_Space_71.9_MB_(100.00%) @Suppress("UNUSED_PARAMETER") class Solution { private lateinit var pow: LongArray fun longestCommonSubpath(n: Int, paths: Array<IntArray>): Int { var res = 0 var min = Int.MAX_VALUE for (path in paths) { min = Math.min(min, path.size) } pow = LongArray(min + 1) pow[0]++ for (i in 1..min) { pow[i] = pow[i - 1] * BASE % MOD } var st = 1 var end = min var mid = (st + end) / 2 while (st <= end) { if (commonSubstring(paths, mid)) { res = mid st = mid + 1 } else { end = mid - 1 } mid = (st + end) / 2 } return res } private fun commonSubstring(paths: Array<IntArray>, l: Int): Boolean { val set = rollingHash(paths[0], l) var i = 1 val n = paths.size while (i < n) { set.retainAll(rollingHash(paths[i], l)) if (set.isEmpty()) { return false } i++ } return true } private fun rollingHash(a: IntArray, l: Int): HashSet<Long> { val set = HashSet<Long>() var hash: Long = 0 for (i in 0 until l) { hash = (hash * BASE + a[i]) % MOD } set.add(hash) val n = a.size var curr = l var prev = 0 while (curr < n) { hash = (hash * BASE % MOD - a[prev] * pow[l] % MOD + a[curr] + MOD) % MOD set.add(hash) prev++ curr++ } return set } companion object { private const val BASE: Long = 100001 private val MOD = (Math.pow(10.0, 11.0) + 7).toLong() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,969
LeetCode-in-Kotlin
MIT License
src/Day18.kt
dakr0013
572,861,855
false
{"Kotlin": 105418}
import kotlin.test.assertEquals fun main() { fun part1(input: List<String>): Int { val lavaDroplet = LavaDroplet.parse(input) return lavaDroplet.surfaceArea() } fun part2(input: List<String>): Int { val lavaDroplet = LavaDroplet.parse(input) return lavaDroplet.surfaceAreaAccountingAirPockets() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") assertEquals(64, part1(testInput)) assertEquals(58, part2(testInput)) val input = readInput("Day18") println(part1(input)) println(part2(input)) } class LavaDroplet(private val shape: Array<Array<BooleanArray>>) { fun surfaceArea(): Int { var surfaceArea = 0 val maxXYZ = shape.lastIndex for (x in shape.indices) { for (y in shape.indices) { for (z in shape.indices) { if (!shape[x][y][z]) continue if (x == 0 || !shape[x - 1][y][z]) surfaceArea++ if (x == maxXYZ || !shape[x + 1][y][z]) surfaceArea++ if (y == 0 || !shape[x][y - 1][z]) surfaceArea++ if (y == maxXYZ || !shape[x][y + 1][z]) surfaceArea++ if (z == 0 || !shape[x][y][z - 1]) surfaceArea++ if (z == maxXYZ || !shape[x][y][z + 1]) surfaceArea++ } } } return surfaceArea } fun surfaceAreaAccountingAirPockets(): Int { var surfaceArea = 0 val maxXYZ = shape.lastIndex for (x in shape.indices) { for (y in shape.indices) { for (z in shape.indices) { if (!shape[x][y][z]) continue if (x == 0 || isAir(x - 1, y, z)) surfaceArea++ if (x == maxXYZ || isAir(x + 1, y, z)) surfaceArea++ if (y == 0 || isAir(x, y - 1, z)) surfaceArea++ if (y == maxXYZ || isAir(x, y + 1, z)) surfaceArea++ if (z == 0 || isAir(x, y, z - 1)) surfaceArea++ if (z == maxXYZ || isAir(x, y, z + 1)) surfaceArea++ } } } return surfaceArea } /** @return true if cube at x,y,z is air but not an air pocket */ private fun isAir( x: Int, y: Int, z: Int, checkedCubes: MutableSet<Cube> = mutableSetOf() ): Boolean { checkedCubes.add(Cube(x, y, z)) if (shape[x][y][z]) return false val maxXYZ = shape.lastIndex if (x == 0 || x == maxXYZ || y == 0 || y == maxXYZ || z == 0 || z == maxXYZ) return true return listOf( Cube(x - 1, y, z), Cube(x + 1, y, z), Cube(x, y - 1, z), Cube(x, y + 1, z), Cube(x, y, z - 1), Cube(x, y, z + 1), ) .filter { it !in checkedCubes } .any { isAir(it.x, it.y, it.z, checkedCubes) } } companion object { fun parse(input: List<String>): LavaDroplet { val maxCoordinate = input.flatMap { it.split(",") }.maxOf { it.toInt() } val shape = Array(maxCoordinate + 1) { Array(maxCoordinate + 1) { BooleanArray(maxCoordinate + 1) } } val cubes = input.map { val (x, y, z) = it.split(",") Cube(x.toInt(), y.toInt(), z.toInt()) } for (cube in cubes) { shape[cube.x][cube.y][cube.z] = true } return LavaDroplet(shape) } } } data class Cube(val x: Int, val y: Int, val z: Int)
0
Kotlin
0
0
6b3adb09f10f10baae36284ac19c29896d9993d9
3,271
aoc2022
Apache License 2.0
src/Utils.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
import java.io.File import java.math.BigInteger import java.security.MessageDigest /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines() /** * Reads entire input txt file. */ fun readInputAsText(name: String) = File("src", "$name.txt").readText() /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') /** * A generic graph node */ data class GraphNode(val name: String, val x: Int, val y: Int) { constructor(name: Char, x: Int, y: Int) : this(name.toString(), x, y) } /** * Performs a Dijkstra algorithm for a given graph (adjacency list) and start node */ class Dijkstra( private val graph: Map<GraphNode, List<GraphNode>>, private val start: GraphNode ) { private val unvisited = graph.keys.toMutableSet() private val visited = mutableSetOf<GraphNode>() // arbitrary values private val nodeDistances = unvisited.associateWith { Int.MAX_VALUE - 1 }.toMutableMap().apply { put(start, 0) } private fun visit(curr: GraphNode) { val currDist = nodeDistances[curr]!! + 1 for (node in graph[curr]!!) { val nodeDist = nodeDistances[node]!! if (node !in visited) { // take the smallest nodeDistances[node] = currDist.coerceAtMost(nodeDist) } } visited += curr unvisited -= curr } /** * Find the number of steps from start until end */ fun run(end: GraphNode): Int { while (end !in visited) { val curr = unvisited.minBy { nodeDistances[it]!! } visit(curr) } return nodeDistances[end]!! } /** * Find the number of steps from start to all ends */ fun runAll(ends: Set<GraphNode>): Map<GraphNode, Int> { while (!visited.containsAll(ends)) { val curr = unvisited.minBy { nodeDistances[it]!! } visit(curr) } return nodeDistances.filterKeys { it in ends } } } /** * Performs a BFS search for a given graph (adjacency list) and start node */ class BFSGraphSearch( private val graph: Map<GraphNode, List<GraphNode>>, private val start: GraphNode ) { /** * Find the number of steps from start until end */ fun run(end: GraphNode): Int { val visited = mutableSetOf<GraphNode>().apply { add(start) } val q = ArrayDeque<GraphNode>().apply { addFirst(start) } val steps = graph.keys.associateWith { Int.MAX_VALUE - 1 }.toMutableMap() var count = 0 while (q.isNotEmpty()) { val size = q.size for (n in 0 until size) { val node = q.removeFirst() steps[node]?.let { dist -> steps[node] = dist.coerceAtMost(count) } if (node == end) { break } graph[node]?.forEach { neighbor -> if (neighbor !in visited) { visited.add(neighbor) q.addLast(neighbor) } } ?: throw IllegalArgumentException("unable to find neighbors for $node") } count++ } return steps[end]!! } }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
3,365
advent-of-code-2022
Apache License 2.0
day13/src/main/kotlin/com/lillicoder/adventofcode2023/day13/Day13.kt
lillicoder
731,776,788
false
{"Kotlin": 98872}
package com.lillicoder.adventofcode2023.day13 import com.lillicoder.adventofcode2023.grids.Grid import com.lillicoder.adventofcode2023.grids.GridParser import com.lillicoder.adventofcode2023.grids.Node fun main() { val day13 = Day13() val grids = GridParser().parseFile("input.txt") println("Sum of reflections of the grids is ${day13.part1(grids)}.") println("Sum of reflections w/ smudges is ${day13.part2(grids)}.") } class Day13 { fun part1(grids: List<Grid<String>>) = ReflectionCalculator().sumReflections(grids) fun part2(grids: List<Grid<String>>) = ReflectionCalculator().sumReflectionsWithSmudges(grids) } class ReflectionCalculator { /** * Sums the count of reflected columns or rows for each of the given [Grid]. * @param grids Grids to evaluate. * @return Sum of reflections. */ fun sumReflections(grids: List<Grid<String>>) = grids.sumOf { countReflectedColumnsAndRows(it, false) } /** * Sums the count of reflected columns or rows for each of the given [Grid] allowing a single incorrect * symbol per grid. * @param grids Grids to evaluate. * @return Sum of reflections. */ fun sumReflectionsWithSmudges(grids: List<Grid<String>>) = grids.sumOf { countReflectedColumnsAndRows(it, true) } /** * Gets the number of [Node] whose values differ at each position of the given lists. * @param first First list. * @param second Second list. * @return Count of mismatches. */ private fun countMismatches( first: List<Node<String>>, second: List<Node<String>>, ) = first.map { it.value }.zip(second.map { it.value }).count { it.first != it.second } /** * Counts the number of columns and rows from a reflection point in given [Grid]. * @param grid Grid to evaluate. * @param allowSmudge True to allow grids to have symmetry when a single symbol doesn't match an analyzed row * or column pair. * @return Count of column to the left of the vertical reflection point, if any, or * the count of rows above the vertical reflection point times 100, if any. */ private fun countReflectedColumnsAndRows( grid: Grid<String>, allowSmudge: Boolean = false, ): Long { // Try to find the horizontal reflection (if any) val horizontalIndex = findHorizontalSymmetry(grid, allowSmudge) if (horizontalIndex > -1) return (horizontalIndex + 1L) * 100L // Try to find the vertical reflection (if any) val verticalIndex = findVerticalSymmetry(grid, allowSmudge) if (verticalIndex > -1) return verticalIndex + 1L return 0L } /** * Finds the row index of horizontal symmetry for the given [Grid]. * @param grid Grid to evaluate. * @param allowSmudge True if symmetry includes rows with a single symbol mismatch. * @return Row index or -1 if there was no point of symmetry found. */ private fun findHorizontalSymmetry( grid: Grid<String>, allowSmudge: Boolean = false, ): Long { for (index in 0..<grid.height - 1) { if (hasHorizontalSymmetry(grid, index, allowSmudge)) return index.toLong() } return -1L } /** * Finds the column index of vertical symmetry for the given [Grid]. * @param grid Grid to evaluate. * @param allowSmudge True if symmetry includes columns with a single symbol mismatch. * @return Column index or -1 if there was no point of symmetry found. */ private fun findVerticalSymmetry( grid: Grid<String>, allowSmudge: Boolean = false, ): Long { for (index in 0..<grid.width - 1) { if (hasVerticalSymmetry(grid, index, allowSmudge)) return index.toLong() } return -1L } /** * Checks the given [Grid] for horizontal symmetry starting from the given row index. * @param grid Grid to check. * @param index Starting row index. * @param allowSmudge True if symmetry includes rows with a single symbol mismatch. * @return True if grid is symmetrical, false otherwise. */ private fun hasHorizontalSymmetry( grid: Grid<String>, index: Int, allowSmudge: Boolean = false, ): Boolean { var start = index var end = index + 1 var mismatches = 0L while (start >= 0 && end < grid.height) { val first = grid.row(start) val second = grid.row(end) mismatches += countMismatches(first, second) start-- end++ } return mismatches == if (allowSmudge) 1L else 0L } /** * Checks the given [Grid] for vertical symmetry starting from the given column index. * @param grid Grid to check. * @param index Starting column index. * @param allowSmudge True if symmetry includes columns with a single symbol mismatch. * @return True if grid is symmetrical, false otherwise. */ private fun hasVerticalSymmetry( grid: Grid<String>, index: Int, allowSmudge: Boolean = false, ): Boolean { // Start and neighbor have identical content var start = index var end = index + 1 var mismatches = 0L while (start >= 0 && end < grid.width) { val first = grid.column(start) val second = grid.column(end) mismatches += countMismatches(first, second) start-- end++ } return mismatches == if (allowSmudge) 1L else 0L } }
0
Kotlin
0
0
390f804a3da7e9d2e5747ef29299a6ad42c8d877
5,602
advent-of-code-2023
Apache License 2.0
src/main/kotlin/day16/Day16.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day16 import java.io.File fun main() { val data = parse("src/main/kotlin/day16/Day16.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 16 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Cave( val rates: Map<String, Int>, val edges: Map<String, List<String>>, val costs: Map<Pair<String, String>, Int>, val useful: Set<String>, ) @Suppress("SameParameterValue") private fun parse(path: String): Cave { val rates = mutableMapOf<String, Int>() val edges = mutableMapOf<String, List<String>>() val useful = mutableSetOf<String>() val pattern = Regex("""Valve (\w\w) has flow rate=(\d+); tunnels? leads? to valves? (.*)""") File(path).forEachLine { line -> val (name, rate, tunnels) = (pattern.matchEntire(line) ?: error("Couldn't parse: $line")).destructured rates[name] = rate.toInt() edges[name] = tunnels.split(", ") if (rate.toInt() != 0) { useful += name } } val costs = floydWarshall(edges) return Cave(rates, edges, costs, useful) } private fun floydWarshall(edges: Map<String, List<String>>): Map<Pair<String, String>, Int> { val nodes = edges.keys val costs = mutableMapOf<Pair<String, String>, Int>() for (source in nodes) { for (target in nodes) { costs[source to target] = nodes.size + 1 } } for ((source, neighbors) in edges) { for (target in neighbors) { costs[source to target] = 1 } } for (source in nodes) { costs[source to source] = 0 } for (via in nodes) { for (source in nodes) { for (target in nodes) { if (costs[source to target]!! > costs[source to via]!! + costs[via to target]!!) { costs[source to target] = costs[source to via]!! + costs[via to target]!! } } } } return costs } private fun Cave.dfs( source: String, minutesLeft: Int, candidates: Set<String> = useful, rate: Int = 0, pressure: Int = 0, elephantAllowed: Boolean = false, ): Int { var maxPressure = pressure + rate * minutesLeft // This solution is really slow and ugly, but I don't care ¯\_(ツ)_/¯ if (elephantAllowed) { maxPressure += dfs(source = "AA", minutesLeft = 26, candidates = candidates, elephantAllowed = false) } for (target in candidates) { val cost = costs.getValue(source to target) + 1 if (minutesLeft - cost <= 0) { continue } val newPressure = dfs( source = target, minutesLeft = minutesLeft - cost, candidates = candidates - target, rate = rate + rates.getValue(target), pressure = pressure + rate * cost, elephantAllowed = elephantAllowed ) if (newPressure > maxPressure) { maxPressure = newPressure } } return maxPressure } private fun part1(cave: Cave): Int = cave.dfs(source = "AA", minutesLeft = 30) private fun part2(cave: Cave): Int = cave.dfs(source = "AA", minutesLeft = 26, elephantAllowed = true)
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
3,332
advent-of-code-2022
MIT License
usvm-util/src/main/kotlin/org/usvm/algorithms/RandomizedPriorityCollection.kt
UnitTestBot
586,907,774
false
{"Kotlin": 2547205, "Java": 471958}
package org.usvm.algorithms /** * [UPriorityCollection] implementation which peeks elements randomly with distribution based on priority. * * Implemented with tree set in which each node contains sum of its children weights (priorities). * * To peek an element, a random point in interval [[0..sum of all leaf weights]] is selected, then the node which * weight interval contains this point is found in binary-search manner. * * @param comparator comparator for elements to arrange them in tree. It doesn't affect the priorities. * @param unitIntervalRandom function returning a random value in [[0..1]] interval which is used to peek the element. */ class RandomizedPriorityCollection<T>(comparator: Comparator<T>, private val unitIntervalRandom: () -> Double) : UPriorityCollection<T, Double> { private val tree = WeightedAaTree(comparator) override val count: Int get() = tree.count private tailrec fun peekRec(targetPoint: Double, leftEndpoint: Double, peekAt: AaTreeNode<T>): T { val leftSegmentEndsAt = leftEndpoint + (peekAt.left?.weightSum ?: 0.0) val currentSegmentEndsAt = leftSegmentEndsAt + peekAt.weight return when { targetPoint < leftSegmentEndsAt && peekAt.left != null -> peekRec(targetPoint, leftEndpoint, peekAt.left) targetPoint > currentSegmentEndsAt && peekAt.right != null -> peekRec(targetPoint, currentSegmentEndsAt, peekAt.right) else -> peekAt.value } } override fun peek(): T { val root = tree.root ?: throw NoSuchElementException("Discrete PDF was empty") val randomValue = unitIntervalRandom() check(randomValue in 0.0..1.0) { "Random generator in discrete PDF returned a number outside the unit interval (${randomValue})" } val randomValueScaled = randomValue * root.weightSum return peekRec(randomValueScaled, 0.0, root) } override fun update(element: T, priority: Double) { remove(element) add(element, priority) } override fun remove(element: T) { if (!tree.remove(element)) { throw NoSuchElementException("Element not found in discrete PDF") } } override fun add(element: T, priority: Double) { require(priority >= 0.0) { "Discrete PDF cannot store elements with negative priority" } check(tree.add(element, priority)) { "Element already exists in discrete PDF" } } }
39
Kotlin
0
7
94c5a49a0812737024dee5be9d642f22baf991a2
2,473
usvm
Apache License 2.0
Kotlin/problem011.kt
emergent
116,013,843
false
null
// Problem 11 - Project Euler // http://projecteuler.net/index.php?section=problems&id=11 fun main(args: Array<String>) { val d = """ 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ .trim() .split("\n") .map { it.split(" ").map { it.toInt() } } var ans = 0; for (i in 0..20-1) { for (j in 0..20-1) { val right = if (j < 17) d[i][j] * d[i][j+1] * d[i][j+2] * d[i][j+3] else 0 val down = if (i < 17) d[i][j] * d[i+1][j] * d[i+2][j] * d[i+3][j] else 0 val dr = if (i < 17 && j < 17) d[i][j] * d[i+1][j+1] * d[i+2][j+2] * d[i+3][j+3] else 0 val dl = if (i < 17 && j >= 3) d[i][j] * d[i+1][j-1] * d[i+2][j-2] * d[i+3][j-3] else 0 ans = listOf(right, down, dr, dl, ans).max() ?: ans } } println(ans) }
0
Rust
0
0
d04f5029385c09a569c071254191c75d582fe340
1,991
ProjectEuler
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinCostClimbingStairs.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.min /** * Min Cost Climbing Stairs. * @see <a href="https://leetcode.com/problems/min-cost-climbing-stairs/">Source</a> * Time Complexity: O(N). * Space Complexity: O(1). */ fun interface MinCostClimbingStairs { operator fun invoke(cost: IntArray): Int } /** * Recursive Approach - TLE. */ class MinCostClimbingStairsRecursive : MinCostClimbingStairs { override operator fun invoke(cost: IntArray): Int { val length: Int = cost.size return min(recurse(cost, length - 1), recurse(cost, length - 2)) } private fun recurse(cost: IntArray, i: Int): Int { if (i < 0) return 0 return if (i == 0 || i == 1) { cost[i] } else { min(recurse(cost, i - 1), recurse(cost, i - 2)) + cost[i] } } } /** * Recursive Memoization. */ class MinCostClimbingStairsMemoization : MinCostClimbingStairs { override operator fun invoke(cost: IntArray): Int { val length: Int = cost.size val cache = IntArray(cost.size + 1) return min(recurse(cost, cache, length - 1), recurse(cost, cache, length - 2)) } private fun recurse(cost: IntArray, cache: IntArray, i: Int): Int { if (i < 0) return 0 if (i == 0 || i == 1) { cache[i] = cost[i] return cost[i] } if (cache[i] > 0) { return cache[i] } cache[i] = min(recurse(cost, cache, i - 1), recurse(cost, cache, i - 2)) + cost[i] return cache[i] } } /** * Bottom Up - DP Approach. */ class MinCostClimbingStairsDPBottomUp : MinCostClimbingStairs { override operator fun invoke(cost: IntArray): Int { if (cost.isEmpty()) return 0 val length: Int = cost.size val dp = IntArray(length + 1) for (i in 0 until length) { if (i == 0 || i == 1) { dp[i] = cost[i] } else { dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i] } } return min(dp[length - 1], dp[length - 2]) } } /** * DP Optimized. */ class MinCostClimbingStairsDPOptimized : MinCostClimbingStairs { override operator fun invoke(cost: IntArray): Int { var f1 = 0 var f2 = 0 for (i in cost.size - 1 downTo 0) { val f0 = cost[i] + min(f1, f2) f2 = f1 f1 = f0 } return min(f1, f2) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,058
kotlab
Apache License 2.0
original/Kotlin/KtHelloPrime.kt
alexy2008
242,878,207
false
null
import kotlin.math.ceil import kotlin.math.pow fun primeByEuler(page: Int, prime: KtPrime) { val num = BooleanArray(page) for (i in 2 until page) { if (!num[i]) prime.add(i.toLong()) for (j in 0 until prime.size() ){ if (i.toLong() * prime.getitem(j) >= page) break num[(i * prime.getitem(j)).toInt()] = true if (i % prime.getitem(j) == 0L) break } } } fun primeByEratosthenesInterval(pos: Long, page: Int, prime: KtPrime) { val num = BooleanArray(page) for (i in 0 until prime.size()) { val p = prime.getitem(i) if (p * p >= pos + page) break for (j in ceil(pos * 1.0 / p).toLong() until ((pos + page - 1) / p).toLong() + 1) num[(j * p - pos).toInt()] = true } for (i in num.indices) if (!num[i]) prime.add(pos + i) } fun main(args: Array<String>) { println("Hello sample.Prime! I'm Kotlin :-)") val limit = args[0].toLong() val page = args[1].toInt() val mode = args[2].toInt() val prime = KtPrime(limit, page, mode) println("使用分区埃拉托色尼筛选法计算${prime.getDfString(limit)}以内素数:") val costTime = kotlin.system.measureTimeMillis { //首先使用欧拉法得到种子素数组 primeByEuler(page, prime) prime.generateResults(page.toLong()) //循环使用埃拉托色尼法计算分区 for (i in 1 until limit/page) { val pos = page * i primeByEratosthenesInterval(pos, page, prime) prime.generateResults(pos + page) } } prime.printTable() System.out.printf("Kotline finished within %.0e the %dth prime is %d; time cost: %d ms \n", limit.toDouble(), prime.maxInd, prime.maxPrime, costTime) } class KtPrime(limit: Long, page: Int, private val mode: Int) { var maxInd: Long = 0 var maxPrime: Long = 0 private val maxKeep: Int = (Math.sqrt(limit.toDouble()) / Math.log(Math.sqrt(limit.toDouble())) * 1.3).toInt() var reserve = ((Math.sqrt(limit.toDouble()) + page) / Math.log(Math.sqrt(limit.toDouble()) + page) * 1.3).toInt() private val primeList: ArrayList<Long> = ArrayList(reserve) private val seqList = ArrayList<String>() private val interList = ArrayList<String>() private var prevNo: Long = 0 fun getitem(index: Int): Long { return primeList[index] } fun size(): Int { return primeList.size } fun add(p: Long) { primeList.add(p) maxInd++ } fun generateResults(inter: Long) { if (mode > 0) { putSequence(prevNo) putInterval(inter) prevNo = maxInd } maxPrime = primeList[primeList.size - 1] freeUp() } private fun putInterval(inter: Long) { val s: String if (inter % 10.0.pow(inter.toString().length - 1.toDouble()) == 0.0) { s = "${getDfString(inter)}|$maxInd|${getitem(size() - 1)}" interList.add(s) if (mode > 1) println("[In:]$s") } } private fun putSequence(beginNo: Long) { for (i in beginNo.toString().length - 1 until maxInd.toString().length) { for (j in 1..9) { val seq = (j * 10.0.pow(i.toDouble())).toLong() if (seq < beginNo) continue if (seq >= maxInd) return val l = getitem(size() - 1 - (maxInd - seq).toInt()) var s = getDfString(seq) + "|" + l seqList.add(s) if (mode > 1) println("==>[No:]$s") } } } private fun freeUp() { if (maxInd > maxKeep) primeList.subList(maxKeep, primeList.size - 1).clear() } fun printTable() { if (mode < 1) return println("## 素数序列表") println("序号|数值") println("---|---") seqList.forEach { x: String? -> println(x) } println("## 素数区间表") println("区间|个数|最大值") println("---|---|---") interList.forEach { x: String? -> println(x) } } fun getDfString(l: Long): String { var s = l.toString() when { l % 1000000000000L == 0L -> { s = s.substring(0, s.length - 12) + "万亿" } l % 100000000L == 0L -> { s = s.substring(0, s.length - 8) + "亿" } l % 10000 == 0L -> { s = s.substring(0, s.length - 4) + "万" } } return s } init { println("内存分配:$reserve") } }
0
Java
0
1
dac2f599b5f88df1fe675e5ba21046bdcb9eb127
4,622
HelloPrime
Apache License 2.0
src/main/kotlin/day18.kt
Gitvert
433,947,508
false
{"Kotlin": 82286}
import kotlin.math.ceil import kotlin.math.floor fun day18() { val lines: List<String> = readFile("day18.txt") day18part1(lines) day18part2(lines) } fun day18part1(lines: List<String>) { val sum = sumListOfSnailFishNumbers(lines) val answer = getMagnitudeOfNumber(sum) println("18a: $answer") } fun day18part2(lines: List<String>) { var maxMagnitude = -1 for (i in lines.indices) { for (j in lines.indices) { if (i == j) { continue } val sum = addSnailFishNumber(lines[i], lines[j]) val magnitude = getMagnitudeOfNumber(sum) if (magnitude > maxMagnitude) { maxMagnitude = magnitude } } } val answer = maxMagnitude println("18b: $answer") } fun sumListOfSnailFishNumbers(lines: List<String>): String { var finalSum = "" lines.forEachIndexed { index, it -> if (index < lines.size - 1) { if (finalSum.isEmpty()) { finalSum = addSnailFishNumber(lines[index], lines[index + 1]) } else { finalSum = addSnailFishNumber(finalSum, lines[index + 1]) } } } return finalSum } fun addSnailFishNumber(left: String, right: String): String { var newNumber = "[$left,$right]" while (true) { val startOfRoundNumber = newNumber newNumber = explodeSnailFishNumber(newNumber) if (startOfRoundNumber != newNumber) { continue } newNumber = splitSnailFishNumber(newNumber) if (startOfRoundNumber != newNumber) { continue } break } return newNumber } fun splitSnailFishNumber(number: String): String { var lastWasNumber = false number.forEachIndexed { index, it -> lastWasNumber = if (it.isDigit()) { if (lastWasNumber) { return number.replaceRange(index - 1..index, splitNumber(Integer.valueOf(number.substring(index - 1..index)))) } true } else { false } } return number } fun getMagnitudeOfNumber(number: String): Int { var newNumber = number while (true) { val startOfRoundNumber = newNumber newNumber = getInnerMagnitude(newNumber) if (newNumber == startOfRoundNumber) { break } } return Integer.valueOf(newNumber) } fun getInnerMagnitude(number: String): String { val regex = "\\d+,\\d+".toRegex() val result = regex.find(number) if (result != null) { val range = result.range val values = number.substring(range).split(",") val pair = Pair(Integer.valueOf(values[0]), Integer.valueOf(values[1])) val sum = pair.first * 3 + pair.second * 2 return number.replaceRange(range.first - 1..range.last + 1, sum.toString()) } return number } fun splitNumber(number: Int): String { val first = floor(number / 2.0).toInt() val second = ceil(number / 2.0).toInt() return "[$first,$second]" } fun explodeSnailFishNumber(number: String): String { var bracketDepth = 0 var explodeIndex = -1 run loop@ { number.forEachIndexed { index, it -> if (bracketDepth >= 5 && it.isDigit()) { explodeIndex = index return@loop } if (it == '[') { bracketDepth++ } else if (it == ']') { bracketDepth-- } } } if (explodeIndex == -1) { return number } val endExplodeIndex = number.indexOf(']', explodeIndex) + 1 val leftValue = Integer.valueOf(number.substring(explodeIndex, number.indexOf(',', explodeIndex))) val rightValue = Integer.valueOf(number.substring(number.indexOf(',', explodeIndex) + 1, endExplodeIndex - 1)) var leftSide = number.substring(0..explodeIndex - 2) var rightSide = number.substring(endExplodeIndex until number.length) val leftExplodeIndex = findLastNumberEndIndex(number.substring(0 until explodeIndex)) val rightExplodeIndex = findFirstNumberStartIndex(number.substring(endExplodeIndex until number.length)) if (leftExplodeIndex > 0) { val leftExplodeIndexStart = findNumberStartIndex(number.substring(0..leftExplodeIndex), leftExplodeIndex) val newNumber = Integer.valueOf(number.substring(leftExplodeIndexStart..leftExplodeIndex)) + leftValue leftSide = leftSide.replaceRange(leftExplodeIndexStart..leftExplodeIndex, newNumber.toString()) } if (rightExplodeIndex > 0) { val rightExplodeIndexEnd = findNumberEndIndex(rightSide.substring(rightExplodeIndex until rightSide.length), rightExplodeIndex) val newNumber = Integer.valueOf(rightSide.substring(rightExplodeIndex..rightExplodeIndexEnd)) + rightValue rightSide = rightSide.replaceRange(rightExplodeIndex..rightExplodeIndexEnd, newNumber.toString()) } return leftSide + "0" + rightSide } fun findLastNumberEndIndex(number: String): Int { var lastNumberIndex = -1 number.forEachIndexed { index, it -> if (it.isDigit()) { lastNumberIndex = index } } return lastNumberIndex } fun findFirstNumberStartIndex(number: String): Int { number.forEachIndexed { index, it -> if (it.isDigit()) { return index } } return -1 } fun findNumberEndIndex(number: String, startIndex: Int): Int { number.forEachIndexed { index, it -> if (!it.isDigit()) { return index - 1 + startIndex } } return startIndex } fun findNumberStartIndex(number: String, endIndex: Int): Int { number.reversed().forEachIndexed { index, it -> if (!it.isDigit()) { return endIndex - index + 1 } } return endIndex }
0
Kotlin
0
0
02484bd3bcb921094bc83368843773f7912fe757
5,887
advent_of_code_2021
MIT License
kotlin/2140-solving-questions-with-brainpower.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}
/* * DFS/Recursion + Memoization */ class Solution { fun mostPoints(questions: Array<IntArray>): Long { val memo = LongArray(questions.size) { -1L } fun dfs(i: Int): Long { if (i >= questions.size) return 0 if (memo[i] != -1L) return memo[i] memo[i] = maxOf( questions[i][0] + dfs(i + 1 + questions[i][1]), dfs(i + 1) ) return memo[i] } return dfs(0) } } /* * DP */ class Solution { fun mostPoints(q: Array<IntArray>): Long { val n = q.lastIndex val dp = LongArray(q.size) for (i in n downTo 0) { dp[i] = maxOf( if (i < n) dp[i + 1] else 0, q[i][0] + if (i + 1 + q[i][1] <= n) dp[i + 1 + q[i][1]] else 0 ) } return dp[0] } } /* * DP with HashMap instead of Array for simpler code */ class Solution { fun mostPoints(q: Array<IntArray>): Long { val n = q.lastIndex val dp = HashMap<Int, Long>() for (i in n downTo 0) { dp[i] = maxOf( dp[i + 1] ?: 0L, q[i][0] + (dp[i + 1 + q[i][1]] ?: 0L) ) } return dp[0] ?: 0L } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,308
leetcode
MIT License
src/day17/Day17.kt
ritesh-singh
572,210,598
false
{"Kotlin": 99540}
package day17 import readInput data class Position(val x: Long, val y: Long) val firstRock = listOf( Position(0 + 2, 3), Position(1 + 2, 3), Position(2 + 2, 3), Position(3 + 2, 3), ) val secondRock = listOf( Position(1 + 2, 5), Position(0 + 2, 4), Position(1 + 2, 4), Position(2 + 2, 4), Position(1 + 2, 3), ) val thirdRock = listOf( Position(2 + 2, 5), Position(2 + 2, 4), Position(0 + 2, 3), Position(1 + 2, 3), Position(2 + 2, 3) ) val fourthRock = listOf( Position(0 + 2, 6), Position(0 + 2, 5), Position(0 + 2, 4), Position(0 + 2, 3), ) val fifthRock = listOf( Position(0 + 2, 4), Position(1 + 2, 4), Position(0 + 2, 3), Position(1 + 2, 3), ) fun solve(input: List<String>, maxRocks:Long): Long { val jetPattern = input[0] var hotGasIndex = 0 val rocks = listOf(firstRock, secondRock, thirdRock, fourthRock, fifthRock) val blockedPosition = hashSetOf<Position>().apply { for (x in 0..6L) add(Position(x, -1)) } fun rightPosBlocked(rock: List<Position>): Boolean { val end = rock.any { it.x + 1 > 6 } var right = false for (blockPos in blockedPosition) { val isBlocked = rock.any { it.copy(x = it.x + 1) == blockPos } if (isBlocked) { right = true break } } return end || right } fun leftPosBlocked(rock: List<Position>): Boolean { val end = rock.any { it.x - 1 < 0 } var left = false for (blockPos in blockedPosition) { val isBlocked = rock.any { it.copy(x = it.x - 1) == blockPos } if (isBlocked) { left = true break } } return end || left } fun downPosBlocked(rock: List<Position>): Boolean { var isBlocked = false for (blockPos in blockedPosition) { isBlocked = rock.any { it.copy(y = it.y - 1) == blockPos } if (isBlocked) break } return isBlocked } fun List<Position>.move(gasIndex: Int): List<Position> { if (jetPattern[gasIndex] == '<' && !leftPosBlocked(this)) { return this.map { it.copy(x = it.x - 1, y = it.y) } } if (jetPattern[gasIndex] == '>' && !rightPosBlocked(this)) { return this.map { it.copy(x = it.x + 1, y = it.y) } } return this } fun List<Position>.drop() = this.map { it.copy(x = it.x, y = it.y - 1) } var totalRock = 1L var rockIndex = 0 var currentHeight = 0L data class State(val jetIndex: Int, val rockType: Int, ) val seen = hashMapOf<State, Pair<Long, Long>>() while (totalRock < maxRocks) { if (totalRock > 500) { if (!seen.contains(State(jetIndex = hotGasIndex, rockType = rockIndex))) { seen[State(hotGasIndex, rockIndex)] = Pair(totalRock, currentHeight) } else { val (prevTotalRock, prevHeight) = seen[State(hotGasIndex, rockIndex)]!! val cyclePeriod = totalRock - prevTotalRock if (totalRock % cyclePeriod == maxRocks % cyclePeriod) { val cycleHeight = currentHeight - prevHeight val remainingRocks = maxRocks - totalRock val cyclesRemaining = (remainingRocks / cyclePeriod) + 1 return prevHeight + (cycleHeight * cyclesRemaining) } } } var currentRock = rocks[rockIndex] currentRock = currentRock.map { it.copy(y = it.y + currentHeight) } var count = 3 while (true) { // move left or right currentRock = currentRock.move(hotGasIndex) hotGasIndex = (hotGasIndex + 1) % jetPattern.length // one unit down - first three are not blocked if (count > 0){ currentRock = currentRock.drop() count-- continue } // fall one unit down if (!downPosBlocked(currentRock)) { currentRock = currentRock.drop() } else { blockedPosition.addAll(currentRock) currentHeight = if (totalRock == 1L) { 1 } else { (blockedPosition.groupBy { it.y }.count() - 1).toLong() } break } } rockIndex = (rockIndex + 1) % 5 totalRock++ } return currentHeight } fun main() { fun part1(input: List<String>): Long = solve(input, 2023) fun part2(input: List<String>): Long = solve(input, 1000000000001L) val input = readInput("/day17/Day17") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17fd65a8fac7fa0c6f4718d218a91a7b7d535eab
4,929
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2015/calendar/day06/Day06.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2015.calendar.day06 import me.peckb.aoc._2015.calendar.day06.Day06.Action.TOGGLE import me.peckb.aoc._2015.calendar.day06.Day06.Action.TURN_OFF import me.peckb.aoc._2015.calendar.day06.Day06.Action.TURN_ON import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import javax.inject.Inject import kotlin.math.max class Day06 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::instruction) { input -> val lights = Array(1000) { Array(1000) { false } } input.forEach { (it.UL.first .. it.LR.first).forEach { y -> (it.UL.second .. it.LR.second).forEach { x -> when (it.action) { TURN_ON -> lights[y][x] = true TURN_OFF -> lights[y][x] = false TOGGLE -> lights[y][x] = !lights[y][x] } } } } lights.sumOf { row -> row.count { it } } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::instruction) { input -> val lights = Array(1000) { Array(1000) { 0 } } input.forEach { (it.UL.first .. it.LR.first).forEach { y -> (it.UL.second .. it.LR.second).forEach { x -> when (it.action) { TURN_ON -> lights[y][x] += 1 TURN_OFF -> lights[y][x] = max(0, lights[y][x] - 1) TOGGLE -> lights[y][x] += 2 } } } } lights.sumOf { row -> row.sumOf { it } } } private fun instruction(line: String) : Instruction { val parts = line.split(" ") val action = Action.fromInput(parts.take(2)) val (ULy, URx) = parts.takeLast(3).first().split(",").map(String::toInt) val (LRy, LRx) = parts.last().split(",").map(String::toInt) return Instruction(action, ULy to URx, LRy to LRx) } enum class Action { TURN_ON, TURN_OFF, TOGGLE; companion object { fun fromInput(actionStrings: List<String>): Action { return when (actionStrings[0]) { "toggle" -> TOGGLE else -> when (actionStrings[1]) { "on" -> TURN_ON "off" -> TURN_OFF else -> throw IllegalArgumentException("Unexpected Action ${actionStrings.joinToString(" ")}") } } } } } data class Instruction(val action: Action, val UL: Pair<Int, Int>, val LR: Pair<Int, Int>) }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,402
advent-of-code
MIT License
year2015/src/main/kotlin/net/olegg/aoc/year2015/day14/Day14.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day14 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2015.DayOf2015 /** * See [Year 2015, Day 14](https://adventofcode.com/2015/day/14) */ object Day14 : DayOf2015(14) { private const val TIME = 2503 private val PATTERN = ".*\\b(\\d+)\\b.*\\b(\\d+)\\b.*\\b(\\d+)\\b.*".toRegex() private val SPEEDS = lines .map { line -> val match = checkNotNull(PATTERN.matchEntire(line)) val (speed, time, rest) = match.destructured return@map Triple(speed.toInt(), time.toInt(), time.toInt() + rest.toInt()) } override fun first(): Any? { return SPEEDS.maxOf { (speed, active, period) -> ((TIME / period) * active + (TIME % period).coerceAtMost(active)) * speed } } override fun second(): Any? { val distances = SPEEDS .map { (speed, active, period) -> (0..<TIME).scan(0) { acc, value -> if (value % period < active) acc + speed else acc }.drop(1) } val timestamps = (0..<TIME) .map { second -> distances.map { it[second] } } .map { list -> val max = list.max() list.map { if (it == max) 1 else 0 } } return SPEEDS .indices .maxOf { speed -> timestamps.sumOf { it[speed] } } } } fun main() = SomeDay.mainify(Day14)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,333
adventofcode
MIT License
src/main/kotlin/days/Day8.kt
jgrgt
575,475,683
false
{"Kotlin": 94368}
package days import util.MutableMatrix import util.Point class Day8 : Day(8) { override fun partOne(): Any { val matrix = MutableMatrix.fromSingleDigits(inputList) { c -> c.digitToInt() } var count = 0 matrix.forEachPoint { p -> if (matrix.isOnEdge(p)) { count += 1 } else { if (matrix.isVisible(p)) { count += 1 } } } return count } override fun partTwo(): Any { val matrix = MutableMatrix.fromSingleDigits(inputList) { c -> c.digitToInt() } var bestScore = 0 matrix.forEachPoint { p -> val score = matrix.viewScore(p) if (score > bestScore) { bestScore = score } } return bestScore } } private fun MutableMatrix<Int>.viewScore(p: Point): Int { val height = this.get(p) val valuesUp = this.valuesList(p) { it.up() } val valuesDown = this.valuesList(p) { it.down() } val valuesLeft = this.valuesList(p) { it.left() } val valuesRight = this.valuesList(p) { it.right() } return viewDistance(valuesUp, height) * viewDistance(valuesDown, height) * viewDistance(valuesLeft, height) * viewDistance(valuesRight, height) } private fun viewDistance(heights: List<Int>, height: Int): Int { var d = heights.takeWhile { h -> h < height }.size if (d < heights.size) { d += 1 // count the higher tree } return d } fun MutableMatrix<Int>.isVisible(p: Point): Boolean { val pointValue = this.get(p) val valuesUp = this.valuesList(p) { it.up() } val valuesDown = this.valuesList(p) { it.down() } val valuesLeft = this.valuesList(p) { it.left() } val valuesRight = this.valuesList(p) { it.right() } return valuesLeft.all { it < pointValue } || valuesRight.all { it < pointValue } || valuesDown.all { it < pointValue } || valuesUp.all { it < pointValue } }
0
Kotlin
0
0
5174262b5a9fc0ee4c1da9f8fca6fb86860188f4
2,081
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/aoc2016/MazeOfTwistyLittleCubicles.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2016 import komu.adventofcode.utils.Point import utils.shortestPathBetween fun mazeOfTwistyLittleCubicles1() = shortestPathBetween(Point(1, 1), Point(31, 39)) { it.openNeighbors }?.size ?: error("no path") fun mazeOfTwistyLittleCubicles2(): Int { val seen = mutableSetOf<Point>() val queue = ArrayDeque<SearchState>() queue.add(SearchState(Point(1, 1), depth = 0)) while (queue.isNotEmpty()) { val state = queue.removeFirst() if (state.depth <= 50 && seen.add(state.point)) queue += state.next } return seen.size } private class SearchState(val point: Point, val depth: Int) { val next: List<SearchState> get() = point.openNeighbors.map { SearchState(it, depth = depth + 1) } } private val Point.openNeighbors: List<Point> get() = neighbors.filter { isOpenSpace(it.x, it.y) } private fun isOpenSpace(x: Int, y: Int): Boolean { if (x < 0 || y < 0) return false val num = (x * x) + (3 * x) + (2 * x * y) + y + (y * y) return Integer.bitCount(num + 1364) % 2 == 0 }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,086
advent-of-code
MIT License
src/day03/Solve03.kt
NKorchagin
572,397,799
false
{"Kotlin": 9272}
package day03 import utils.* import kotlin.time.ExperimentalTime import kotlin.time.measureTimedValue @ExperimentalTime fun main() { fun Char.priority(): Int = if (isUpperCase()) { this - 'A' + 27 // Uppercase item types 'A' through 'Z' have priorities 27 through 52. } else { this - 'a' + 1 // Lowercase item types 'a' through 'z' have priorities 1 through 26. } fun findShareItem(line: String): Char { val firstCompartment = line.take(line.length / 2).toSet() val secondCompartment = line.takeLast(line.length / 2).toSet() return (firstCompartment intersect secondCompartment).first() } fun findShareItemPerGroup(lines: List<String>): Char { return lines .map { it.toSet() } .reduce { acc, set -> acc intersect set } .first() } fun solveA(fileName: String): Long { val input = readInput(fileName) return input .sumOf { findShareItem(it).priority() } .toLong() } fun solveB(fileName: String): Long { val input = readInput(fileName) return input .chunked(3) .sumOf { findShareItemPerGroup(it).priority() } .toLong() } check(solveA("day03/Example") == 157L) check(solveB("day03/Example") == 70L) val input = "day03/Input.ignore" val (part1, time1) = measureTimedValue { solveA(input) } println("Part1: $part1 takes: ${time1.inWholeMilliseconds}ms") val (part2, time2) = measureTimedValue { solveB(input) } println("Part2: $part2 takes: ${time2.inWholeMilliseconds}ms") }
0
Kotlin
0
0
ed401ab4de38b83cecbc4e3ac823e4d22a332885
1,651
AOC-2022-Kotlin
Apache License 2.0
src/util/Iterables.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package util /** * Splits a list into sublists where the predicate is true, similar to String.split. */ fun <T> List<T>.split(matchInPost: Boolean = false, matchInPre: Boolean = false, predicate: (T) -> Boolean): List<List<T>> { val idx = this.indexOfFirst(predicate) return if (idx == -1) { listOf(this) } else { val preSplit = this.slice(0 until idx + if (matchInPre) 1 else 0) val tail = this.slice((idx + 1) until this.size).split(matchInPost, matchInPre, predicate).toMutableList() if (matchInPost) { tail[0] = listOf(this[idx]) + tail[0] } return listOf(preSplit) + tail } } fun <T> List<T>.split(predicate: (T) -> Boolean): List<List<T>> { val idx = this.indexOfFirst(predicate) return if (idx == -1) { listOf(this) } else { return listOf(this.take(idx)) + this.drop(idx + 1).split(predicate) } } /** * Combinatorics: generate all the ways of selecting [n] elements from [list] (ignoring order) */ fun <T> generateTakes(list: List<T>, n: Int) : Sequence<List<T>> = sequence { if (n == 1) { list.forEach { yield(listOf(it)) } } else { list.dropLast(n - 1).forEachIndexed { index, el -> val tails = generateTakes(list.subList(index + 1, list.size), n - 1) tails.forEach { yield(listOf(el) + it) } } } } fun Iterable<Int>.product(): Int { var product = 1 for (element in this) { product *= element } return product } fun Iterable<Long>.product(): Long { var product = 1L for (element in this) { product *= element } return product } fun <T> List<T>.indexOfAll(predicate: (T) -> Boolean): List<Int> { return this.mapIndexedNotNull { index, t -> if (predicate(t)) index else null } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,865
advent-of-code
Apache License 2.0
Day3/src/CrossedWires.kt
gautemo
225,219,298
false
null
import java.io.File import kotlin.math.abs fun readLines() = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readLines() fun main(){ val wires = readLines() val path1 = path(wires[0]) val path2 = path(wires[1]) val closest = closestIntersect(path1, path2) println(closest) val steps = leastSteps(path1, path2) println(steps) } fun closestIntersect(path1: List<Point>, path2: List<Point>): Int? { return path1.filter { path2.contains(it) && !it.startPoint() }.map { abs(it.x) + abs(it.y) }.min() } fun leastSteps(path1: List<Point>, path2: List<Point>): Int? { val intersects = path1.mapIndexed { i1, p1 -> Pair(i1, p1) }.filter { path2.contains(it.second) && !it.second.startPoint()} return intersects.map { path2.mapIndexed { i2, p2 -> Pair(i2, p2) }.filter { pair -> pair.second == it.second }.map { pair -> pair.first }.min()!! + it.first }.min() } fun path(wire: String): List<Point>{ val moves = wire.split(',') val path = mutableListOf(Point(0,0)) for(move in moves){ when(move[0]){ 'R' -> move(path, 1, 0, move.substring(1).toInt()) 'L' -> move(path, -1, 0, move.substring(1).toInt()) 'U' -> move(path, 0, 1, move.substring(1).toInt()) 'D' -> move(path, 0, -1, move.substring(1).toInt()) } } return path } fun move(path: MutableList<Point>, xDir: Int, yDir: Int, moves: Int){ for(i in 1..moves){ path.add(Point(path.last().x + xDir, path.last().y + yDir)) } } data class Point(val x: Int, val y: Int){ fun startPoint() = x == 0 && y == 0 }
0
Kotlin
0
0
f8ac96e7b8af13202f9233bb5a736d72261c3a3b
1,633
AdventOfCode2019
MIT License
src/Lesson6Sorting/Triangle.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
import java.util.Arrays /** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { val N = A.size if (N < 3) return 0 Arrays.sort(A) for (i in 0 until N - 2) { /** * Since the array is sorted A[i + 2] is always the greates or equal to previous values * So A[i + 2] + A[i] > A[i + 1] ALWAYS * As well ass A[i + 2] + A[i + 1] > A[i] ALWAYS * Therefore no need to check those. We only need to check if A[i] + A[i + 1] > A[i + 2]? * Since in case of MAXINTS: A[i] + A[i + 1] the code would strike an overflow * Will modify the formula to an equivalent A[i] > A[i + 2] - A[i + 1] * And inspect it there */ if (A[i] >= 0 && A[i] > A[i + 2] - A[i + 1]) { return 1 } } return 0 } /** * 93/100 * This solution will cause the overflow in case there are multiple MAXINTS in array * so it will FAIL at least one correctness test */ fun solution2(A: IntArray): Int { val N = A.size if (N < 3) return 0 Arrays.sort(A) for (i in 0 until N - 2) { /** * Since the array is sorted A[i + 2] is always the greater or equal to previous values * So A[i + 2] + A[i] > A[i + 1] ALWAYS * As well ass A[i + 2] + A[i + 1] > A[i] ALWAYS * Therefore no need to check those. We only need to check if A[i] + A[i + 1] > A[i + 2]? */ if (A[i] >= 0 && A[i] + A[i + 1] > A[i + 2]) { return 1 } } return 0 } /** * An array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and: * * A[P] + A[Q] > A[R], * A[Q] + A[R] > A[P], * A[R] + A[P] > A[Q]. * For example, consider array A such that: * * A[0] = 10 A[1] = 2 A[2] = 5 * A[3] = 1 A[4] = 8 A[5] = 20 * Triplet (0, 2, 4) is triangular. * * Write a function: * * class Solution { public int solution(int[] A); } * * that, given an array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise. * * For example, given array A such that: * * A[0] = 10 A[1] = 2 A[2] = 5 * A[3] = 1 A[4] = 8 A[5] = 20 * the function should return 1, as explained above. Given array A such that: * * A[0] = 10 A[1] = 50 A[2] = 5 * A[3] = 1 * the function should return 0. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [0..100,000]; * each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
2,613
Codility-Kotlin
Apache License 2.0
2022/Day12/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 java.util.ArrayDeque import kotlin.text.toCharArray data class Position(val row: Int, val col: Int) {} fun main(args: Array<String>) { val lines = File(args[0]).readLines() println(problem1(lines.map { it.toCharArray() })) println(problem2(lines.map { it.toCharArray() })) } fun problem1(map: List<CharArray>): Int { val start = findPosition('S', map) val end = findPosition('E', map) map[start.row][start.col] = 'a' map[end.row][end.col] = 'z' return visit(listOf(start), end, map) } fun problem2(map: List<CharArray>): Int { val start = findPosition('S', map) val end = findPosition('E', map) map[start.row][start.col] = 'a' map[end.row][end.col] = 'z' var startPos = mutableListOf<Position>() for (r in 0 until map.size) { for (c in 0 until map[0].size) { if (map[r][c] == 'a') { startPos.add(Position(r, c)) } } } return visit(startPos, end, map) } fun visit(startPos: List<Position>, endPos: Position, map: List<CharArray>): Int { var visited = mutableSetOf<Position>() var queue = ArrayDeque<Pair<Position, Int>>() startPos.forEach { queue.addLast(Pair(it, 0)) visited.add(it) } while (!queue.isEmpty()) { val (position, steps) = queue.removeFirst() if (position == endPos) { return steps } visited.add(position) val (r, c) = position if (isValid(r, c - 1, map[r][c], map) && !visited.contains(Position(r, c - 1))) { queue.addLast(Pair(Position(r, c - 1), steps + 1)) visited.add(Position(r, c - 1)) } if (isValid(r, c + 1, map[r][c], map) && !visited.contains(Position(r, c + 1))) { queue.addLast(Pair(Position(r, c + 1), steps + 1)) visited.add(Position(r, c + 1)) } if (isValid(r - 1, c, map[r][c], map) && !visited.contains(Position(r - 1, c))) { queue.addLast(Pair(Position(r - 1, c), steps + 1)) visited.add(Position(r - 1, c)) } if (isValid(r + 1, c, map[r][c], map) && !visited.contains(Position(r + 1, c))) { queue.addLast(Pair(Position(r + 1, c), steps + 1)) visited.add(Position(r + 1, c)) } } return -1 } fun findPosition(x: Char, map: List<CharArray>): Position { for (r in 0 until map.size) { for (c in 0 until map[0].size) { if (map[r][c] == x) { return Position(r, c) } } } throw Exception("Not found.") } fun isValid(row: Int, col: Int, current: Char, map: List<CharArray>): Boolean = isInMap(row, col, map) && canMoveTo(row, col, current, map) fun isInMap(row: Int, col: Int, map: List<CharArray>): Boolean = row >= 0 && col >= 0 && row < map.size && col < map[0].size fun canMoveTo(row: Int, col: Int, current: Char, map: List<CharArray>): Boolean = map[row][col].code - current.code <= 1
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
3,021
AdventOfCode
MIT License
src/aoc2022/Day09.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
import utils.* import java.rmi.UnexpectedException import kotlin.math.sign internal class Day09(val lines: List<String>) { init { lines.forEach { println(it) } } fun part1(): Any { val tailVisitedCoordinates = mutableSetOf<Coord>() var head = Coord.xy(0, 0) var tail = Coord.xy(0, 0) for (l in lines) { val (dir, n) = l.split(" ") // Move num steps in dir direction repeat(n.toInt()) { head = moveHead(dir, head) tail = follow(head, tail) tailVisitedCoordinates.add(tail) } } return tailVisitedCoordinates.size } fun part2(): Any { val tailVisitedCoordinates = mutableSetOf<Coord>() // Make some knots val knots = (0 until 10).map { Coord.xy(0, 0) }.toMutableList() for (l in lines) { val (dir, n) = l.split(" ") // Move num steps in dir direction repeat(n.toInt()) { knots[0] = moveHead(dir, knots[0]) // Move each follower knot for (i in 1 until knots.size) { knots[i] = follow(knots[i - 1], knots[i]) } tailVisitedCoordinates.add(knots.last()) } } return tailVisitedCoordinates.size } /** Moves the head one step in the specified direction. */ private fun moveHead(dir: String, head: Coord): Coord { return head + when (dir) { "R" -> Coord.RIGHT "L" -> Coord.LEFT "U" -> Coord.UP "D" -> Coord.DOWN else -> throw UnexpectedException("This should not happen $dir") } } /** Outputs where b is after following a. If a is adjacent to b, b does not move. */ fun follow(a: Coord, b: Coord) : Coord { if (b !in a.neighbors()) { return Coord.rc(b.r + (a.r - b.r).sign, b.c + (a.c - b.c).sign) } return b } } fun main() { val day = "09".toInt() val todayTest = Day09(readInput(9, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 13) val today = Day09(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1", 6464) val todayTest2 = Day09(readInput(9, 2022, true, 2)) execute(todayTest2::part2, "Day[Test] $day: pt 2", 36) execute(today::part2, "Day $day: pt 2", 2604) }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
2,170
aoc2022
Apache License 2.0
src/main/kotlin/g1701_1800/s1738_find_kth_largest_xor_coordinate_value/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1738_find_kth_largest_xor_coordinate_value // #Medium #Array #Matrix #Bit_Manipulation #Heap_Priority_Queue #Prefix_Sum #Divide_and_Conquer // #Quickselect #2023_06_16_Time_936_ms_(100.00%)_Space_146.3_MB_(100.00%) class Solution { fun kthLargestValue(matrix: Array<IntArray>, k: Int): Int { var t = 0 val rows: Int = matrix.size val cols: Int = matrix[0].size val prefixXor: Array<IntArray> = Array(rows + 1) { IntArray(cols + 1) } val array = IntArray(rows * cols) for (r in 1..rows) { for (c in 1..cols) { prefixXor[r][c] = ( matrix[r - 1][c - 1] xor prefixXor[r - 1][c] xor prefixXor[r][c - 1] xor prefixXor[r - 1][c - 1] ) array[t++] = prefixXor[r][c] } } val target: Int = array.size - k quickSelect(array, 0, array.size - 1, target) return array[target] } private fun quickSelect(array: IntArray, left: Int, right: Int, target: Int): Int { if (left == right) { return left } val pivot: Int = array[right] var j: Int = left var k: Int = right - 1 while (j <= k) { if (array[j] < pivot) { j++ } else if (array[k] > pivot) { k-- } else { swap(array, j++, k--) } } swap(array, j, right) return if (j == target) { j } else if (j > target) { quickSelect(array, left, j - 1, target) } else { quickSelect(array, j + 1, right, target) } } private fun swap(array: IntArray, i: Int, j: Int) { val tmp: Int = array[i] array[i] = array[j] array[j] = tmp } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,912
LeetCode-in-Kotlin
MIT License
2021/src/main/kotlin/day25_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Parser import utils.Solution import utils.wrap fun main() { Day25Func.run() } object Day25Func : Solution<IntGrid>() { override val name = "day25" private const val EMPTY = 0 private const val EAST = 1 private const val SOUTH = 2 override val parser = Parser { input -> input .replace('.', '0') .replace('>', '1') .replace('v', '2') }.map { IntGrid.singleDigits(it) } private fun tryMove(grid: IntGrid, type: Int): IntGrid { val xAxis = type == EAST return grid.map { coord, value -> if (value == type) { // move if next is empty val toX = if (xAxis) (coord.x + 1).wrap(grid.width) else coord.x val toY = if (!xAxis) (coord.y + 1).wrap(grid.height) else coord.y if (grid[toX][toY] == EMPTY) EMPTY else type } else if (value == EMPTY) { val fromX = if (xAxis) (coord.x - 1).wrap(grid.width) else coord.x val fromY = if (!xAxis) (coord.y - 1).wrap(grid.height) else coord.y if (grid[fromX][fromY] == type) type else EMPTY } else { value } } } fun step(grid: IntGrid): IntGrid { return tryMove(tryMove(grid, EAST), SOUTH) } override fun part1(input: IntGrid): Number? { return generateSequence(IntGrid.EMPTY to input) { it.second to step(it.second) } .takeWhile { it.first != it.second } .count() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,397
aoc_kotlin
MIT License
app-quality-insights/api/src/com/android/tools/idea/insights/IssueStats.kt
JetBrains
60,701,247
false
{"Kotlin": 47313864, "Java": 36708134, "HTML": 1217549, "Starlark": 856523, "C++": 321587, "Python": 100400, "C": 71515, "Lex": 66732, "NSIS": 58538, "AIDL": 35209, "Shell": 28591, "CMake": 26717, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.insights /** * Ensures the minimum number of [StatsGroup]s and [DataPoint]s within a group if applicable. * * Given a number N, the resulting [IssueStats] will have at least top N values plus the "Other" * value if applicable. */ const val MINIMUM_SUMMARY_GROUP_SIZE_TO_SHOW = 3 /** * Ensures we show distributions if the given manufacturer/model/OS accounts for more than this * percentage of the total. */ const val MINIMUM_PERCENTAGE_TO_SHOW = 10.0 private const val OTHER_GROUP = "Other" /** Stats of an [Issue]. */ data class IssueStats<T : Number>(val topValue: String?, val groups: List<StatsGroup<T>>) { fun isEmpty() = topValue == null && groups.isEmpty() } /** A named group of [DataPoint]s. */ data class StatsGroup<T : Number>( val groupName: String, val percentage: T, val breakdown: List<DataPoint<T>> ) /** Represents a leaf named data point. */ data class DataPoint<T : Number>(val name: String, val percentage: T) data class DetailedIssueStats(val deviceStats: IssueStats<Double>, val osStats: IssueStats<Double>) fun <T : Number> T.percentOf(total: T): Double = ((this.toDouble() / total.toDouble()) * 100) /** * Returns the count of elements from [this] whose values are greater than [threshold], meanwhile * [minElementCount] is ensured if not met. */ fun List<Double>.resolveElementCountBy(minElementCount: Int, threshold: Double): Int { return indexOfFirst { it <= threshold }.coerceAtLeast(minElementCount) } /** * Returns summarized distributions of Oses. * * Please ensure the input of the data points are sorted by [WithCount.count] in descending order. */ fun List<WithCount<OperatingSystemInfo>>.summarizeOsesFromRawDataPoints( minGroupSize: Int, minPercentage: Double ): IssueStats<Double> { if (isEmpty()) return IssueStats(null, emptyList()) val totalEvents = sumOf { it.count } val topOs = first().value.displayName val statsGroups = map { StatsGroup(it.value.displayName, it.count.percentOf(totalEvents), emptyList()) } val resolvedGroupSize = statsGroups.map { it.percentage }.resolveElementCountBy(minGroupSize, minPercentage) val others = statsGroups.drop(resolvedGroupSize) return IssueStats( topOs, statsGroups.take(resolvedGroupSize) + if (others.isEmpty()) listOf() else listOf( StatsGroup( OTHER_GROUP, others.sumOf { it.percentage }, others .map { DataPoint(it.groupName, it.percentage) } .let { points -> // Here we just show top N (minGroupSize) + "Other" in the sub "Other" group. points.take(minGroupSize) + if (minGroupSize >= points.size) listOf() else listOf( DataPoint(OTHER_GROUP, points.drop(minGroupSize).sumOf { it.percentage }) ) } ) ) ) } /** * Returns summarized distributions of devices. * * Please ensure the input of the data points are sorted by [WithCount.count] in descending order. */ fun List<WithCount<Device>>.summarizeDevicesFromRawDataPoints( minGroupSize: Int, minPercentage: Double ): IssueStats<Double> { if (isEmpty()) return IssueStats(null, emptyList()) val topDevice = first().value val totalEvents = sumOf { it.count } val statsGroups = groupBy { it.value.manufacturer } .map { (manufacturer, reports) -> val groupEvents = reports.sumOf { it.count } val totalDataPoints = reports .sortedByDescending { it.count } .map { DataPoint(it.value.model.substringAfter("/"), it.count.percentOf(totalEvents)) } val resolvedGroupSize = totalDataPoints.map { it.percentage }.resolveElementCountBy(minGroupSize, minPercentage) val topGroupSizePercentages = totalDataPoints.take(resolvedGroupSize).sumOf { it.percentage } StatsGroup( manufacturer, groupEvents.percentOf(totalEvents), totalDataPoints.take(resolvedGroupSize) + if (resolvedGroupSize >= totalDataPoints.size) listOf() else listOf( DataPoint(OTHER_GROUP, groupEvents.percentOf(totalEvents) - topGroupSizePercentages) ) ) } .sortedByDescending { it.percentage } val resolvedGroupSize = statsGroups.map { it.percentage }.resolveElementCountBy(minGroupSize, minPercentage) val others = statsGroups.drop(resolvedGroupSize) return IssueStats( topDevice.model, statsGroups.take(resolvedGroupSize) + if (others.isEmpty()) listOf() else listOf( StatsGroup( OTHER_GROUP, others.sumOf { it.percentage }, others .map { DataPoint(it.groupName, it.percentage) } .let { points -> // Here we just show top N (minGroupSize) + "Other" in the sub "Other" group. points.take(minGroupSize) + if (minGroupSize >= points.size) listOf() else listOf( DataPoint(OTHER_GROUP, points.drop(minGroupSize).sumOf { it.percentage }) ) } ) ) ) }
2
Kotlin
231
892
ca717ad602b0c2141bd5e7db4a88067a55b71bfe
5,945
android
Apache License 2.0
src/main/kotlin/day10/Day10.kt
dustinconrad
572,737,903
false
{"Kotlin": 100547}
package day10 import readResourceAsBufferedReader fun main() { println("part 1: ${part1(readResourceAsBufferedReader("10_1.txt").readLines())}") println("part 2: \n${part2(readResourceAsBufferedReader("10_1.txt").readLines())}") } fun part1(input: List<String>): Int { val instrs = input.map { Instruction.parse(it) } val signalStrength = signalStrength(instrs) return listOf(20, 60, 100, 140, 180, 220) .map { signalStrength[it - 1] } .sum() } fun part2(input: List<String>): String { val instrs = input.map { Instruction.parse(it) } val spritePos = runResults(instrs) return spritePos.mapIndexed { cycle, pos -> val cycleX = cycle % 40 if ((pos - 1..pos + 1).contains(cycleX)) { "#" } else { "." } }.joinToString("") .chunked(40) .joinToString("\n") } sealed class Instruction(val cycles: Int) { abstract fun complete(cpu: Cpu) companion object { fun parse(line: String): Instruction { return if (line == "noop") { NoOp } else { val (_, v) = line.split(" ") AddX(v.toInt()) } } } } data class AddX(val value: Int): Instruction(2) { override fun complete(cpu: Cpu) { cpu.register += value } } object NoOp : Instruction(1) { override fun complete(cpu: Cpu) { //do nothing } } fun runResults(instrs: List<Instruction>): List<Int> { val cpu = Cpu() return instrs.flatMap { cpu.step(it) } } fun signalStrength(instrs: List<Instruction>): List<Int> { val cpu = Cpu() return instrs.flatMap { cpu.step(it) } .mapIndexed { idx, v -> (idx + 1) * v } } class Cpu { var register = 1 fun step(instr: Instruction): List<Int> { val currX = register instr.complete(this) return MutableList(instr.cycles) { currX } } }
0
Kotlin
0
0
1dae6d2790d7605ac3643356b207b36a34ad38be
1,948
aoc-2022
Apache License 2.0
src/net/sheltem/common/NumericUtils.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.common import kotlin.math.abs infix fun Int?.nullsafeMax(other: Int?): Int? = when { other == null -> this this == null -> other else -> maxOf(this, other) } infix operator fun Pair<Long, Long>.plus(other: Pair<Long, Long>): Pair<Long, Long> = first + other.first to second + other.second fun Pair<Long, Long>.absoluteDifference(): Long = let { (a, b) -> if (abs(a) >= abs(b)) abs(a) - abs(b) else abs(b) - abs(a) } fun Collection<Long>.multiply(): Long = reduce { acc, l -> acc * l } fun List<Long>.gcd(): Long { var result = this[0] for (i in 1 until this.size) { var num1 = result var num2 = this[i] while (num2 != 0L) { val temp = num2 num2 = num1 % num2 num1 = temp } result = num1 } return result } fun Pair<Long, Long>.lcm(): Long { val larger = if (first > second) first else second val maxLcm = first * second var lcm = larger while (lcm <= maxLcm) { if (lcm % first == 0L && lcm % second == 0L) { return lcm } lcm += larger } return maxLcm } fun List<Long>.lcm(): Long { var result = this[0] for (i in 1 until this.size) { result = (result to this[i]).lcm() } return result } fun <T : Comparable<T>> maxOfOrNull(a: T?, b: T?): T? { return when { a == null -> b b == null -> a else -> maxOf(a, b) } } fun Long.wordify(): String { val digitMap = mapOf(1 to "one", 2 to "two", 3 to "three", 4 to "four", 5 to "five", 6 to "six", 7 to "seven", 8 to "eight", 9 to "nine") val tenDigitMap = mapOf(2 to "twenty", 3 to "thirty", 4 to "forty", 5 to "fifty", 6 to "sixty", 7 to "seventy", 8 to "eighty", 9 to "ninety") val tenMap = mapOf( 10 to "ten", 11 to "eleven", 12 to "twelve", 13 to "thirteen", 14 to "fourteen", 15 to "fifteen", 16 to "sixteen", 17 to "seventeen", 18 to "eighteen", 19 to "nineteen" ) var num = this.toString() var result = "" while (num.isNotEmpty() && num.toInt() != 0) { result += when (num.length) { 1 -> digitMap[num.toInt()].also { num = "" } 2 -> tenDigitMap[num.first().digitToInt()]?.also { num = num.drop(1) } ?: tenMap[num.toInt()]?.also { num = num.drop(2) } ?: "".also { num = num.drop(1) } 3 -> { var text = (digitMap[num.first().digitToInt()] + "hundred") num = num.drop(1) if (num.toInt() != 0) { text += "and" } text } 4 -> (digitMap[num.first().digitToInt()] + "thousand").also { num = num.drop(1) } else -> "" } } println("$result = ${result.length}") return result }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,954
aoc
Apache License 2.0
src/main/kotlin/day01_sonar_sweep/SonarSweep.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day01_sonar_sweep import util.saveTextFile import java.io.PrintWriter import java.io.StringWriter import java.util.* /** * Classic day one: prove you can read in a text file, get numeric values out of * it, and then loop over them. * * Part two requires the a windowed loop, instead of treating each item * separately. Kotlin has a library function which can be simply injected into * part one's solution without changing anything else (consider [partOneZip] vs * [partTwoZip]). */ fun main() { util.solve(1616, ::partOneFold) util.solve(1616, ::partOneLoop) util.solve(1616, ::partOneZip) util.solve(1645, ::partTwo) util.solve(1645, ::partTwoZip) saveTextFile(::csv, "csv") } private fun depthsOne(depths: Sequence<Int>) = depths fun partOneFold(input: String) = depthsOne( input .lineSequence() .map(String::toInt) ) .fold(Pair(0, Int.MAX_VALUE)) { (n, prev), it -> Pair(if (it > prev) n + 1 else n, it) } .first fun partOneLoop(input: String): Int { var prev = Int.MAX_VALUE var count = 0 for (it in input.lineSequence()) { val n = it.toInt() if (n > prev) { count += 1 } prev = n } return count } fun partOneZip(input: String) = input .lineSequence() .map(String::toInt) .zipWithNext() .count { (a, b) -> a < b } fun partTwo(input: String): Int { var prev = Int.MAX_VALUE var curr = 0 var count = 0 val buffer: Queue<Int> = LinkedList() for (it in input.lineSequence()) { val n = it.toInt() buffer.add(n) curr += n if (buffer.size > 3) { curr -= buffer.remove() } if (buffer.size == 3) { if (curr > prev) { count += 1 } prev = curr } } return count } fun partTwoZip(input: String) = input .lineSequence() .map(String::toInt) .windowed(size = 3, transform = List<Int>::sum) // new vs partOneZip .zipWithNext() .count { (a, b) -> a < b } private fun depthsTwo(raw: Sequence<Int>) = raw .windowed(3, partialWindows = true) .map { it.sum() / it.size } fun csv(input: String): String { val sw = StringWriter() val out = PrintWriter(sw) csv(input, out) out.close() return sw.toString() } private fun csv(input: String, out: PrintWriter) { out.println("pos,depth,smooth_depth") val raw = input .lineSequence() .map { it.toInt() } depthsOne(raw) .zip(depthsTwo(raw)) .forEachIndexed { i, (r, s) -> out.println("$i,$r,$s") } }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
2,750
aoc-2021
MIT License
src/jvmMain/kotlin/day01/refined/Day01.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day01.refined import java.io.File fun main() { // solvePart1() // Solution: 55816 solvePart2() // Solution: 54980 } fun solvePart1() { // val input = File("src/jvmMain/kotlin/day01/input/input_part1_test.txt") val input = File("src/jvmMain/kotlin/day01/input/input.txt") val lines = input.readLines() val result = lines.sumOf { line -> "${line.first { it.isDigit() }}${line.last { it.isDigit() }}".toInt() } println(result) } val wordNumbers = 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 ) val allNumbers = (wordNumbers.keys + wordNumbers.values.map { it.toString() }).toList() val allNumbersReversed = allNumbers.map { it.reversed() } // eno, owt, eerht, etc... fun solvePart2() { // val input = File("src/jvmMain/kotlin/day01/input/input_part2_test.txt") val input = File("src/jvmMain/kotlin/day01/input/input.txt") val lines = input.readLines() val result = lines.sumOf { line -> val firstNumber = line.firstOfAny(allNumbers).convertToDigit() val lastNumber = line.reversed().firstOfAny(allNumbersReversed).reversed().convertToDigit() 10 * firstNumber + lastNumber } println(result) } fun String.firstOfAny(values: List<String>): String = values.minBy { number -> val index = indexOf(number) if (index == -1) Int.MAX_VALUE else index } fun String.convertToDigit(): Int = if (this[0].isDigit()) this.toInt() else wordNumbers[this]!!.toInt()
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
1,557
advent-of-code
MIT License
src/Day10.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 8 private const val EXPECTED_2 = 10 // Way too complicated with trying all 4 directions from the start point, but it works private class Day10(isTest: Boolean) : Solver(isTest) { val connections = mapOf( '|' to listOf(0 to -1, 0 to 1), '-' to listOf(-1 to 0, 1 to 0), 'L' to listOf(0 to -1, 1 to 0), 'J' to listOf(0 to -1, -1 to 0), '7' to listOf(0 to 1, -1 to 0), 'F' to listOf(0 to 1, 1 to 0), '.' to listOf(), 'S' to listOf(0 to 1, 0 to -1, 1 to 0, -1 to 0) ) val dirs = listOf(0 to 1, 0 to -1, 1 to 0, -1 to 0) val field = readAsLines().map { it.toCharArray() } val X = field[0].size val Y = field.size var startPoint = 0 to 0 val allPoints = (0 until Y).flatMap { y -> (0 until X).map { x -> x to y } } init { for (y in 0 until Y) { for (x in 0 until X) { if (field[y][x] == 'S') { startPoint = x to y } } } } fun createMap(dir: Pair<Int, Int>): Map<Pair<Int, Int>, Int> { val map = mutableMapOf<Pair<Int, Int>, Int>() val queue = mutableListOf(startPoint) var step = 0 while (queue.isNotEmpty()) { val newQueue = mutableListOf<Pair<Int, Int>>() for (point in queue) { if (map.containsKey(point)) continue map[point] = step val conns = if (field[point.second][point.first] == 'S') listOf(dir) else connections[field[point.second][point.first]]!! for (d in conns) { val newPoint = point.first + d.first to point.second + d.second if (newPoint.first !in 0 until X || newPoint.second !in 0 until Y) continue if (!connections[field[newPoint.second][newPoint.first]]!!.contains(-d.first to -d.second)) continue newQueue.add(newPoint) } } queue.clear() queue.addAll(newQueue) step++ } return map } fun part1(): Any { val maps = dirs.map { createMap(it) } var best = 0 for (a in 0..3) for (b in (a + 1)..3) { val f1 = maps[a] val f2 = maps[b] for (point in allPoints) { if (point !in f1 || point !in f2) continue best = maxOf(best, minOf(f1[point]!!, f2[point]!!)) } } return best } fun part2(): Any { val maps = dirs.map { createMap(it) } var best = 0 var bestParams = listOf(0, 0, 0, 0) for (a in 0..3) for (b in (a + 1)..3) { val f1 = maps[a] val f2 = maps[b] for (point in allPoints) { if (point !in f1 || point !in f2) continue if (minOf(f1[point]!!, f2[point]!!) > best) { best = minOf(f1[point]!!, f2[point]!!) bestParams = listOf(a, b, point.first, point.second) } } } val inEdge: MutableSet<Pair<Int, Int>> = mutableSetOf() tailrec fun walkBack(p: Pair<Int, Int>, map: Map<Pair<Int, Int>, Int>) { inEdge.add(p) if (map[p] == 0) return var nextPoint = -1 to -1 for (d in connections[field[p.second][p.first]]!!) { val newPoint = p.first + d.first to p.second + d.second if (newPoint.first !in 0 until X || newPoint.second !in 0 until Y) continue if (!connections[field[newPoint.second][newPoint.first]]!!.contains(-d.first to -d.second)) continue if (map[newPoint]!! < map[p]!!) { nextPoint = newPoint } } if (nextPoint == -1 to -1) throw Exception("No next point") walkBack(nextPoint, map) } fun findConnection(a: Int, b: Int): Char { val d1 = dirs[a] val d2 = dirs[b] return connections.entries.filter { it.value.contains(d1) && it.value.contains(d2) } .first().key } walkBack(bestParams[2] to bestParams[3], maps[bestParams[0]]) walkBack(bestParams[2] to bestParams[3], maps[bestParams[1]]) field[startPoint.second][startPoint.first] = findConnection(bestParams[0], bestParams[1]) var sum = 0 for (y in 0 until Y) { var inside = false for (x in 0 until X) { if (x to y in inEdge) { val conn = connections[field[y][x]]!! val yMovement = conn.maxOf { it.second } if (yMovement > 0) { inside = !inside } } else { if (inside) { sum++ } } } } return sum } } fun main() { val testInstance = Day10(true) val instance = Day10(false) // testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } // println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
5,552
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day6.kt
Gitvert
433,947,508
false
{"Kotlin": 82286}
import java.math.BigInteger fun day6() { val lines: List<String> = readFile("day06.txt") day6part1(lines) day6part2(lines) } fun day6part1(lines: List<String>) { val answer = solve(lines, 79) println("6a: $answer") } fun day6part2(lines: List<String>) { val answer = solve(lines, 255) println("6b: $answer") } fun solve(lines: List<String>, iterations: Int): BigInteger { var fishMap = initFishMap(lines) for (i in 0..iterations) { fishMap = moveOneDay(fishMap) } return fishMap[0]!! + fishMap[1]!! + fishMap[2]!! + fishMap[3]!! + fishMap[4]!! + fishMap[5]!! + fishMap[6]!! + fishMap[7]!! + fishMap[8]!! } fun moveOneDay(fishMap: MutableMap<Int, BigInteger>): MutableMap<Int, BigInteger> { val newFishMap: MutableMap<Int, BigInteger> = mutableMapOf() newFishMap[0] = fishMap[1]!! newFishMap[1] = fishMap[2]!! newFishMap[2] = fishMap[3]!! newFishMap[3] = fishMap[4]!! newFishMap[4] = fishMap[5]!! newFishMap[5] = fishMap[6]!! newFishMap[6] = (fishMap[7]!! + fishMap[0]!!) newFishMap[7] = fishMap[8]!! newFishMap[8] = fishMap[0]!! return newFishMap } fun initFishMap(lines: List<String>): MutableMap<Int, BigInteger> { val fishMap: MutableMap<Int, BigInteger> = mutableMapOf() for (i in 0..8) { fishMap[i] = BigInteger.ZERO } lines[0].split(",").forEach { val internalTimer = Integer.valueOf(it) fishMap[internalTimer] = fishMap[internalTimer]!! + BigInteger.ONE } return fishMap }
0
Kotlin
0
0
02484bd3bcb921094bc83368843773f7912fe757
1,540
advent_of_code_2021
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem28/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem28 /** * LeetCode page: [28. Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/); */ class Solution { /* Complexity: * Time O(N+M) and Space O(M) where N and M are the length of haystack and needle; */ fun strStr(haystack: String, needle: String): Int { if (haystack.length < needle.length) { return -1 } return kmpSearch(haystack, needle) } private fun kmpSearch(text: String, pattern: String): Int { val pi = buildPrefixFunctionForKmp(pattern) var q = -1 for ((index, char) in text.withIndex()) { while (q > -1 && pattern[q + 1] != char) { q = pi[q] } if (pattern[q + 1] == char) { q++ } if (q == pattern.lastIndex) { // If it is to find all occurrences, set q to pi[q] here return index - pattern.length + 1 } } return -1 } private fun buildPrefixFunctionForKmp(pattern: String): IntArray { /* pi(q) ::= max { k : k < q and P_k is suffix of P_q } where P_k and P_q are * the prefix of P up to index k and q inclusively. */ val pi = IntArray(pattern.length).apply { this[0] = -1 } var k = pi[0] for (q in 1 until pattern.length) { while (k > -1 && pattern[k + 1] != pattern[q]) { k = pi[k] } if (pattern[k + 1] == pattern[q]) { k++ } pi[q] = k } return pi } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,695
hj-leetcode-kotlin
Apache License 2.0
solutions/src/main/kotlin/fr/triozer/aoc/y2022/Day02.kt
triozer
573,964,813
false
{"Kotlin": 16632, "Shell": 3355, "JavaScript": 1716}
package fr.triozer.aoc.y2022 import fr.triozer.aoc.utils.readInput // #region other private enum class Action(val value: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun from(value: String) = when (value) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> throw IllegalArgumentException("Unknown action: $value") } } // #region added-for-part-2 fun beats() = when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } fun beaten() = when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } // #endregion added-for-part-2 fun compare(other: Action): Int = when { this == other -> 3 this == ROCK && other == SCISSORS -> 6 this == PAPER && other == ROCK -> 6 this == SCISSORS && other == PAPER -> 6 else -> 0 } } // #endregion other // #region part1 private fun part1(input: List<String>) = input.fold(0) { acc, round -> val (player1, player2) = round.split(" ").map(Action.Companion::from) acc + player2.value + player2.compare(player1) } // #endregion part1 // #region part2 private fun part2(input: List<String>) = input.fold(0) { acc, round -> val (p1, goal) = round.split(" ") val player1 = Action.from(p1) // We define the action based on the goal val player2 = when (goal) { "X" -> player1.beats() "Y" -> player1 else -> player1.beaten() } acc + player2.value + player2.compare(player1) } // #endregion part2 private fun main() { val testInput = readInput(2022, 2, "test") check(part1(testInput) == 15) check(part2(testInput) == 12) println("Checks passed ✅") val input = readInput(2022, 2, "input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a9f47fa0f749a40e9667295ea8a4023045793ac1
1,887
advent-of-code
Apache License 2.0
src/day14/Day14.kt
Ciel-MC
572,868,010
false
{"Kotlin": 55885}
package day14 import readInput sealed class Tile { data object Wall: Tile() class Sand(private val grid: Grid): Tile(), Iterable<Sand.MoveResult> { private var x = 500 private var y = 0 init { grid[x, y] = this } enum class MoveResult { MOVED, STUCK, DELETED } fun tick(): MoveResult { check(grid[x, y] == this) val downResult = checkAndMove(x, y + 1) ?: run { // if the movement is out of bound, we hit the abyss and is deleted grid[x, y] = Empty // delete this sand return MoveResult.DELETED } if (downResult) return MoveResult.MOVED // If we can't move down, try to move left down if (checkAndMove(x-1, y+1) == true) return MoveResult.MOVED // If we can't move left down, try to move right down if (checkAndMove(x+1, y+1) == true) return MoveResult.MOVED // If we can't move right down, we're stuck return MoveResult.STUCK } private fun checkAndMove(x: Int, y: Int): Boolean? { val tile = grid[x, y] ?: return null if (tile == Empty) { grid[x, y] = this grid[this.x, this.y] = Empty this.x = x this.y = y return true } return false } override fun iterator(): Iterator<MoveResult> = generateSequence(MoveResult.MOVED) { if (it == MoveResult.MOVED) tick() else null }.iterator().also { it.next() } override fun toString(): String { return "Sand" } } data object Empty: Tile() } enum class Movement { LEFT_DOWN, DOWN, RIGHT_DOWN, STATIONARY } class Grid(width: Int, height: Int) { private val inside: List<MutableList<Tile>> = List(height+1) { MutableList(width+1) { Tile.Empty } } private val heightRange = 0..height private val widthRange = 0..width operator fun get(x: Int, y: Int): Tile? = if (x in widthRange && y in heightRange) inside[y][x] else null operator fun set(x: Int, y: Int, tile: Tile) { // println("Setting $x, $y to $tile") if (x !in widthRange || y !in heightRange) return inside[y][x] = tile } operator fun set(x: Int, ys: IntRange, tile: Tile) = ys.forEach { this[x, it] = tile } operator fun set(xs: IntRange, y: Int, tile: Tile) = xs.forEach { this[it, y] = tile } override fun toString(): String = inside.map { it.joinToString("") { tile -> when (tile) { Tile.Wall -> "#" is Tile.Sand -> "o" Tile.Empty -> "." } } }.mapIndexed { index, s -> "${index.toString().padStart(2, '0')} $s" }.joinToString("\n") } fun<T: Comparable<T>> ordered(a: T, b: T): Pair<T, T> = if (a < b) a to b else b to a fun createGrid(input: List<String>, withFloor: Boolean = false): Grid { val inputs = input .map { it.split(" -> ") } .map { it.map { it.split(",").let { (a, b) -> a.toInt() to b.toInt() } } } .toMutableList() val grid = run { val flattened = inputs.flatten() var height = flattened.maxBy { it.second }.second val width = flattened.maxBy { it.first }.first * 2 if (withFloor) { height += 2 inputs.add(listOf(0 to height, width to height)) } Grid(width, height) } inputs.forEach { it.windowed(2, partialWindows = false).forEach { (a, b) -> if (a.first == b.first) { val (y1, y2) = ordered(a.second, b.second) grid[a.first, y1..y2] = Tile.Wall } else { val (x1, x2) = ordered(a.first, b.first) grid[x1..x2, a.second] = Tile.Wall } } } return grid } fun main() { fun part1(input: List<String>): Int { val grid = createGrid(input) var count = 0 while (true) { val sand = Tile.Sand(grid) count++ var result: Tile.Sand.MoveResult? = null sand.forEach { result = it } when(result!!) { Tile.Sand.MoveResult.MOVED -> error("This should not happen") Tile.Sand.MoveResult.STUCK -> continue Tile.Sand.MoveResult.DELETED -> break } } return count-1 } fun part2(input: List<String>): Int { val grid = createGrid(input, true) var count = 0 while (true) { if (grid[500, 0] != Tile.Empty) break val sand = Tile.Sand(grid) count++ var result: Tile.Sand.MoveResult? = null sand.forEach { result = it } // println(grid) when(result!!) { Tile.Sand.MoveResult.MOVED -> error("This should not happen") Tile.Sand.MoveResult.STUCK -> continue Tile.Sand.MoveResult.DELETED -> error("This should not happen either") } } return count } val testInput = readInput(14, true) part1(testInput).let { check(it == 24) { println(it) } } part2(testInput).let { check(it == 93) { println(it) } } val input = readInput(14) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7eb57c9bced945dcad4750a7cc4835e56d20cbc8
5,469
Advent-Of-Code
Apache License 2.0
src/main/kotlin/com/marcdenning/adventofcode/day23/Day23a.kt
marcdenning
317,730,735
false
{"Kotlin": 87536}
package com.marcdenning.adventofcode.day23 import java.util.Collections.* fun main(args: Array<String>) { var cups = args[0].map { Integer.parseInt(it + "") } val moves = args[1].toInt() for (i in 1..moves) { cups = moveCups(cups) } println(getCupsStateString(cups)) } /** * Conduct moves for 1 round: * * 1. Pick up 3 cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle. * 2. Pick destination cup: the cup with a label equal to the current cup's label minus one. If this would select one of the cups that was just picked up, the crab will keep subtracting one until it finds a cup that wasn't just picked up. If at any point in this process the value goes below the lowest value on any cup's label, it wraps around to the highest value on any cup's label instead. * 3. Places the cups just picked up so that they are immediately clockwise of the destination cup. They keep the same order as when they were picked up. * 4. Select a new current cup: the cup which is immediately clockwise of the current cup. * * @param cups current state of cups, current cup is always index 0 * @return new state of cups after a round */ fun moveCups(cups: List<Int>): List<Int> { val movedCups = mutableListOf(*cups.toTypedArray()) val removedCups = mutableListOf<Int>() for (i in 1..3) { removedCups.add(movedCups.removeAt(1)) } val destinationCupIndex = findDestinationCupIndex(movedCups) movedCups.addAll(destinationCupIndex + 1, removedCups) rotate(movedCups, -1) return movedCups } fun findDestinationCupIndex(cups: List<Int>): Int { val currentCup = cups[0] var destinationCup = currentCup - 1 if (cups.contains(destinationCup)) { return cups.indexOf(destinationCup) } do { destinationCup-- if (destinationCup < min(cups)) { destinationCup = max(cups) } } while (!cups.contains(destinationCup)) return cups.indexOf(destinationCup) } fun getCupsStateString(cups: List<Int>): String { val assembledCups = mutableListOf(*cups.toTypedArray()) val indexOf1 = assembledCups.indexOf(1) rotate(assembledCups, -indexOf1) assembledCups.remove(1) return assembledCups.joinToString(separator = "", transform = {i -> "" + i}) }
0
Kotlin
0
0
b227acb3876726e5eed3dcdbf6c73475cc86cbc1
2,387
advent-of-code-2020
MIT License
src/net/sheltem/aoc/y2016/Day04.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2016 import net.sheltem.common.ALPHABET suspend fun main() { Day04().run(true) } class Day04 : Day<Int>(1514, 4) { override suspend fun part1(input: List<String>): Int { return input.map { Room.from(it) }.filter { it.isValid() }.sumOf { it.id } } override suspend fun part2(input: List<String>): Int { return input.map { Room.from(it, true) }.first { it.name.contains("northpole") }.id } class Room(val name: String, val id: Int, val checksum: String) { override fun toString() = "$name: $id - $checksum" fun isValid(): Boolean = name .groupingBy { it } .eachCount() .entries .asSequence() .sortedBy { it.key } .sortedByDescending { it.value } .map { it.key } .take(5) .joinToString("", "") == checksum companion object { fun from(roomString: String, shift: Boolean = false): Room { val name = roomString.substring(0, roomString.indexOfFirst { it.isDigit() }).replace("-", "") val id = roomString.substring(roomString.indexOfFirst { it.isDigit() }, roomString.indexOfFirst { it == '[' }).toInt() val checksum = roomString.substring(roomString.indexOfFirst { it == '[' } + 1).dropLast(1) return Room(if (shift) name.shift(id) else name, id, checksum) } } } } private fun String.shift(id: Int) = map { ALPHABET[(ALPHABET.indexOf(it) + id).mod(26)] }.joinToString("")
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
1,573
aoc
Apache License 2.0
src/main/kotlin/21.kts
reitzig
318,492,753
false
null
import java.io.File typealias Ingredient = String typealias Allergen = String data class Food(val ingredients: List<Ingredient>, val allergens: List<Allergen>) { companion object { val linePattern = Regex("^([^(]*)\\(contains ([^)]*)\\)$") operator fun invoke(foodLine: String): Food { with(linePattern.matchEntire(foodLine) ?: throw IllegalArgumentException("invalid line $foodLine")) { val ingredients = groupValues[1].trim().split(Regex("\\s+")) val allergens = groupValues[2].trim().split(",").map { it.trim() } return@invoke Food(ingredients, allergens) } } } } // Input: val foods = File(args[0]).readLines() .map { Food(it) } val ingredients = foods.flatMap { it.ingredients }.distinct().sorted() as List<Ingredient> val allergens = foods.flatMap { it.allergens }.distinct().sorted() as List<Allergen> // Part 1: val ingredientCandidates = allergens.map { allergen -> ingredients .filter { ingredient -> foods.none { it.allergens.contains(allergen) && !it.ingredients.contains(ingredient) } } .let { Pair(allergen, it) } }.toMap() ingredients .filterNot { ingredientCandidates.values.flatten().contains(it) } .map { ingredient -> foods.count { it.ingredients.contains(ingredient) } } .sum() .also { println(it) } // Part 2: val ingredientAllergens = ingredientCandidates.toMutableMap() do { val assigned = ingredientAllergens .filterValues { it.size == 1 } .flatMap { (_, i) -> i } val notAssigned = ingredientAllergens.filterValues { it.size > 1 } for ((allergen, ingredients) in notAssigned) { ingredientAllergens[allergen] = ingredients.subtract(assigned).toList() } } while (notAssigned.isNotEmpty()) ingredientAllergens .toList() .sortedBy { (all, _) -> all } .flatMap { (_, ing) -> ing } .joinToString(",") .also { println(it) }
0
Kotlin
0
0
f17184fe55dfe06ac8897c2ecfe329a1efbf6a09
1,972
advent-of-code-2020
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/FourKeysKeyboard.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.max /** * 4 Keys Keyboard. * @see <a href="https://leetcode.com/problems/4-keys-keyboard/">Source</a> */ fun interface FourKeysKeyboard { fun maxA(n: Int): Int } /** * Approach #1: Dynamic Programming. */ class FourKeysKeyboardDP : FourKeysKeyboard { override fun maxA(n: Int): Int { val best = IntArray(n + 1) for (k in 1..n) { best[k] = best[k - 1] + 1 for (x in 0 until k - 1) best[k] = max(best[k], best[x] * (k - x - 1)) } return best[n] } } /** * Approach #3: Mathematical. */ class FourKeysKeyboardMath : FourKeysKeyboard { override fun maxA(n: Int): Int { val q = if (n > MAX) (n - N_MAX) / MULTIPLY_LIMIT else 0 return best[n - MULTIPLY_LIMIT * q] shl 2 * q } companion object { private val best = intArrayOf( 0, 1, 2, 3, 4, 5, 6, 9, 12, 16, 20, 27, 36, 48, 64, 81, ) private const val MAX = 15 private const val N_MAX = 11 private const val MULTIPLY_LIMIT = 5 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,712
kotlab
Apache License 2.0
src/Day04.kt
proggler23
573,129,757
false
{"Kotlin": 27990}
fun main() { fun part1(input: List<String>): Int { return input.parse4().count { (elf1, elf2) -> (elf1.first in elf2 && elf1.last in elf2) || (elf2.first in elf1 && elf2.last in elf1) } } fun part2(input: List<String>): Int { return input.parse4().count { (elf1, elf2) -> (elf1.first in elf2 || elf1.last in elf2) || (elf2.first in elf1 || elf2.last in elf1) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) } fun List<String>.parse4() = map { line -> line.split(',').map { range -> range.split('-') .map { it.toInt() } .let { (from, to) -> from..to } } }
0
Kotlin
0
0
584fa4d73f8589bc17ef56c8e1864d64a23483c8
896
advent-of-code-2022
Apache License 2.0
src/day15/Day15.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day15 import readInput import java.lang.Math.abs import java.util.regex.Pattern data class Point(var x: Int, var y: Int) { fun manhattanDistance(other: Point): Int { return abs(x-other.x) + abs(y-other.y) } } enum class FieldReading { SENSOR, BEACON, KNOWN_EMPTY } class SensorField(input: List<String>, focusRow: Int) { var field = mutableMapOf<Point, FieldReading>() init { for (reading in input) { var sensorLocation = Point(0, 0) var beaconLocation = Point(0, 0) if (parseSensorReading(reading, sensorLocation, beaconLocation)) { // Assume beacons & sensors cannot be in the same location check(!field.containsKey(sensorLocation) || field[sensorLocation] == FieldReading.KNOWN_EMPTY) check(!field.containsKey(beaconLocation) || field[beaconLocation] != FieldReading.SENSOR) field[sensorLocation] = FieldReading.SENSOR field[beaconLocation] = FieldReading.BEACON val range = sensorLocation.manhattanDistance(beaconLocation) for (x in IntRange(-range, range)) { val testPoint = Point(sensorLocation.x + x, focusRow) val distance = testPoint.manhattanDistance(sensorLocation) if (!field.containsKey(testPoint) && distance <= range) { field[testPoint] = FieldReading.KNOWN_EMPTY } } } } } } fun parseInput(input: List<String>, readings: MutableList<Pair<Point, Point>>) { for (reading in input) { var sensorLocation = Point(0, 0) var beaconLocation = Point(0, 0) if (parseSensorReading(reading, sensorLocation, beaconLocation)) { readings.add(Pair(sensorLocation, beaconLocation)) } } } class Sensor(p: Point, d: Int) { val sensor = p.copy() val distance = d fun isInside(p: Point): Boolean = sensor.manhattanDistance(p) <= distance } class BoundingSensorField(readings: List<Pair<Point, Point>>) { var sensorBounds = mutableListOf<Sensor>() init { for (reading in readings) { val sensor = reading.first val beacon = reading.second val distance = sensor.manhattanDistance(beacon) sensorBounds.add(Sensor(sensor, distance)) } } fun findOutside(x: Int, limit: Int): Int { var testPoint = Point(x, 0) var found = true while (testPoint.y <= limit && found) { found = false for (b in sensorBounds) { if (b.isInside(testPoint)) { testPoint.y = b.sensor.y + b.distance - abs(b.sensor.x - testPoint.x) + 1 found = true break } } } return testPoint.y } } fun parseSensorReading(reading: String, sensorLocation: Point, beaconLocation: Point): Boolean { val pattern = Pattern.compile("""Sensor at x=(\-?\d+), y=(\-?\d+): closest beacon is at x=(\-?\d+), y=(\-?\d+)""") val matcher = pattern.matcher(reading) val matchFound = matcher.find() if (matchFound) { sensorLocation.x = matcher.group(1).toInt() sensorLocation.y = matcher.group(2).toInt() beaconLocation.x = matcher.group(3).toInt() beaconLocation.y = matcher.group(4).toInt() } return matchFound } fun main() { fun part1(input: List<String>, focusRow: Int): Int { var field = SensorField(input, focusRow) val count = field.field.count{ (k, v) -> k.y == focusRow && v != FieldReading.BEACON } return count } fun part2(input: List<String>, limit: Int): Long { var tuningFrequency = 0.toLong() var readings = mutableListOf<Pair<Point, Point>>() parseInput(input, readings) var field = BoundingSensorField(readings) var beaconLocation = Point(-1, -1) for (x in IntRange(0, limit)) { beaconLocation.x = x beaconLocation.y = field.findOutside(x, limit) if (beaconLocation.y <= limit) { println("Found beacon location: ${beaconLocation.x}, ${beaconLocation.y}") tuningFrequency = beaconLocation.x.toLong() * 4000000 + beaconLocation.y.toLong() break } } println("Tuning frequency: $tuningFrequency") return tuningFrequency } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011.toLong()) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
4,749
AdventOfCode2022
Apache License 2.0
src/main/kotlin/Day04.kt
ripla
573,901,460
false
{"Kotlin": 19599}
object Day4 { private fun stringToIntRange(stringRange: String): IntRange = stringRange .split("-") .toPair() .map { it.toInt() } .toIntRange() private fun containsOther(elfPair: Pair<IntRange, IntRange>): Boolean = elfPair.first.all(elfPair.second::contains) || elfPair.second.all(elfPair.first::contains) private fun rangesOverlap(elfPair: Pair<IntRange, IntRange>): Boolean = elfPair.first.intersect(elfPair.second).isNotEmpty() fun part1(input: List<String>): Int { return input.map { it.split(",").toPair() } .map { it.map(::stringToIntRange) } .map(::containsOther) .count { it } } fun part2(input: List<String>): Int { return input.map { it.split(",").toPair() } .map { it.map(::stringToIntRange) } .map(::rangesOverlap) .count { it } } }
0
Kotlin
0
0
e5e6c0bc7a9c6eaee1a69abca051601ccd0257c8
939
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2021/Day11.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 11 - Dumbo Octopus * Problem Description: http://adventofcode.com/2021/day/11 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day11/ */ package com.ginsberg.advent2021 typealias OctopusCave = Map<Point2d, Int> class Day11(input: List<String>) { private val startingCave: OctopusCave = parseInput(input) fun solvePart1(): Int = startingCave.steps().take(100).sum() fun solvePart2(): Int = startingCave.steps().indexOfFirst { it == startingCave.size } + 1 private fun OctopusCave.steps(): Sequence<Int> = sequence { val cave = this@steps.toMutableMap() while (true) { cave.forEach { (point, energy) -> cave[point] = energy + 1 } do { val flashersThisRound = cave.filterValues { it > 9 }.keys flashersThisRound.forEach { cave[it] = 0 } flashersThisRound .flatMap { it.allNeighbors() } .filter { it in cave && cave[it] != 0 } .forEach { cave[it] = cave.getValue(it) + 1 } } while (flashersThisRound.isNotEmpty()) yield(cave.count { it.value == 0 }) } } private fun parseInput(input: List<String>): OctopusCave = input.flatMapIndexed { y, row -> row.mapIndexed { x, energy -> Point2d(x, y) to energy.digitToInt() } }.toMap() }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
1,490
advent-2021-kotlin
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day07.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2016 import se.saidaspen.aoc.util.* fun main() = Day07.run() object Day07 : Day(2016, 7) { override fun part1() = input.lines().count { supportsTls(it) } override fun part2() = input.lines().count { supportSsl(it) } private fun supportSsl(s: String): Boolean { val candidates = superString(s).windowed(3).filter { it[0] == it[2] && it[0] != it[1] } val needles = candidates.map { "" + it[1] + it[0] + it[1] } return subStrings(s).any { subStr -> needles.any { subStr.contains(it) } } } private fun superString(s: String) = """\[[a-z]+]""".toRegex().replace(s, ",").split(",").joinToString("") private fun supportsTls(s: String) : Boolean { val subStringWAbba = subStrings(s).any { isAbba(it) != null } return !subStringWAbba && """\[[a-z]+]""".toRegex().replace(s, ",").split(",").map { isAbba(it) != null } .any { it } } private fun isAbba(s: String) = s.windowed(4).firstOrNull { it[0] != it[1] && it.take(2) == it.takeLast(2).reversed() } private fun subStrings(s: String) = """\[[a-z]+]""".toRegex().findAll(s).map { it.value }.map { it.drop(1).dropLast(1) }.toList() }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,201
adventofkotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/FullBloomFlowers.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import java.util.TreeMap /** * 2251. Number of Flowers in Full Bloom * @see <a href="https://leetcode.com/problems/number-of-flowers-in-full-bloom">Source</a> */ interface FullBloomFlowers { operator fun invoke(flowers: Array<IntArray>, people: IntArray): IntArray } /** * Approach 1: Heap/Priority Queue */ class FullBloomFlowersPQ : FullBloomFlowers { override fun invoke(flowers: Array<IntArray>, people: IntArray): IntArray { val sortedPeople = people.copyOf() sortedPeople.sort() val sortedFlowers = flowers.sortedWith(compareBy({ it[0] }, { it[1] })) val dic = mutableMapOf<Int, Int>() val heap = PriorityQueue<Int>() var i = 0 for (person in sortedPeople) { while (i < sortedFlowers.size && sortedFlowers[i][0] <= person) { heap.add(sortedFlowers[i][1]) i++ } while (heap.isNotEmpty() && heap.peek() < person) { heap.poll() } dic[person] = heap.size } val ans = IntArray(people.size) for (j in people.indices) { ans[j] = dic[people[j]] ?: 0 } return ans } } /** * Approach 2: Difference Array + Binary Search */ class FullBloomFlowersBS : FullBloomFlowers { override fun invoke(flowers: Array<IntArray>, people: IntArray): IntArray { val difference = TreeMap<Int, Int>() difference[0] = 0 for (flower in flowers) { val start = flower[0] val end = flower[1] + 1 difference[start] = difference.getOrDefault(start, 0) + 1 difference[end] = difference.getOrDefault(end, 0) - 1 } val positions: MutableList<Int> = ArrayList() val prefix: MutableList<Int> = ArrayList() var curr = 0 for (key in difference.keys) { positions.add(key) curr += difference[key]!! prefix.add(curr) } val ans = IntArray(people.size) for (j in people.indices) { val i = binarySearch(positions, people[j]) - 1 ans[j] = prefix[i] } return ans } } /** * Approach 3: Simpler Binary Search */ class FullBloomFlowersSimplerBS : FullBloomFlowers { override fun invoke(flowers: Array<IntArray>, people: IntArray): IntArray { val starts: MutableList<Int> = ArrayList() val ends: MutableList<Int> = ArrayList() for (flower in flowers) { starts.add(flower[0]) ends.add(flower[1] + 1) } starts.sort() ends.sort() val ans = IntArray(people.size) for (index in people.indices) { val person = people[index] val i: Int = binarySearch(starts, person) val j: Int = binarySearch(ends, person) ans[index] = i - j } return ans } } private fun binarySearch(arr: List<Int>, target: Int): Int { var left = 0 var right = arr.size while (left < right) { val mid = (left + right) / 2 if (target < arr[mid]) { right = mid } else { left = mid + 1 } } return left }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,899
kotlab
Apache License 2.0
src/main/kotlin/io/queue/BasicCalculatorII.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.queue import io.utils.runTests import java.util.* // https://leetcode.com/problems/basic-calculator-ii/ class BasicCalculatorII { // inspired by https://leetcode.com/problems/basic-calculator-ii/discuss/63003/Share-my-java-solution fun execute(input: String): Int { var sign = '+' var num = 0 val stack = LinkedList<Int>() input.forEachIndexed { index, char -> if (char.isDigit()) num = num * 10 + (char - '0') if (!char.isDigit() && char != ' ' || index == input.lastIndex) { when (sign) { '+' -> stack.push(num) '-' -> stack.push(-num) '*' -> stack.push(stack.pop() * num) '/' -> stack.push(stack.pop() / num) } sign = char num = 0 } } return stack.fold(0) { acc, value -> acc + value } } fun execute1(i: String): Int { val input = i.replace(" ", "") val map = mutableMapOf<Int, Pair<Int, Int>>() var index = 0 var lastValue = 0 var lastIndexMap: Int? = null var lastValueIndex = 0 while (index < input.length) { val char = input[index] when { char.isDigit() -> { lastValueIndex = index val (newLast, nextIndex) = readInteger(input, index) index = nextIndex lastValue = newLast lastIndexMap = null } char == '+' || char == '-' -> { index++ lastIndexMap = null } char == '*' -> { val (value, nextIndex) = readInteger(input, index + 1) lastValue *= value map[lastIndexMap ?: lastValueIndex] = lastValue to nextIndex index = nextIndex } char == '/' -> { val (value, nextIndex) = readInteger(input, index + 1) lastValue /= value map[lastIndexMap ?: lastValueIndex] = lastValue to nextIndex index = nextIndex } } } index = 0 var result = 0 while (index < input.length) { val char = input[index] when { map.containsKey(index) -> { val (value, newIndex) = map.getValue(index) result += value index = newIndex } char.isDigit() -> { val (value, nextIndex) = readInteger(input, index) index = nextIndex result += value } char == '+' -> { val (value, newIndex) = if (map.containsKey(index + 1)) map.getValue(index + 1) else readInteger(input, index + 1) result += value index = newIndex } char == '-' -> { val (value, newIndex) = if (map.containsKey(index + 1)) map.getValue(index + 1) else readInteger(input, index + 1) result -= value index = newIndex } } } return result } private fun readInteger(input: String, index: Int): Pair<Int, Int> { var current = index var result = 0 while (current < input.length && input[current].isDigit()) { result = 10 * result + (input[current] - '0') current++ } return result to current } } fun main() { runTests(listOf( "3+2*2" to 7, "3/2 " to 1, " 3+5 / 2 " to 5 )) { (input, value) -> value to BasicCalculatorII().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
3,248
coding
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2022/day16/day16.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day16 import biz.koziolek.adventofcode.* import java.util.Comparator import java.util.PriorityQueue import java.util.Queue fun main() { val inputFile = findInput(object {}) val valvesGraph = parseValvesGraph(inputFile.bufferedReader().readLines()) val timeLimit = 30 val bestPath = findBestPath(valvesGraph, timeLimit) val potentialPressure = bestPath.potentialPressure(timeLimit - bestPath.time) println("Best path is: $bestPath with total pressure released: $potentialPressure") } const val TIME_PER_DISTANCE = 1 const val TIME_TO_OPEN = 1 data class Valve( override val id: String, val flowRate: Int ) : GraphNode { override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float) = id } fun parseValvesGraph(lines: List<String>): Graph<Valve, UniDirectionalGraphEdge<Valve>> = buildGraph { val regex = Regex("Valve ([a-zA-Z0-9]+) has flow rate=([0-9]+); tunnels? leads? to valves? (.*)$") val valves = lines .mapNotNull { regex.find(it) } .map { Valve( id = it.groups[1]!!.value, flowRate = it.groups[2]!!.value.toInt(), ) } .associateBy { it.id } lines .mapNotNull { regex.find(it) } .flatMap { result -> val currentId = result.groups[1]!!.value val currentValve = valves[currentId] ?: throw IllegalStateException("Valve '$currentId' not found") val neighbors = result.groups[3]!!.value.split(',') .map { it.trim() } .map { valves[it] ?: throw IllegalStateException("Valve '$it' not found") } neighbors.map { UniDirectionalGraphEdge(currentValve, it) } } .forEach { add(it) } } fun buildDistanceMatrix(valvesGraph: Graph<Valve, UniDirectionalGraphEdge<Valve>>): Map<Valve, Map<Valve, Int>> = valvesGraph.nodes.associateWith { srcValve -> valvesGraph.nodes.associateWith { dstValve -> valvesGraph.findShortestPath(srcValve, dstValve).size - 1 } } fun findBestPath(valvesGraph: Graph<Valve, UniDirectionalGraphEdge<Valve>>, timeLimit: Int): ValvePath = generatePaths(valvesGraph, timeLimit) .maxByOrNull { it.potentialPressure(timeLimit - it.time) }!! fun generatePaths(valvesGraph: Graph<Valve, UniDirectionalGraphEdge<Valve>>, timeLimit: Int): Sequence<ValvePath> = sequence { // val distanceMatrix = buildDistanceMatrix(valvesGraph) val toCheck: Queue<Pair<ValvePath, Int>> = PriorityQueue( Comparator.comparing { (path, timeLeft) -> -path.potentialPressure(timeLeft) } ) toCheck.add( Pair( ValvePath( valvesGraph.nodes.single { it.id == "AA" }, open = false ), timeLimit, ) ) while (toCheck.isNotEmpty()) { // println("--------------------------------------------------------------------------------") val (currentPath, timeLeft) = toCheck.poll() if (timeLeft <= 0) { yield(currentPath) continue } val srcValve = currentPath.lastValve // val currentPotentialPressure = currentPath.potentialPressure(timeLeft) // println("Time left: $timeLeft") // println("Current: $currentPath (${currentPath.releasedPressure}/$currentPotentialPressure)") val unopenedValves = valvesGraph.nodes .filter { dstValve -> dstValve.flowRate > 0 && !currentPath.isOpened(dstValve) } if (unopenedValves.isEmpty()) { yield(currentPath) continue } val newPaths = unopenedValves.flatMap { dstValve -> val newPathFragment = valvesGraph.findShortestPath(srcValve, dstValve) // val distance = distanceMatrix[srcValve]!![dstValve]!! val distance = newPathFragment.size - 1 val newTimeLeft = timeLeft - distance * TIME_PER_DISTANCE - TIME_TO_OPEN // val newPotentialPressure = dstValve.flowRate * newTimeLeft // println(" ${dstValve.id}: potential pressure: $currentPotentialPressure + $newPotentialPressure") if (newTimeLeft > 0) { listOf( Pair( newPathFragment.drop(1).fold(currentPath) { newPath, valve -> newPath.addValve(valve, open = valve == dstValve) }, newTimeLeft, ) ) } else { emptyList() } } if (newPaths.isNotEmpty()) { toCheck.addAll(newPaths) } else { yield(currentPath) } } } data class ValvePath( private val path: List<Pair<Valve, Boolean>> ) { constructor(valve: Valve, open: Boolean) : this(listOf(valve to open)) val time = path.fold(-1) { time, (_, open) -> time + TIME_PER_DISTANCE + if (open) TIME_TO_OPEN else 0 } val lastValve = path.last().first val releasedPressure: Int get() { val (released, _) = calculatePressure() return released } fun potentialPressure(timeLeft: Int): Int { val (released, lastTotalFlowRate) = calculatePressure() return released + lastTotalFlowRate * timeLeft } private fun calculatePressure() = path.fold(0 to 0) { (totalPressure, flowRate), (valve, open) -> when { open -> Pair( totalPressure + flowRate * (TIME_PER_DISTANCE + TIME_TO_OPEN), flowRate + valve.flowRate ) else -> Pair( totalPressure + flowRate * TIME_PER_DISTANCE, flowRate ) } } fun isOpened(valve: Valve) = path.any { it.first == valve && it.second } fun addValve(valve: Valve, open: Boolean) = if (open && isOpened(valve)) { throw IllegalStateException("Valve ${valve.id} is already opened") } else if (open && valve.flowRate == 0) { throw IllegalArgumentException("Valve ${valve.id} is zero flow rate - why would you waste time opening it?!") } else { copy(path = path + (valve to open)) } override fun toString() = path.joinToString("->") { (valve, open) -> if (open) { "(${valve.id})" } else { valve.id } } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
6,898
advent-of-code
MIT License
src/day15.kt
skuhtic
572,645,300
false
{"Kotlin": 36109}
import kotlin.math.abs fun main() { day15.execute(onlyTests = false, forceBothParts = false) } val day15 = object : Day<Long>(15, 26, 56000011) { override val testInput: InputData get() = """ Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3 """.trimIndent().lines() override fun part1(input: InputData): Long { val parsed = parsedInput(input) val sensors = parsed.map { (s, b) -> s to abs(s.first - b.first) + abs(s.second - b.second) } val onLine = if (sensors.maxOf { it.first.second } < 50) 10 else 2_000_000 val beacons = parsed.filter { it.second.second == onLine }.map { it.second.first }.toSet() val line = sensors.asSequence().flatMap { (s, d) -> val dy = abs(s.second - onLine) val dx = d - dy ((s.first - dx)..(s.first + dx)).toList() }.toSet() return (line - beacons).count().toLong() } override fun part2(input: InputData): Long { val parsed = parsedInput(input) val sensors = parsed.map { (s, b) -> s to abs(s.first - b.first) + abs(s.second - b.second) } val range = if (sensors.maxOf { it.first.second } < 50) 0..20 else 0..4_000_000 for (x in range) { // x.logIt("XXX") var y = 0 do { if (!sensors.any { (s, sd) -> abs(s.first - x) + abs(s.second - y) <= sd }) { return x * 4_000_000L + y } val md = sensors.minOf { (s, sd) -> abs(s.first - x) + abs(s.second - y) - sd } // md.logIt() val dx = if (md == 0) 1 else if (md < 0) -md else error("$x, $y") y += dx } while (y in range) } return 1 } fun parsedInput(input: InputData) = input.map { line -> line.split(':').let { (s, b) -> s.split(',').let { (sx, sy) -> sx.substringAfterLast('=').toInt() to sy.substringAfterLast('=').toInt() } to b.split(',').let { (bx, by) -> bx.substringAfterLast('=').toInt() to by.substringAfterLast('=').toInt() } } } }
0
Kotlin
0
0
8de2933df90259cf53c9cb190624d1fb18566868
3,057
aoc-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2018/Day12.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 12 - Subterranean Sustainability * * Problem Description: http://adventofcode.com/2018/day/12 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day12/ */ package com.ginsberg.advent2018 class Day12(rawInput: List<String>) { private val rules: Set<String> = parseRules(rawInput) private val initialState: String = rawInput.first().substring(15) fun solvePart1(): Long = mutatePlants().drop(19).first().second fun solvePart2(targetGeneration: Long = 50_000_000_000): Long { var previousDiff = 0L var previousSize = 0L var generationNumber = 0 // Go through the sequence until we find one that grows the same one as its previous generation mutatePlants().dropWhile { thisGen -> val thisDiff = thisGen.second - previousSize // Our diff to last generation if (thisDiff != previousDiff) { // Still changing previousDiff = thisDiff previousSize = thisGen.second generationNumber += 1 true } else { // We've found it, stop dropping. false } }.first() // Consume first because sequences are lazy and it won't start otherwise. return previousSize + (previousDiff * (targetGeneration - generationNumber)) } private fun mutatePlants(state: String = initialState): Sequence<Pair<String, Long>> = sequence { var zeroIndex = 0 var currentState = state while (true) { // Make sure we have something to match to the left of our first real center point. while (!currentState.startsWith(".....")) { currentState = ".$currentState" zeroIndex++ } // Make sure we have something to match to the right of our last real center point. while (!currentState.endsWith(".....")) { currentState = "$currentState." } currentState = currentState .toList() .windowed(5, 1) .map { it.joinToString(separator = "") } .map { if (it in rules) '#' else '.' } .joinToString(separator = "") zeroIndex -= 2 // Because there are two positions to the left of the first real center and were not evaluated yield(Pair(currentState, currentState.sumIndexesFrom(zeroIndex))) } } private fun String.sumIndexesFrom(zero: Int): Long = this.mapIndexed { idx, c -> if (c == '#') idx.toLong() - zero else 0 }.sum() private fun parseRules(input: List<String>): Set<String> = input .drop(2) .filter { it.endsWith("#") } .map { it.take(5) } .toSet() }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
2,905
advent-2018-kotlin
MIT License
codeforces/round606/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round606 import kotlin.math.sqrt fun main() { readLn() val a = readInts() val groups = a.groupBy { it }.toList().sortedByDescending { it.second.size } val b = groups.map { it.second.size } var bSelf = b.size var bSum = 0 val (h, w) = (1..sqrt(a.size.toDouble()).toInt()).map { h -> while (bSelf > 0 && b[bSelf - 1] <= h) bSum += b[--bSelf] h to ((bSelf + bSum / h).takeIf { it >= h } ?: 0) }.maxByOrNull { it.first * it.second }!! println("${h * w}\n$h $w") val f = List(h) { IntArray(w) } var x = 0 for (group in groups) repeat(minOf(group.second.size, h)) { f[x % h][(x % h + x / h) % w] = group.first if (++x == h * w) return f.forEach { println(it.joinToString(" ")) } } } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
862
competitions
The Unlicense
src/day02/Day02.kt
pientaa
572,927,825
false
{"Kotlin": 19922}
package day02 import readLines fun main() { fun part1(input: List<String>): Int { fun Char.shapeScore() = this - 'X' + 1 fun outcome(round: String): Int = when (round) { "C X", "A Y", "B Z" -> 6 "A X", "B Y", "C Z" -> 3 "B X", "C Y", "A Z" -> 0 else -> throw Exception() } return input.sumOf { outcome(it) + it[2].shapeScore() } } fun part2(input: List<String>): Int { fun Char.outcome() = (this - 'X') * 3 fun shapeScore(round: String): Int = when (round) { "B X", "A Y", "C Z" -> 1 "C X", "B Y", "A Z" -> 2 "A X", "C Y", "B Z" -> 3 else -> throw Exception() } return input.sumOf { it[2].outcome() + shapeScore(it) } } // test if implementation meets criteria from the description, like: val testInput = readLines("day02/Day02_test") val input = readLines("day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
63094d8d1887d33b78e2dd73f917d46ca1cbaf9c
1,128
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
mattfrsn
573,195,420
false
{"Kotlin": 5703}
import java.io.File fun main() { val values = mapOf<String, Int>( "X" to 1, // pt1 Rock / 2 lose "Y" to 2, // pt1 Paper / 2 draw "Z" to 3 // pt1 Sissors / 2 win ) fun determineGameResult(theirs: String, mine: String): Int { return when(theirs.single() to mine.single()) { 'B' to 'X', 'C' to 'Y', 'A' to 'Z' -> 0 'B' to 'Y', 'C' to 'Z', 'A' to 'X' -> 3 'B' to 'Z', 'C' to 'X', 'A' to 'Y' -> 6 else -> error("Before you wreck yourself") } } fun determineGuess(game: List<String>): Char { val theirGuess = game[0].single() return when(game[1].single()) { 'X' -> // lose when(theirGuess){ 'B' -> 'X' 'C' -> 'Y' 'A' -> 'Z' else -> error("Check input") } 'Y' -> // draw when(theirGuess){ 'B' -> 'Y' 'C' -> 'Z' 'A' -> 'X' else -> error("Check input") } 'Z' -> // win when(theirGuess){ 'B' -> 'Z' 'C' -> 'X' 'A' -> 'Y' else -> error("Check input") } else -> error("Check your input") } } fun rockPaperSissors(input: List<String>, part: Int) { var score = 0 require(part in 1..2) { "part must be 1 or 2" } input.map { currentGame -> currentGame.split(" ").let { val myGuess = if(part == 1) it[1] else determineGuess(it).toString() val myScore = values[myGuess] ?: error("Check yourself") val gameScore = determineGameResult(it[0], myGuess) score += myScore + gameScore!! } } println(score) } val input = File("src/input.txt").readLines() rockPaperSissors(input, 1) rockPaperSissors(input, 2) }
0
Kotlin
0
0
f17941024c1a2bac1cea88c3d9f6b7ecb9fd67e4
2,078
kotlinAdvent2022
Apache License 2.0
src/main/kotlin/arrayandlist/medium/4Sum.kt
jiahaoliuliu
747,189,993
false
{"Kotlin": 97631}
package arrayandlist.medium import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test /** * Given an array nums of n integers, return an array of all the unique quadruplets * [nums[a], nums[b], nums[c], nums[d]] such that: * 0 <= a, b, c, d < n * a, b, c, and d are distinct. * nums[a] + nums[b] + nums[c] + nums[d] == target * You may return the answer in any order. * Example 1: * - Input: nums = [1,0,-1,0,-2,2], target = 0 * - Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] * * Example 2: * - Input: nums = [2,2,2,2,2], target = 8 * - Output: [[2,2,2,2]] */ class `4Sum` { /** * Solution based on CodeCryptic * https://www.youtube.com/watch?v=vBfqUNPAx30 */ private fun solution(nums: IntArray, target: Int): List<List<Int>> { val sortedList = nums.sorted().map { it.toLong() } val result = mutableListOf<List<Long>>() for (a in sortedList.indices) { // To avoid to put the same element in the list if (a > 0 && sortedList[a] == sortedList[a - 1]) continue for (b in a+1 until sortedList.size) { // To avoid the duplication of b if (b > a + 1 && sortedList[b] == sortedList[b - 1]) continue var c = b + 1 var d = sortedList.size - 1 while (c < d) { val quad = listOf(sortedList[a], sortedList[b], sortedList[c], sortedList[d]) val quadSum:Long = quad.sum() if (quadSum > target) d-- else if (quadSum < target) c++ else { // The quad sum is the target. We found the result result.add(quad) while (c < d && sortedList[c] == quad[2]) c++ while (c < d && sortedList[d] == quad[3]) d-- } } } } return result.map { longList -> longList.map { long -> long.toInt()}} } @Test fun test1() { // Given val input = intArrayOf(1, 0, -1, 0, -2, 2) val target = 0 // When val result = solution(input, target) // Then assertEquals(3, result.size) assertTrue(result.contains(listOf(-2, -1, 1, 2))) assertTrue(result.contains(listOf(-2, 0, 0, 2))) assertTrue(result.contains(listOf(-1, 0, 0, 1))) } @Test fun test2() { // Given val input = intArrayOf(2, 2, 2, 2, 2) val target = 8 // When val result = solution(input, target) // Then assertTrue(listOf(listOf(2, 2, 2, 2)) == result) } @Test fun test3() { // Given val input = intArrayOf(1_000_000_000,1_000_000_000,1_000_000_000,1_000_000_000) val target = -294967296 // When val result = solution(input, target) // Then assertTrue(emptyList<Int>() == result) } }
0
Kotlin
0
0
c5ed998111b2a44d082fc6e6470d197554c0e7c9
3,009
CodingExercises
Apache License 2.0
src/main/kotlin/day13/Day13.kt
afTrolle
572,960,379
false
{"Kotlin": 33530}
package day13 import Day import kotlin.math.max fun main() { Day13("Day13").solve() } class ValueOrList( val parent: ValueOrList? = null, val list: MutableList<ValueOrList>? = null, val value: Int? = null ) { val isValue = value != null } class Day13(input: String) : Day<List<Pair<ValueOrList, ValueOrList>>>(input) { override fun parseInput(): List<Pair<ValueOrList, ValueOrList>> { return inputByGroups.map { (left, right) -> parseToValueOrList(left) to parseToValueOrList(right) } } private fun parseToValueOrList(left: String): ValueOrList { val root = ValueOrList(list = mutableListOf()) var current = root "(\\d+)|(\\[)|(\\])".toRegex().findAll(left).toList().drop(1).dropLast(1).forEach { match -> val c = match.value val maybeInt = c.toIntOrNull() when { maybeInt != null -> { current.list!!.add(ValueOrList(parent = current, value = maybeInt)) } c == "[" -> { val prev = current current = ValueOrList(parent = prev, list = mutableListOf()) prev.list?.add(current) } c == "]" -> { current = current.parent!! } } } return root } private fun isInRightOrder(left: ValueOrList, right: ValueOrList): Boolean? { return if (left.isValue && right.isValue) { val leftV = left.value!! val rightV = right.value!! return if (leftV == rightV) { null } else { leftV < rightV } } else if (left.isValue && !right.isValue) { // mixed val leftList = ValueOrList(parent = left, mutableListOf(left)) isInRightOrder(leftList, right) } else if (!left.isValue && right.isValue) { // mixed val rightList = ValueOrList(parent = right, mutableListOf(right)) isInRightOrder(left, rightList) } else { // both lists val size = max(left.list!!.size, right.list!!.size) if (left.list.isEmpty() && right.list.isNotEmpty()) { return true } else if (left.list.isNotEmpty() && right.list.isEmpty()) { return false } else { for (x in 0 until size) { val leftV = left.list.getOrNull(x) val rightV = right.list.getOrNull(x) if (leftV != null && rightV != null) { val result = isInRightOrder(leftV, rightV) if (result != null) { return result } } else if (leftV == null && rightV != null) { // mixed return true } else if (leftV != null && rightV == null) { // mixed return false } else { // both null return null } } } return null } } override fun part1(input: List<Pair<ValueOrList, ValueOrList>>): Any? { return input.mapIndexedNotNull { index, (left, right) -> val at = isInRightOrder(left, right)!! if (at) index + 1 else null }.sum() } override fun part2(input: List<Pair<ValueOrList, ValueOrList>>): Any? { val two = ValueOrList(list = mutableListOf()).also { it.list!!.add(ValueOrList(parent = it, value = 2)) } val six = ValueOrList(list = mutableListOf()).also { it.list!!.add(ValueOrList(parent = it, value = 6)) } val list = input.map { (left, right) -> listOf(left, right) }.flatten().plus(two).plus(six).sortedWith { o1, o2 -> if (isInRightOrder(o1!!, o2!!)!!) { 1 } else { -1 } } return list.indexOf(six) * list.indexOf(two) } }
0
Kotlin
0
0
4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545
4,245
aoc-2022
Apache License 2.0
src/vectors.ws.kts
exerro
191,953,002
false
null
sealed class Dimensions { object Zero: Dimensions() class Inc<D: Dimensions>(): Dimensions() } typealias One = Dimensions.Inc<Dimensions.Zero> typealias Two = Dimensions.Inc<One> typealias Three = Dimensions.Inc<Two> typealias Four = Dimensions.Inc<Three> sealed class FList<D: Dimensions> { object Empty: FList<Dimensions.Zero>() class Cons<D: Dimensions>(val v: Float, val l: FList<D>): FList<Dimensions.Inc<D>>() fun components(): List<Float> = when (this) { is Empty -> listOf() is Cons<*> -> listOf(v) + l.components() } fun map(other: FList<D>, fn: (Float, Float) -> Float): FList<D> = when (this) { is Empty -> this is Cons<*> -> Cons(fn(v, (other as Cons<*>).v), (l as FList<D>).map((other as Cons<D>).l, fn)) as FList<D> } } class Vector<D: Dimensions>(val fl: FList<D>) { operator fun plus(v: Vector<D>): Vector<D> = Vector(fl.map(v.fl) { a, b -> a + b }) } typealias vec2 = Vector<Two> typealias vec3 = Vector<Three> typealias vec4 = Vector<Four> fun <D: Dimensions> Vector<D>.introduce(n: Float): Vector<Dimensions.Inc<D>> = TODO() fun <D: Dimensions> Vector<Dimensions.Inc<D>>.reduce(): Vector<D> = TODO() fun vec2(x: Float, y: Float) = vec2(FList.Cons(x, FList.Cons(y, FList.Empty))) fun vec3(x: Float, y: Float, z: Float) = vec3(FList.Cons(x, FList.Cons(y, FList.Cons(z, FList.Empty)))) fun vec4(x: Float, y: Float, z: Float, w: Float) = vec4(FList.Cons(x, FList.Cons(y, FList.Cons(z, FList.Cons(z, FList.Empty))))) fun <D: Dimensions> Vector<D>.dot(v: Vector<D>): Float = fl.components().zip(v.fl.components()) { a, b -> a * b } .sum() val a: vec2 = vec2(1f, 2f) val b: vec2 = vec2(2f, 3f) val c: vec2 = a + b val d: vec3 = c.introduce(5f) val e: vec2 = d.reduce() val f: vec4 = a.introduce(2f).introduce(5f) val g: vec2 = f.reduce().reduce()
8
Kotlin
0
0
3210f450651e68430d2442dc184253c0b5c40da2
1,874
ktaf
MIT License
src/main/kotlin/com/jacobhyphenated/advent2022/day18/Day18.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day18 import com.jacobhyphenated.advent2022.Day import kotlin.math.absoluteValue /** * Day 18: Boiling Boulders * * We can observe lava being shot into the air by the volcano. * Each unit of lava is represented by a 1x1x1 cube in 3d space by the puzzle input. * How the lava cools into stone is effected by how much surface area is exposed, * with adjacent cubes of lava sticking together. */ class Day18: Day<List<Cube>> { override fun getInput(): List<Cube> { return readInputFile("day18").lines().map { line -> val (x,y,z) = line.trim().split(",").map { it.toInt() } Cube(x, y, z) } } override fun warmup(input: List<Cube>): Any { return computeAdjacentCubes(input).size } /** * Count all the sides not connected to another cube. What is the surface area? */ override fun part1(input: List<Cube>): Int { val cubes = computeAdjacentCubes(input) return cubes.sumOf { it.freeSides } } /** * Steam moves over the structure, but not diagonally. * Some internal sides of the lava cubes are never exposed to the water/steam. * What is only teh exterior surface of the lava cube structure? */ override fun part2(input: List<Cube>): Int { // We use the value from part1 in this calculation val surfaceArea = part1(input) val allCubes = input.toSet() var interiorSpace = 0 // find all cubes that are adjacent to a known lava cube // note: there will be duplicates. We want to count an open space multiple times, // based on the number of adjacent lava cubes to the open space val allSides = allCubes.flatMap {(x,y,z) -> listOf( Cube(x + 1, y, z), Cube(x - 1, y, z), Cube(x, y + 1, z), Cube(x, y - 1, z), Cube(x, y, z + 1), Cube(x, y, z - 1) ) } for ((x,y,z) in allSides){ if (Cube(x,y,z) in allCubes) { continue } // for each empty space cube, see if there is an unblocked path to the exterior // we know from the input that our structure is limited to [0,19] in all 3 axis val pathways = listOf((x downTo 0).map { Cube(it,y,z) }, (x + 1 .. 20).map { Cube(it, y, z) }, (y downTo 0).map { Cube(x, it, z) }, (y + 1 .. 20).map { Cube(x, it, z) }, (z downTo 0).map { Cube(x, y, it) }, (z + 1 .. 20).map { Cube(x, y, it) }) if (pathways.all { path -> path.any { it in allCubes } }) { interiorSpace++ } } // Return the total surface area subtracting each interior side that has no external exposure return surfaceArea - interiorSpace } /** * Cubes share a side if 2/3 coordinates are the same and the third is +- 1 apart. * Track what cubes are adjacent (share a side). */ private fun computeAdjacentCubes(input: List<Cube>): List<Cube> { val cubes = input.map { it.copy() } for (cube in 0 until cubes.size -1) { for (other in cube + 1 until cubes.size) { val (x1, y1, z1) = cubes[cube] val (x2, y2, z2) = cubes[other] if ((x1 == x2 && y1 == y2 && (z1 - z2).absoluteValue == 1) || (y1 == y2 && z1 == z2 && (x1 - x2).absoluteValue == 1) || (x1 == x2 && z1 == z2 && (y1 - y2).absoluteValue == 1) ){ cubes[cube].adjacent.add(cubes[other]) cubes[other].adjacent.add(cubes[cube]) } } } return cubes } } data class Cube(val x: Int, val y: Int, val z: Int) { val adjacent: MutableList<Cube> = mutableListOf() // The surface area for each cube is 6 - the number of adjacent cubes. val freeSides: Int get() = 6 - adjacent.size }
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
4,099
advent2022
The Unlicense
src/day23/Day23.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day23 import lib.Point2D import lib.Vector2D import readInput fun main() { val day = 23 val testInput = readInput("day$day/testInput") // check(part1(testInput) == 110) // check(part2(testInput) == 20) val input = readInput("day$day/input") // println(part1(input)) println(part2(input)) } val N = Vector2D(0, -1) val NE = Vector2D(1, -1) val NW = Vector2D(-1, -1) val S = Vector2D(0, 1) val SE = Vector2D(1, 1) val SW = Vector2D(-1, 1) val W = Vector2D(-1, 0) val E = Vector2D(1, 0) val allDirections = listOf(E, SE, S, SW, W, NW, N, NE) val moveDirections = listOf(N, S, W, E) val checkDirectionsMap = mapOf( N to listOf(N, NE, NW), S to listOf(S, SE, SW), W to listOf(W, NW, SW), E to listOf(E, NE, SE), ) sealed class GroovyObject object Empty : GroovyObject() data class Elve(var position: Point2D) : GroovyObject() { var firstDirectionIndex: Int = 0 fun proposedDirections() = (0..3).map { it -> val i = (firstDirectionIndex + it) % 4 moveDirections[i] } fun getCheckDirections(direction: Vector2D) = checkDirectionsMap[direction]!! // if isAlone - it is surrounded by empty objects var isAlone = false var proposedNewPosition: Point2D? = null } fun part1(input: List<String>): Int { val initialHeight = input.size val initialWidth = input[0].length // from left and right val additionalX = 10 // from top and bottom val additionalY = 10 val elves = mutableListOf<Elve>() val width = additionalX + initialWidth + additionalX val height = additionalY + initialHeight + additionalY val field = MutableList(height) { y -> MutableList(width) { x -> if (x in (additionalX until (additionalX + initialWidth)) && y in (additionalY until (additionalY + initialHeight))) { val inicialX = x - additionalX val inicialY = y - additionalY val char = input[inicialY][inicialX] if (char == '#') { Elve(Point2D(x, y)).apply { elves.add(this) } } else { Empty } } else { Empty } } } fun printField() { for (y in 0 until height) { for (x in 0 until width) { print(if (field[y][x] is Empty) "." else "#") } println() } } printField() repeat(10) { r -> // firstHalf elves.forEach { e -> e.isAlone = true // look up 8 directions for (d in allDirections) { val lookUpPoint = e.position + d if (field[lookUpPoint.y][lookUpPoint.x] is Elve) { e.isAlone = false break } } println("Elve ${e.position} is alone?: ${e.isAlone}") // calculate proposed position if (!e.isAlone) { for (d in e.proposedDirections()) { val checkDirections = e.getCheckDirections(d) val isValidDirection = checkDirections.all { checkDir -> val checkPoint = e.position + checkDir field[checkPoint.y][checkPoint.x] !is Elve } if (isValidDirection) { e.proposedNewPosition = e.position + d println("Found direction for elve: ${e.position}, direction: $d") break } } } } // second half, trying to move val notAloneElves = elves.filter { !it.isAlone } val proposedPositions = notAloneElves.mapNotNull { it.proposedNewPosition } notAloneElves.forEach { e -> val newPosition = e.proposedNewPosition if (newPosition != null) { val otherPositions = proposedPositions - newPosition val isBlocked = otherPositions.contains(newPosition) println("Elve: ${e.position} isBlocked?: $isBlocked") if (!isBlocked) { // previous position becomes empty field[e.position.y][e.position.x] = Empty // updating position e.position = newPosition // also update field field[newPosition.y][newPosition.x] = e } } } elves.forEach { it.proposedNewPosition = null it.firstDirectionIndex++ } println() println("Round: ${r+1}") // printField() } // finding rectangle coordinates, which contains all elves val startX: Int = elves.minOf { it.position.x } val endX = elves.maxOf { it.position.x } val startY = elves.minOf { it.position.y } val endY = elves.maxOf { it.position.y } var countEmpty = 0 for (y in startY..endY) { for (x in startX..endX) { if (field[y][x] is Empty) { countEmpty++ } } } println("rectangle: startX: $startX, endX: $endX; startY: $startY, endY: $endY") println(countEmpty) return countEmpty } fun part2(input: List<String>): Int { val initialHeight = input.size val initialWidth = input[0].length // from left and right val additionalX = 1000 // from top and bottom val additionalY = 1000 val elves = mutableListOf<Elve>() val width = additionalX + initialWidth + additionalX val height = additionalY + initialHeight + additionalY val field = MutableList(height) { y -> MutableList(width) { x -> if (x in (additionalX until (additionalX + initialWidth)) && y in (additionalY until (additionalY + initialHeight))) { val inicialX = x - additionalX val inicialY = y - additionalY val char = input[inicialY][inicialX] if (char == '#') { Elve(Point2D(x, y)).apply { elves.add(this) } } else { Empty } } else { Empty } } } fun printField() { for (y in 0 until height) { for (x in 0 until width) { print(if (field[y][x] is Empty) "." else "#") } println() } } // printField() var round = 1 while(true) { // firstHalf elves.forEach { e -> e.isAlone = true // look up 8 directions for (d in allDirections) { val lookUpPoint = e.position + d if (field[lookUpPoint.y][lookUpPoint.x] is Elve) { e.isAlone = false break } } // println("Elve ${e.position} is alone?: ${e.isAlone}") // calculate proposed position if (!e.isAlone) { for (d in e.proposedDirections()) { val checkDirections = e.getCheckDirections(d) val isValidDirection = checkDirections.all { checkDir -> val checkPoint = e.position + checkDir field[checkPoint.y][checkPoint.x] !is Elve } if (isValidDirection) { e.proposedNewPosition = e.position + d // println("Found direction for elve: ${e.position}, direction: $d") break } } } } // second half, trying to move val notAloneElves = elves.filter { !it.isAlone } val proposedPositions = notAloneElves.mapNotNull { it.proposedNewPosition } notAloneElves.forEach { e -> val newPosition = e.proposedNewPosition if (newPosition != null) { val otherPositions = proposedPositions - newPosition val isBlocked = otherPositions.contains(newPosition) // println("Elve: ${e.position} isBlocked?: $isBlocked") if (!isBlocked) { // previous position becomes empty field[e.position.y][e.position.x] = Empty // updating position e.position = newPosition // also update field field[newPosition.y][newPosition.x] = e } } } elves.forEach { it.proposedNewPosition = null it.firstDirectionIndex++ } println() println("Round: $round, notAloneSize: ${notAloneElves.size}") if (notAloneElves.isEmpty()) { break } round++ } return round }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
9,036
advent-of-code-2022
Apache License 2.0
src/Day03.kt
devLeitner
572,272,654
false
{"Kotlin": 6301}
fun main(){ fun part1(){ var input = readInput("resources/day3source") var pairList = input.map { Pair(it.subSequence(0, it.length/2),it.subSequence(it.length/2, it.length)) } println(pairList) var totalScore = 0 pairList.forEachIndexed{index, pair -> pair.first.forEach{ if (pair.second.contains(it)) { println("$it with score(${it.code}) to ${calcScore(it)} at index $index") totalScore += calcScore(it) return@forEachIndexed } } } print(totalScore) } fun part2(){ print(readInput("resources/day3source") .chunked(3) .map { Triple(it[0].toCharArray(), it[1].toSet(), it[2].toSet()) }.sumOf { calcScore( it.first.intersect(it.second) .intersect(it.third) .first() ) }) } part2() // part1() } internal fun calcScore(x:Char) = if(x.code >= 97) x.code - 96 else x.code - 38
0
Kotlin
0
0
72b9d184fc58f790b393260fc6b1a0ed24028059
1,166
AOC_2022
Apache License 2.0
mynlp/src/main/java/com/mayabot/nlp/algorithm/TopIntMinK.kt
mayabot
113,726,044
false
{"Java": 985672, "Kotlin": 575923, "Shell": 530}
package com.mayabot.nlp.algorithm /** * Top K 最小值。 */ class TopIntMinK(private val k: Int) { private val heap = FloatArray(k) private val idIndex = IntArray(k) { -1 } var size = 0 fun push(id: Int, score: Float) { if (size < k) { heap[size] = score idIndex[size] = id size++ if (size == k) { buildMinHeap() } } else { // 如果这个数据小于最大值,那么有资格进入 if (score < heap[0]) { heap[0] = score idIndex[0] = id topify(0) } } } fun result(): ArrayList<Pair<Int, Float>> { val top = Math.min(k, size) val list = ArrayList<Pair<Int, Float>>(top) for (i in 0 until top) { list += idIndex[i] to heap[i] } list.sortBy { it.second } return list } private fun buildMinHeap() { for (i in k / 2 - 1 downTo 0) { topify(i)// 依次向上将当前子树最大堆化 } } private fun topify(i: Int) { val l = 2 * i + 1 val r = 2 * i + 2 var max: Int if (l < k && heap[l] > heap[i]) max = l else max = i if (r < k && heap[r] > heap[max]) { max = r } if (max == i || max >= k) // 如果largest等于i说明i是最大元素 // largest超出heap范围说明不存在比i节点大的子女 return swap(i, max) topify(max) } private fun swap(i: Int, j: Int) { val tmp = heap[i] heap[i] = heap[j] heap[j] = tmp val tmp2 = idIndex[i] idIndex[i] = idIndex[j] idIndex[j] = tmp2 } }
18
Java
90
658
b980da3a6f9cdcb83e0800f6cab50656df94a22a
1,822
mynlp
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/RotatedDigits.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.DECIMAL /** * Rotated Digits * @see <a href="https://leetcode.com/problems/rotated-digits/">Source</a> */ fun interface RotatedDigits { operator fun invoke(n: Int): Int } class RotatedDigitsBruteForce : RotatedDigits { override operator fun invoke(n: Int): Int { // Count how many n in [1, N] are good. var ans = 0 for (i in 1..n) if (good(i, false)) ans++ return ans } // Return true if n is good. // The flag is true iff we have an occurrence of 2, 5, 6, 9. private fun good(n: Int, flag: Boolean): Boolean { if (n == 0) return flag val d = n % DECIMAL if (invalidRotation.contains(d)) return false return if (validRotation.contains(d)) good(n / DECIMAL, flag) else good(n / DECIMAL, true) } companion object { private val invalidRotation = listOf(3, 4, 7) private val validRotation = listOf(0, 1, 8) } } class RotatedDigitsDP : RotatedDigits { override operator fun invoke(n: Int): Int { val a = n.toString().toCharArray() val k = a.size val memo = Array(k + 1) { Array(2) { IntArray(2) } } memo[k][0][1] = 1.also { memo[k][1][1] = it } for (i in k - 1 downTo 0) { for (eqf in 0..1) for (invf in 0..1) { var ans = 0 var d = '0' while (d <= if (eqf == 1) a[i] else '9') { if (d == '3' || d == '4' || d == '7') { ++d continue } val invo = d == '2' || d == '5' || d == '6' || d == '9' ans += memo[i + 1][if (d == a[i]) eqf else 0][if (invo) 1 else invf] ++d } memo[i][eqf][invf] = ans } } return memo[0][1][0] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,526
kotlab
Apache License 2.0
security/src/main/java/dev/funkymuse/security/RSA.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728251}
package dev.funkymuse.security import java.math.BigInteger import kotlin.random.Random /** * Two numbers are co-prime when the GCD of the numbers is 1. * This method uses an algorithm called the Euclidean algorithm to compute GCD. */ private fun areCoprime(first: Long, second: Long): Boolean { fun greatestCommonDivisor(first: Long, second: Long): Long { val smaller = if (first <= second) first else second val bigger = if (first > second) first else second return if (bigger % smaller == 0L) smaller else greatestCommonDivisor(smaller, bigger % smaller) } return greatestCommonDivisor(first, second) == 1L } /** * Generates a random prime number within range, using isPrime() function to check for primality. */ private fun generateRandomPrime(range: IntRange): Int { val count = range.count() var i = 0 var number: Int do { number = Random.nextInt(range.first, range.last) if (isPrime(number.toLong())) return number i++ if (i >= count) return -1 } while (true) } /** * This method returns true if the number is a prime number. * Simply, it checks all the numbers up to the numbers square root and returns false if the number is divisible by any, * otherwise returns true. */ private fun isPrime(num: Long): Boolean { // Negative integers can not be prime. 0 is also not a prime. if (num < 1) return false // Taking shortcuts - if a number is divisible without the remainder by small natural numbers, it is not a prime number. if (num > 10 && (num % 2 == 0L || num % 3 == 0L || num % 5 == 0L || num % 7 == 0L || num % 9 == 0L)) return false // If the number is belonging to small known prime numbers, return true. // Likewise, small known not-primes, return false. when (num) { in setOf<Long>(2, 3, 5, 7) -> return true in setOf<Long>(1, 4, 6, 8, 9) -> return false else -> { // Otherwise, take every number up to the numbers square root. // If none of those the number is divisible by without the remainder, it is a prime number. val sqrt = Math.sqrt(num.toDouble()) for (i in 2..sqrt.toInt()) if (num % i == 0L) return false } } return true } private fun generateRandomPrimePair(range: IntRange): Pair<Int, Int> { val num1 = generateRandomPrime(range) var num2 = generateRandomPrime(range) while (num2 == num1) num2 = generateRandomPrime(range) return Pair(num1, num2) } private fun generateRandomCoprime(range: IntRange, number: Int): Int { while (true) Random.nextInt(range.first, range.last).run { if (areCoprime(number.toLong(), this.toLong())) return this } } /** * Generates two random keys from prime numbers within the range. */ fun generateRandomKeys(primeRange: IntRange): Pair<RSAPublicKey, RSAPrivateKey> { fun generateE(intRange: IntRange, n: Int, phi: Int): Int { for (i in intRange) { if (areCoprime(i.toLong(), n.toLong()) && areCoprime(i.toLong(), phi.toLong())) return i } return 1 } fun generateD(e: Int, phi: Int, intRange: IntRange): Int { for (number in intRange) { if ((number * e) % phi == 1) return number } return -1 } val randomPrimes = generateRandomPrimePair(primeRange) val n = randomPrimes.first * randomPrimes.second val phi = (randomPrimes.first - 1) * (randomPrimes.second - 1) val e = generateE(2 until phi, n, phi) val d = generateD(e, phi, 2 until phi) val private = RSAPrivateKey(n, d) val public = RSAPublicKey(n, e) return Pair(public, private) } fun generateRandomKeys(primeRange: IntRange, minimumModulus: Int): Pair<RSAPublicKey, RSAPrivateKey> { fun generateE(intRange: IntRange, n: Int, phi: Int): Int { for (i in intRange) { if (areCoprime(i.toLong(), n.toLong()) && areCoprime(i.toLong(), phi.toLong())) return i } return 1 } fun generateD(e: Int, phi: Int, intRange: IntRange): Int { for (number in intRange) { if ((number * e) % phi == 1) return number } return -1 } var n = 0 var phi = 0 while (n <= minimumModulus) { generateRandomPrimePair(primeRange).run { n = this.first * this.second phi = (this.first - 1) * (this.second - 1) } } val e = generateE(2 until phi, n, phi) val d = generateD(e, phi, 2 until phi) val private = RSAPrivateKey(n, d) val public = RSAPublicKey(n, e) return Pair(public, private) } /** * Iteratively raises a number to a certain power. * For description refer to the method above. */ private fun raiseToPowerBig(num: Long, pow: Int): BigInteger { var result = BigInteger.valueOf(num) for (i in pow downTo 2) result *= BigInteger.valueOf(num) return result } /** * Encrypt a number. * For this to work properly, the modulus has to be bigger than the number. * The formula for encryption is c = m^e mod n, where e is the public key exponent and n is the modulus. */ fun rsaEncrypt(message: Int, publicKey: RSAPublicKey): Long { // Modulus must be bigger than the message to encrypt. if (publicKey.modulus <= message) return -1 return (raiseToPowerBig( message.toLong(), publicKey.exponent ).mod(BigInteger.valueOf(publicKey.modulus.toLong())).toLong()) } fun rsaEncrypt(message: String, publicKey: RSAPublicKey): Pair<String, Int> { var chunks = message .map { char -> rsaEncrypt(char.code, publicKey).toString() } var longest = 0 chunks.forEach { if (it.length > longest) longest = it.length } chunks = chunks.map { var result = it while (result.length < longest) result = "0$result" return@map result } val result = chunks.reduce { acc, s -> acc + s } return Pair(result, longest) } fun rsaDecrypt(message: String, blockSize: Int, privateKey: RSAPrivateKey): String { val chunks = message .chunked(blockSize) .map { if (it[0] != '0') return@map it else { var result = it while (result[0] == '0') { result = result.substring(1) } return@map result } } .map { rsaDecrypt(it.toLong(), privateKey).toInt().toChar() } var result = "" chunks.forEach { result += it.toString() } return result } fun rsaDecrypt(message: Long, privateKey: RSAPrivateKey): Long { val power = raiseToPowerBig(message, privateKey.d) return (power % BigInteger.valueOf(privateKey.modulus.toLong())).toLong() } class RSAPublicKey(val modulus: Int, val exponent: Int) class RSAPrivateKey(val modulus: Int, val d: Int)
0
Kotlin
92
771
e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1
6,964
KAHelpers
MIT License
src/y2016/Day02.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2016 import util.Direction import util.Pos import util.get import util.inverse import util.readInput object Day02 { val keyPad = listOf( listOf(7, 8, 9), listOf(4, 5, 6), listOf(1, 2, 3) ) val keyPad2 = listOf( "XX1XX".toList(), "X234X".toList(), "56789".toList(), "XABCX".toList(), "XXDXX".toList() ).reversed() private fun parse(input: List<String>): List<List<Direction>> { return input.map { line -> line.map { Direction.fromChar(it) } } } fun part1(input: List<String>): String { val parsed = parse(input) var currentPos = 1 to 1 val code = parsed.map { it.forEach { dir -> currentPos = dir.move(currentPos) currentPos = coerce(currentPos) } keyPad[currentPos.inverse()] } return code.joinToString(separator = "") { it.toString() } } private fun coerce(pos: Pos, max: Int = 2): Pos { val first = pos.first.coerceIn(0, max) val second = pos.second.coerceIn(0, max) return first to second } fun part2(input: List<String>): String { val parsed = parse(input) var currentPos = 0 to 2 val code = parsed.map { it.forEach { dir -> val newCandidate = coerce(dir.move(currentPos), 4) if (keyPad2[newCandidate.inverse()] != 'X') { currentPos = newCandidate } } keyPad2[currentPos.inverse()] } return code.joinToString(separator = "") { it.toString() } } } fun main() { val testInput = """ ULL RRDDD LURDL UUUUD """.trimIndent().split("\n") println("------Tests------") println(Day02.part1(testInput)) println(Day02.part2(testInput)) println("------Real------") val input = readInput("resources/2016/day02") println(Day02.part1(input)) println(Day02.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,089
advent-of-code
Apache License 2.0
src/day24/Code.kt
fcolasuonno
162,470,286
false
null
package day24 import java.io.File import java.util.* fun main(args: Array<String>) { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part(parsed, parsed.sum() / 3)}") println("Part 2 = ${part(parsed, parsed.sum() / 4)}") } fun parse(input: List<String>) = input.map { it.toInt() }.requireNoNulls().toSet().toSortedSet() fun part(input: SortedSet<Int>, weight: Int): Long? { val queue = ArrayDeque<Pair<Set<Int>, Int>>() val candidates = mutableSetOf<Set<Int>>() val seen = mutableSetOf<Set<Int>>() input.forEach { queue.addFirst(setOf(it) to (weight - it)) } while (queue.isNotEmpty()) { val (head, leftWeight) = queue.first() queue.removeFirst() if (seen.none { it.containsAll(head) }) { val size = candidates.map { it.size }.min() ?: Int.MAX_VALUE (input - head).filter { when { size > (head.size - 1) -> (it <= leftWeight) size == (head.size - 1) -> (it == leftWeight) else -> false } }.forEach { val new = head + it if (leftWeight - it == 0 && new.size <= size) { candidates.add(new) } else { if (new.size < size) { queue.addFirst(Pair(new, leftWeight - it)) } } } seen.add(head) } } return candidates.map { it.fold(1L) { qe, i -> qe * i } }.min() }
0
Kotlin
0
0
24f54bf7be4b5d2a91a82a6998f633f353b2afb6
1,697
AOC2015
MIT License
src/Day15.kt
rbraeunlich
573,282,138
false
{"Kotlin": 63724}
import kotlin.math.abs fun main() { fun part1(input: List<String>, lineToCheck: Int): Int { val sensorsAndClosestBeacons = input.map { line -> val sensorAndBeaconLine = line.replace("Sensor at ", "").replace(" closest beacon is at ", "") val sensorLine = sensorAndBeaconLine.split(":")[0] val sensorX = sensorLine.split(", ")[0].replace("x=", "").toInt() val sensorY = sensorLine.split(", ")[1].replace("y=", "").toInt() val beaconLine = sensorAndBeaconLine.split(":")[1] val beaconX = beaconLine.split(", ")[0].replace("x=", "").toInt() val beaconY = beaconLine.split(", ")[1].replace("y=", "").toInt() SensorAndClosestBeacon(sensorX to sensorY, beaconX to beaconY) } val minX = sensorsAndClosestBeacons.flatMap { listOf(it.sensorCoordinates.first, it.beaconCoordinates.first) }.min() val minY = sensorsAndClosestBeacons.flatMap { listOf(it.sensorCoordinates.second, it.beaconCoordinates.second) }.min() val maxX = sensorsAndClosestBeacons.flatMap { listOf(it.sensorCoordinates.first, it.beaconCoordinates.first) }.max() val maxY = sensorsAndClosestBeacons.flatMap { listOf(it.sensorCoordinates.second, it.beaconCoordinates.second) }.max() val sensorCave = SensorCave(minX, minY, maxX, maxY) sensorsAndClosestBeacons.forEach { sensorCave.add(it) } // sensorCave.coverSensorArea(sensorsAndClosestBeacons.first { it.sensorCoordinates == 8 to 7 }, lineToCheck) sensorsAndClosestBeacons.forEach { sensorCave.coverSensorArea(it, lineToCheck) // sensorCave.printContents() } // sensorCave.printContents() val allBeaconsInRow = sensorsAndClosestBeacons.map { it.beaconCoordinates } .filter { it.second == lineToCheck }.toSet() return (sensorCave.caveContent - allBeaconsInRow) .count { it.second == lineToCheck } } fun part2(input: List<String>, maxCoordinate: Int): Int { val sensorsAndClosestBeacons = input.map { line -> val sensorAndBeaconLine = line.replace("Sensor at ", "").replace(" closest beacon is at ", "") val sensorLine = sensorAndBeaconLine.split(":")[0] val sensorX = sensorLine.split(", ")[0].replace("x=", "").toInt() val sensorY = sensorLine.split(", ")[1].replace("y=", "").toInt() val beaconLine = sensorAndBeaconLine.split(":")[1] val beaconX = beaconLine.split(", ")[0].replace("x=", "").toInt() val beaconY = beaconLine.split(", ")[1].replace("y=", "").toInt() SensorAndClosestBeacon(sensorX to sensorY, beaconX to beaconY) } // val minX = // sensorsAndClosestBeacons.flatMap { listOf(it.sensorCoordinates.first, it.beaconCoordinates.first) }.min() // val minY = // sensorsAndClosestBeacons.flatMap { listOf(it.sensorCoordinates.second, it.beaconCoordinates.second) }.min() // val maxX = // sensorsAndClosestBeacons.flatMap { listOf(it.sensorCoordinates.first, it.beaconCoordinates.first) }.max() // val maxY = // sensorsAndClosestBeacons.flatMap { listOf(it.sensorCoordinates.second, it.beaconCoordinates.second) }.max() // val sensorCave = SensorCave(minX, minY, maxX, maxY) // sensorsAndClosestBeacons.forEach { sensorCave.add(it) } // sensorsAndClosestBeacons.forEach { // sensorCave.coverSensorAreaWithinLimit(it, maxCoordinate) //// sensorCave.printContents() // } // sensorCave.printContents() for (x in (0..maxCoordinate)) { for (y in (0..maxCoordinate)) { if (sensorsAndClosestBeacons.all { sensorAndBeacon -> manhattanDistrance( x to y, sensorAndBeacon.sensorCoordinates ) > sensorAndBeacon.manhattanDistance }) { return x * 4000000 + y } } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) } data class SensorAndClosestBeacon( val sensorCoordinates: Pair<Int, Int>, val beaconCoordinates: Pair<Int, Int> ) { val manhattanDistance: Int = manhattanDistrance(sensorCoordinates, beaconCoordinates) } fun manhattanDistrance(from: Pair<Int, Int>, to: Pair<Int, Int>) = abs(from.first - to.first) + abs(from.second - to.second) data class SensorCave( val minX: Int, val minY: Int, val maxX: Int, val maxY: Int, val caveContent: MutableSet<Pair<Int, Int>> = mutableSetOf(), ) { fun printContents() { (minY..maxY).forEach { y -> (minX..maxX).forEach { x -> if (caveContent.contains(x to y)) { print("#") } else { print(".") } } println() } } fun add(sensorAndClosestBeacon: SensorAndClosestBeacon) { caveContent.add(sensorAndClosestBeacon.sensorCoordinates) caveContent.add(sensorAndClosestBeacon.beaconCoordinates) } fun coverSensorArea(sensorAndClosestBeacon: SensorAndClosestBeacon, lineToCheck: Int) { val sensorCoordinates = sensorAndClosestBeacon.sensorCoordinates val distance = sensorAndClosestBeacon.manhattanDistance if (reachesLineToCheck(sensorCoordinates, distance, lineToCheck)) { val remainingDistanceInLineToCheck = distance - abs(sensorCoordinates.second - lineToCheck) // is below val y = lineToCheck ((sensorCoordinates.first - remainingDistanceInLineToCheck)..(sensorCoordinates.first + remainingDistanceInLineToCheck)).forEach { caveContent.add(it to y) } } // // fill initial row // fillRow(sensorCoordinates.second, sensorCoordinates.first, distance, lineToCheck) // // afterwards it is always pairwise filled // ((distance) downTo 0).forEachIndexed { index, dist -> // fillRow(sensorCoordinates.second + index, sensorCoordinates.first, dist, lineToCheck) // fillRow(sensorCoordinates.second - index, sensorCoordinates.first, dist, lineToCheck) // } } fun coverSensorAreaWithinLimit(sensorAndClosestBeacon: SensorAndClosestBeacon, limit: Int) { val sensorCoordinates = sensorAndClosestBeacon.sensorCoordinates val distance = sensorAndClosestBeacon.manhattanDistance println(distance) // fill initial row fillRowWithLimit(sensorCoordinates.second, sensorCoordinates.first, distance, limit) // afterwards it is always pairwise filled ((distance) downTo 0).forEachIndexed { index, dist -> fillRowWithLimit(sensorCoordinates.second + index, sensorCoordinates.first, dist, limit) fillRowWithLimit(sensorCoordinates.second - index, sensorCoordinates.first, dist, limit) } } private fun reachesLineToCheck(sensorCoordinates: Pair<Int, Int>, distance: Int, lineToCheck: Int): Boolean = // from below sensorCoordinates.first - distance < lineToCheck || // from above sensorCoordinates.first + distance > lineToCheck private fun fillRow(y: Int, x: Int, distance: Int) { ((x - distance)..(x + distance)).forEach { caveContent.add(it to y) } } private fun fillRowWithLimit(y: Int, x: Int, distance: Int, limit: Int) { if (y !in 0..limit) { return } ((x - distance)..(x + distance)) .filter { x in 0..limit } .forEach { caveContent.add(it to y) } } }
0
Kotlin
0
1
3c7e46ddfb933281be34e58933b84870c6607acd
8,113
advent-of-code-2022
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day199/day199.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day199 // day199.kt // By <NAME>. fun closestString(elems: String): String { return closestString(elems.toList()) } fun closestString(elems: List<Char>): String { /** * Goal: given a string comprising parentheses, find a string with balanced parentheses to the original string. * We can add or remove parentheses: each operation is considered a move, and a string s1 is closer to s2 than s3 * if the number of moves you need to transform s1 to s2 is less than the number needed to transfer from s2 to s3. * * Note that since adding and removing parentheses have the same value, it doesn't matter which one we do: we can * focus on one and ignore the other. Here, we focus on adding ) to balance strings. We could remove ( and have the * same effect, albeit with shorter strings. * * This results in a greedy, functional solution with complexity and space O(n). */ // We only care about parentheses. // Our zero value is a pair of the number of open parentheses and the closest string thus far. val (openParens, closestString) = elems .filter { it in setOf('(', ')')} .fold(0 to ""){ (openParens, closestString), p -> when (p) { /*** (: just devour the ( and move on ***/ '(' -> (openParens + 1 to "$closestString(") /*** ) ***/ else -> when (openParens) { 0 -> (openParens to "$closestString()") else -> (openParens - 1 to "$closestString)") } } } // Now we have to close all the remaining open parentheses. return closestString + ")".repeat(openParens) } /** * Check to see if a string is balanced. */ fun String.isParenthesesBalanced(str: String): Boolean { var balance = 0 for (s in str) { if (s == '(') ++balance else if (s == ')') { if (balance > 0) --balance else return false } } return true }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
2,120
daily-coding-problem
MIT License
src/Day02.kt
kseito
573,212,303
false
{"Kotlin": 2701}
fun main() { fun part1(input: List<String>): Int { var sum = 0 input.forEach { when(it) { "A X" -> sum += 3 + 1 "A Y" -> sum += 6 + 2 "A Z" -> sum += 0 + 3 "B X" -> sum += 0 + 1 "B Y" -> sum += 3 + 2 "B Z" -> sum += 6 + 3 "C X" -> sum += 6 + 1 "C Y" -> sum += 0 + 2 "C Z" -> sum += 3 + 3 } } return sum } fun part2(input: List<String>): Int { var sum = 0 input.forEach { when(it) { "A X" -> sum += 0 + 3 "A Y" -> sum += 3 + 1 "A Z" -> sum += 6 + 2 "B X" -> sum += 0 + 1 "B Y" -> sum += 3 + 2 "B Z" -> sum += 6 + 3 "C X" -> sum += 0 + 2 "C Y" -> sum += 3 + 3 "C Z" -> sum += 6 + 1 } } return sum } val input = readInput("Day02") // val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e14f765390630635a2230feda1efb21b443add39
1,141
advent-of-code-kotlin-template
Apache License 2.0
src/search/Main.kt
JIghtuse
590,549,138
false
null
package search import java.io.File import java.lang.IllegalArgumentException typealias Dataset = List<String> typealias InvertedIndex = Map<String, List<Int>> fun toLowercaseWords(s: String) = s.split(" ").map(String::lowercase) fun ask(prompt: String): String { println(prompt) return readln() } fun scanInputFile(filePath: String): Pair<Dataset, InvertedIndex> { val lines = mutableListOf<String>() val invertedIndex = mutableMapOf<String, MutableList<Int>>() var lineIndex = 0 val file = File(filePath) file.forEachLine { lines.add(it) for (word in toLowercaseWords(it).filter(String::isNotEmpty)) { val positions = invertedIndex.getOrDefault(word, mutableListOf()) positions.add(lineIndex) invertedIndex[word] = positions } lineIndex += 1 } return lines to invertedIndex } fun printPeople(dataset: Dataset) { println("=== List of people ===") dataset.forEach(::println) } fun reportResult(matchedItems: Dataset) { if (matchedItems.isNotEmpty()) { println("${matchedItems.size} persons found:") printPeople(matchedItems) } else { println("No matching people found.") } } enum class MatchOption { ALL, ANY, NONE, } fun toMatchOption(s: String): MatchOption { return MatchOption.valueOf(s.uppercase()) } class Searcher(private val dataset: Dataset, private val invertedIndex: InvertedIndex) { fun search(query: String, matchOption: MatchOption): Dataset { return when (matchOption) { MatchOption.ALL -> ::searchAll MatchOption.ANY -> ::searchAny MatchOption.NONE -> ::searchNone }(toLowercaseWords(query)) } private fun searchAny(queryWords: List<String>): Dataset { return queryWords.flatMap { word -> invertedIndex .getOrDefault(word, mutableListOf()) .map { dataset[it] } } } private fun searchAll(queryWords: List<String>): Dataset { if (queryWords.isEmpty()) return listOf() return queryWords .map { word -> invertedIndex .getOrDefault(word, mutableListOf()) .toSet() } .reduce { acc, indices -> acc.intersect(indices) } .map { dataset[it] } } private fun searchNone(queryWords: List<String>): Dataset { if (queryWords.isEmpty()) return dataset val allIndices = (0..dataset.lastIndex) val anyIndices = queryWords .flatMap { word -> invertedIndex .getOrDefault(word, mutableListOf()) } .toSet() return allIndices .subtract(anyIndices) .map { dataset[it] } } } fun createSearcherAndDataset(dataFilePath: String): Pair<Searcher, Dataset> { val (dataset, invertedIndex) = scanInputFile(dataFilePath) return Searcher(dataset, invertedIndex) to dataset } fun matchOptionToQueryPrompt(matchOption: MatchOption): String { return when (matchOption) { MatchOption.NONE -> "Enter a name or email to search none matching people." MatchOption.ANY -> "Enter a name or email to search any matching people." MatchOption.ALL -> "Enter a name or email to search all matching people." } } fun searchAndReportResult(searcher: Searcher) { val matchOption = toMatchOption(ask("Select a matching strategy: ALL, ANY, NONE")) val query = ask(matchOptionToQueryPrompt(matchOption)) val matchedItems = searcher.search(query, matchOption) reportResult(matchedItems) } data class MenuItem(val name: String, val action: () -> Unit) class Menu(exitItemNumber: Int, private val items: Map<Int, MenuItem>) { private val exitItem = exitItemNumber.toString() init { require(!items.containsKey(exitItemNumber)) } val prompt = buildString { append("=== Menu ===") append("\n") items .entries .forEach { command -> append("${command.key}. ${command.value.name}") append("\n") } append("$exitItem. Exit") append("\n") } fun run(userChoice: String): Boolean { if (userChoice == exitItem) { return false } try { val menuIndex = userChoice.toInt() require(items.containsKey(menuIndex)) items[menuIndex]!!.action() } catch (e: IllegalArgumentException) { println("Incorrect option! Try again.") } return true } } fun main(args: Array<String>) { require(args.size == 2) require(args[0] == "--data") val (searcher, dataset) = createSearcherAndDataset(args[1]) val menu = Menu( 0, mapOf( 1 to MenuItem("Find a person") { searchAndReportResult(searcher) }, 2 to MenuItem("Print all people") { printPeople(dataset) }) ) while (true) { val moreToRun = menu.run(ask(menu.prompt)) if (!moreToRun) break } println("Bye!") }
0
Kotlin
0
0
4634a626ee544ab63fff5b0e08bbfe3bc11e3f65
5,165
simple-search-engine-hyperskill
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2023/day14/Platform.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day14 import com.github.michaelbull.advent2023.math.Vector2 import com.github.michaelbull.advent2023.math.Vector2CharMap import com.github.michaelbull.advent2023.math.toVector2CharMap fun Sequence<String>.toPlatform(): Platform { return Platform(this.toVector2CharMap()) } data class Platform( val map: Vector2CharMap, ) { private val horizontalAxis = HorizontalAxis(map) private val verticalAxis = VerticalAxis(map) fun tiltNorth() = tiltY(+1) fun tiltEast() = tiltX(-1) fun tiltSouth() = tiltY(-1) fun tiltWest() = tiltX(+1) fun totalLoad(): Int { return map.positions() .filter(map::isRoundRockAt) .sumOf(map::load) } fun cycle(times: Int): Sequence<Platform> = sequence { val cycles = mutableMapOf<Platform, Int>() for ((cycle, pair) in cycleSequence().zipWithNext().withIndex()) { val (platform, nextPlatform) = pair cycles[platform] = cycle yield(nextPlatform) val nextPlatformsCycle = cycles[nextPlatform] if (nextPlatformsCycle != null) { val nextCycle = cycle + 1 val delta = nextCycle - nextPlatformsCycle if (delta > 0) { val remainingCycles = times - cycle val remaining = remainingCycles % delta yieldAll(nextPlatform.cycleSequence().take(remaining)) } break } } } private fun cycle(): Platform { return tiltNorth() .tiltWest() .tiltSouth() .tiltEast() } private fun cycleSequence(): Sequence<Platform> { return generateSequence(this, Platform::cycle) } private fun tilt(delta: Int, axis: Axis): Platform { val tilted = Vector2CharMap(width = map.width, height = map.height) { '.' } val range = axis.range.sortedBy(delta::times) for (b in axis.opposite) { var emptyA = range.first() for (a in range) { val position = axis(a, b) val char = map[position] if (char.isRoundRock()) { val emptyPosition = axis(emptyA, b) tilted[emptyPosition] = 'O' emptyA += delta } else if (char.isCubeRock()) { tilted[position] = '#' emptyA = a + delta } } } return copy(map = tilted) } private fun tiltX(x: Int): Platform { return tilt(x, horizontalAxis) } private fun tiltY(y: Int): Platform { return tilt(y, verticalAxis) } } private fun Vector2CharMap.load(vector2: Vector2): Int { return height - vector2.y } private fun Char.isRoundRock(): Boolean { return this == 'O' } private fun Char.isCubeRock(): Boolean { return this == '#' } private fun Vector2CharMap.isRoundRockAt(position: Vector2): Boolean { return get(position).isRoundRock() }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
3,104
advent-2023
ISC License
src/main/kotlin/aoc2018/BeverageBandits.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2018 import komu.adventofcode.aoc2018.Creature.Companion.hitPointComparator import komu.adventofcode.aoc2018.Creature.Companion.positionComparator import komu.adventofcode.aoc2018.CreatureType.ELF import komu.adventofcode.aoc2018.CreatureType.GOBLIN import komu.adventofcode.utils.Point import komu.adventofcode.utils.Point.Companion.readingOrderComparator import komu.adventofcode.utils.nonEmptyLines import utils.shortestPathBetween fun beverageBandits(input: String): Int { val world = BanditWorld(input.nonEmptyLines()) var rounds = 0 while (true) { if (!world.tick()) break rounds++ } return rounds * world.totalHitPoints } fun beverageBandits2(input: String): Int { fun checkPower(power: Int): Int? { val world = BanditWorld(input.nonEmptyLines(), elfPower = power) val originalElves = world.elves.size var rounds = 0 while (world.elves.size == originalElves) { if (!world.tick()) break rounds++ } return if (world.elves.size == originalElves) rounds * world.totalHitPoints else null } var min = 4 var max = 200 var bestResult = 0 // binary search for best power while (min < max) { val power = min + (max - min) / 2 val result = checkPower(power) if (result != null) { max = power bestResult = result } else { min = power + 1 } } return bestResult } private data class Creature(val type: CreatureType, var position: Point, val attackPower: Int = 3) { var hitPoints = 200 val isAlive: Boolean get() = hitPoints > 0 companion object { val positionComparator = compareBy<Creature, Point>(readingOrderComparator) { it.position } val hitPointComparator = compareBy<Creature> { it.hitPoints }.then(positionComparator) } } private enum class CreatureType { GOBLIN, ELF } private class BanditWorld( val spaces: Set<Point>, val goblins: MutableList<Creature>, val elves: MutableList<Creature> ) { val totalHitPoints: Int get() = goblins.sumOf { it.hitPoints } + elves.sumOf { it.hitPoints } private val occupiedPoints = (goblins + elves).mapTo(mutableSetOf()) { it.position } fun tick(): Boolean { val sortedUnits = (goblins + elves).sortedWith(positionComparator) for (unit in sortedUnits) { if (!unit.isAlive) continue val targets = when (unit.type) { ELF -> goblins GOBLIN -> elves } if (targets.isEmpty()) return false val squaresInEnemyRange = targets.flatMap { it.position.neighbors } if (unit.position !in squaresInEnemyRange) if (!move(unit, squaresInEnemyRange)) continue val target = targets.filter { it.position.isAdjacentTo(unit.position) }.minWithOrNull(hitPointComparator) if (target != null) { target.hitPoints -= unit.attackPower if (!target.isAlive) { targets -= target occupiedPoints -= target.position } } } return true } private fun move(unit: Creature, squaresInEnemyRange: List<Point>): Boolean { val target = squaresInEnemyRange .filter { canMoveInto(it) } .mapNotNull { shortestPath(it, unit.position) } .minOrNull() ?.start ?: return false val pathStart = unit.position.neighbors .mapNotNull { shortestPath(it, target) } .minOrNull() ?.start!! occupiedPoints -= unit.position unit.position = pathStart occupiedPoints += unit.position return true } private fun shortestPath(start: Point, target: Point) = if (start == target) PathInfo(start, 0) else shortestPathBetween(target, start) { p -> p.neighbors.filter { canMoveInto(it) } }?.let { PathInfo(start, it.size) } private fun canMoveInto(p: Point) = p in spaces && p !in occupiedPoints private class PathInfo(val start: Point, val length: Int) : Comparable<PathInfo> { override fun compareTo(other: PathInfo): Int { val lengthResult = length.compareTo(other.length) return if (lengthResult != 0) lengthResult else readingOrderComparator.compare(start, other.start) } } companion object { operator fun invoke(lines: List<String>, elfPower: Int = 3): BanditWorld { val spaces = mutableSetOf<Point>() val goblins = mutableListOf<Creature>() val elves = mutableListOf<Creature>() for ((y, line) in lines.withIndex()) { for ((x, c) in line.withIndex()) { val point = Point(x, y) when (c) { '.' -> spaces += point 'E' -> { spaces += point elves += Creature(ELF, point, attackPower = elfPower) } 'G' -> { spaces += point goblins += Creature(GOBLIN, point) } '#' -> { // wall } else -> error("unexpected '$c' at line $y column $x") } } } return BanditWorld( spaces = spaces, goblins = goblins, elves = elves ) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
5,883
advent-of-code
MIT License
src/day7/day7.kt
TimCastelijns
113,205,922
false
null
package day7 import java.io.File fun main(args: Array<String>) { p1(File("src/day7/input")) p2(File("src/day7/input")) } fun p1(file: File) { val programs = mutableListOf<String>() val subPrograms = mutableListOf<String>() file.forEachLine { line -> val parts = line.split(" ") val program = parts[0] programs.add(program) val weight = parts[1].trim('(', ')').toInt() if ("->" in parts) { parts.subList(3, parts.size) .map { it -> it.trim(',') } .forEach { s -> subPrograms.add(s) } } } programs.forEach { program -> if (!subPrograms.contains(program)) { println(program) } } } val programWeights = mutableMapOf<String, Int>() val directSubs = mutableMapOf<String, List<String>>() fun p2(file: File) { val programs = mutableListOf<String>() val subPrograms = mutableListOf<String>() file.forEachLine { line -> val parts = line.split(" ") val program = parts[0] programs.add(program) val weight = parts[1].trim('(', ')').toInt() programWeights.put(program, weight) if ("->" in parts) { val subs = parts.subList(3, parts.size) .map { it -> it.trim(',') } subs.forEach { s -> subPrograms.add(s) } directSubs.put(program, subs) } } val programTotalWeights = mutableMapOf<String, Int>() for (p: String in programs) { if (directSubs.containsKey(p)) { programTotalWeights.put(p, getWeightOfProgramAndSubs(p)) } else { programTotalWeights.put(p, programWeights[p]!!) } } for (p: String in programs.filter { directSubs.containsKey(it) }) { val weights = directSubs[p]!!.map { programTotalWeights[it]!! } if (weights.toSet().size != 1) { println(programTotalWeights[p]) println(weights) directSubs[p]!!.forEach { t: String? -> print("${programWeights[t]} - ") } println() println(programWeights[p]) println() } } } fun getWeightOfProgramAndSubs(name: String): Int { var weight = 0 weight += programWeights[name]!! // start with weight of the program itself // recursively add weights of sub programs if (directSubs.containsKey(name)) { for (sub: String in directSubs[name]!!) { weight += getWeightOfProgramAndSubs(sub) } } return weight }
0
Kotlin
0
0
656f2a424b323175cd14d309bc25430ac7f7250f
2,550
aoc2017
MIT License
src/Day01.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
import java.util.PriorityQueue class Sums(val input: List<String>) : Iterable<Int> { override fun iterator(): Iterator<Int> { return object : Iterator<Int> { var index = 0 override fun hasNext(): Boolean = index < input.size override fun next(): Int { var sum = 0 while (index < input.size && input[index].isNotBlank()) { sum += Integer.parseInt(input[index++]) } index++ return sum } } } } fun main() { fun part1(input: List<String>): Int { var max = 0 for (sum in Sums(input)) { max = max.coerceAtLeast(sum) } return max } fun part2(input: List<String>): Int { val maxes = PriorityQueue<Int>(4) for (sum in Sums(input)) { maxes.add(sum) if (maxes.size > 3) { maxes.poll() } } return maxes.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
1,265
advent-of-code-2022
Apache License 2.0
src/Day07.kt
janbina
112,736,606
false
null
package day07 import getInput import kotlin.math.abs import kotlin.test.assertEquals data class Program( val name: String, val weight: Int, val supports: MutableList<Program> = mutableListOf(), var supportedBy: Program? = null ) { private val totalWeight: Int by lazy { weight + supports.sumBy { it.totalWeight } } private val childrenAreBalanced: Boolean by lazy { supports.distinctBy { it.totalWeight }.size == 1 } fun findImbalance(imbalance: Int? = null): Int { if (imbalance != null && childrenAreBalanced) { return weight - imbalance } else { val grouped = supports.groupBy { it.totalWeight } val badOne = grouped.minBy { it.value.size }!!.value.first() val imb = grouped.keys.toList().let { abs(it[0] - it[1]) } return badOne.findImbalance(imb) } } } fun parseInput(lines: List<String>): Program { val programs = mutableMapOf<String, Program>() val parentToChild = mutableSetOf<Pair<Program, String>>() lines.forEach { val parsed = Regex("\\w+").findAll(it).map { it.value }.toList() val program = Program(parsed[0], parsed[1].toInt()) programs.put(program.name, program) parsed.drop(2).forEach { parentToChild.add(program to it) } } parentToChild.forEach { (parent, child) -> programs[child]?.let { parent.supports.add(it) it.supportedBy = parent } } return programs.values.first { it.supportedBy == null } } fun main(args: Array<String>) { val input = parseInput(getInput(7).readLines()) assertEquals("eugwuhl", input.name) assertEquals(420, input.findImbalance()) }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
1,775
advent-of-code-2017
MIT License
app/src/main/kotlin/com/engineerclark/advent2022/Day04.kt
engineerclark
577,449,596
false
{"Kotlin": 10394}
package com.engineerclark.advent2022 import com.engineerclark.advent2022.utils.readDayLines fun main() { val assignments = readDayLines(4).readPairAssignments() println("Day 4, challenge 1 -- Count of elf pair assignments where one is a subset of the other: " + "${assignments.countHavingSubset}") println("Day 4, challenge 2 -- Count of elf pair assignments that overlap: " + "${assignments.countOverlappingAssignments}") } fun List<String>.readPairAssignments(): List<ElfPair> = this.map { it.trim().readPairAssignment() } val List<ElfPair>.countHavingSubset get() = this.count { it.oneIsSubset } val List<ElfPair>.countOverlappingAssignments get() = this.count { it.assignmentsOverlap } fun String.readPairAssignment(): ElfPair { val assignments = this.split(",") val firstAssignment = readAssignmentRange(assignments[0]) val secondAssignment = readAssignmentRange(assignments[1]) return ElfPair(this, firstAssignment, secondAssignment) } fun readAssignmentRange(assignmentString: String): Set<Int> { val limits = assignmentString.split("-") val first = limits[0].toInt() val last = limits[1].toInt() return IntRange(first, last).toSet() } data class ElfPair( val source: String, val firstAssignment: Set<Int>, val secondAssignment: Set<Int> ) { val oneIsSubset: Boolean get() = firstAssignment.containsAll(secondAssignment) || secondAssignment.containsAll(firstAssignment) val assignmentsOverlap: Boolean get() = firstAssignment.intersect(secondAssignment).isNotEmpty() }
0
Kotlin
0
0
3d03ab2cc9c83b3691fede465a6e3936e7c091e9
1,597
advent-of-code-2022
MIT License
2023/src/main/kotlin/day2.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parse import utils.Parser import utils.Solution import utils.mapItems private typealias Input = List<Day2.Game> fun main() { Day2.run() } object Day2 : Solution<Input>() { override val name = "day2" override val parser = Parser.lines.mapItems(::parseGame) @Parse("Game {id}: {r '; ' rounds}") data class Game( val id: Int, val rounds: List<Round>, ) { fun isPossible(amounts: Map<Color, Int>): Boolean { return rounds.all { Color.entries.all { c -> (it.shown[c] ?: 0) <= (amounts[c] ?: 0) } } } val power: Int get() { return Color.entries.fold(1) { acc, c -> acc * rounds.maxOf { it.shown[c] ?: 0 } } } } @Parse("{r ', ' shown}") data class Round( @Parse("{value} {key}") val shown: Map<Color, Int>, ) enum class Color { red, green, blue; } override fun part1(input: Input): Int { val amounts = mapOf(Color.red to 12, Color.green to 13, Color.blue to 14) return input.filter { it.isPossible(amounts) }.sumOf { it.id } } override fun part2(input: Input): Int { return input.sumOf { it.power } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,156
aoc_kotlin
MIT License
src/main/kotlin/aoc2020/day11/GameOfLife.kt
arnab
75,525,311
false
null
package aoc2020.day11 object GameOfLife { private const val DEBUG_REPORT_MODE = false fun parse(rawData: String): List<List<Cell>> = rawData .split("\n") .mapIndexed { y, row -> row.toCharArray().mapIndexed { x, char -> val state = State.values().find { it.sign == char.toString() }!! Cell(y = y, x = x, state = state) } } enum class State(val sign: String) { EMPTY("L"), OCCUPIED("#"), FLOOR(".") } data class Cell(val y: Int, val x: Int, val state: State) { /** * For the cell at [1,1], these are the neighbors: * [ * [0, 0], [0, 1], [0, 2], * [1, 0], [1, 2], * [2, 0], [2, 1], [2, 2], * ] */ fun neighbors(cells: List<List<Cell>>): List<Cell> = ((y - 1)..(y + 1)).map { col -> ((x - 1)..(x + 1)).map { row -> if (row == this.x && col == this.y) null else cells.getOrNull(col)?.getOrNull(row) } }.flatten().filterNotNull() fun neighborsUntilNextSeat(cells: List<List<Cell>>): List<Cell> = listOf( Pair(-1, -1), Pair(-1, 0), Pair(-1, 1), Pair(0, -1), Pair(0, 1), Pair(1, -1), Pair(1, 0), Pair(1, 1) ).mapNotNull { (stepY, stepX) -> findNearestSeatInDirection(this.y, this.x, stepY, stepX, cells) } private fun findNearestSeatInDirection(y: Int, x: Int, stepY: Int, stepX: Int, cells: List<List<Cell>>): Cell? { val nextY = y + stepY val nextX = x + stepX val nextCell = cells.getOrNull(nextY)?.getOrNull(nextX) return if (nextCell == null || nextCell.state != State.FLOOR) nextCell else findNearestSeatInDirection(nextY, nextX, stepY, stepX, cells) } fun nextState(neighbors: List<Cell>): State { if (this.state == State.FLOOR) return state if (this.state == State.EMPTY && neighbors.none { it.state == State.OCCUPIED }) return State.OCCUPIED // Part 2 rules apply... if (this.state == State.OCCUPIED && neighbors.filter { it.state == State.OCCUPIED }.count() >= 5) return State.EMPTY return state } } fun simulateUntilStable(cells: List<List<Cell>>): Pair<Int, List<List<Cell>>> { var generation = 0 var changedAfterNextGeneration: Boolean var nextCells = cells do { generation++ val result = simulateNextGeneration(nextCells) changedAfterNextGeneration = result.first nextCells = result.second if (DEBUG_REPORT_MODE) report(generation, changedAfterNextGeneration, nextCells) } while (changedAfterNextGeneration) return Pair(generation, nextCells) } private fun simulateNextGeneration(cells: List<List<Cell>>): Pair<Boolean, List<List<Cell>>> { val nextCells = cells.map { col -> col.map { cell -> val neighbors = cell.neighborsUntilNextSeat(cells) cell.copy( state = cell.nextState(neighbors) ) } } return Pair(cells != nextCells, nextCells) } fun countSeats(cells: List<List<Cell>>, state: State) = cells.flatMap { row -> row.map { it.state } }.filter { it == state }.count() private fun report(generation: Int, changed: Boolean, cells: List<List<Cell>>) { println("\n\n") println("=============== Gen: $generation (Changed: $changed) ===============") cells.forEach { row -> println() row.forEach { cell -> print(cell.state.sign) } } } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
4,019
adventofcode
MIT License
src/day03/Day03.kt
apeinte
574,487,528
false
{"Kotlin": 47438}
package day03 import readDayInput const val ITEMS_PATTERN = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z" fun main() { fun getAlphabetParsed(): List<String> { return ITEMS_PATTERN.split(",") } fun checkIfAlphabetIsCorrect(): Boolean { return getAlphabetParsed().size == 52 } fun findPriorityOfThisItem(item: String): Int = getAlphabetParsed().indexOf(item) + 1 fun partOne(input: List<String>): Int { var result = 0 var numberOfAnomaly = 0 // step 1 : loop the list input.forEach { rucksack -> // step 2 : split the list in two list val listOfItems = rucksack.split("") val splitListNumber = listOfItems.size / 2 val listCompartmentOne = listOfItems.subList(0, splitListNumber) println("Compartment one contain : $listCompartmentOne") val listCompartmentTwo = listOfItems.subList(splitListNumber, listOfItems.lastIndex) println("Compartment two contain : $listCompartmentTwo") // step 3 : compare list 1 content with list 2 content var anomalyFound = false listCompartmentOne.forEach { item -> if (listCompartmentTwo.contains(item) && !anomalyFound) { anomalyFound = true val priority = findPriorityOfThisItem(item) println("I found a anomaly! $item with priority $priority") result += priority numberOfAnomaly++ } } } println("All rucksacks has been checked. I've found $numberOfAnomaly anomalies.") return result } fun getTheBadgeOfThisGroup(listRucksackOfTheGroup: MutableList<String>): String { // Search in all rucksack the common item println("Search for the badge of this group...") var result = "" getAlphabetParsed().forEach { letter -> if (listRucksackOfTheGroup[0].contains(letter) && listRucksackOfTheGroup[1].contains(letter) && listRucksackOfTheGroup[2].contains(letter) ) { println("It's badge $letter!") result = letter } } return result } fun partTwo(input: List<String>): Int { var result = 0 var groupCounter = 0 var listRucksackOfTheGroup = mutableListOf<String>() var nbGroupOfElves = 0 // Split group input.forEach { elf -> groupCounter++ listRucksackOfTheGroup.add(elf) if (groupCounter == 3) { nbGroupOfElves++ println("Group of 3 elves created!") // The group is complete, proceed to the badge checker result += findPriorityOfThisItem(getTheBadgeOfThisGroup(listRucksackOfTheGroup)) listRucksackOfTheGroup = mutableListOf() groupCounter = 0 } } println("$nbGroupOfElves group of elves has been created.") return result } val inputRead = readDayInput(3) if (checkIfAlphabetIsCorrect() && partOne(readDayInput(3, true)) == 157) { // Test has been passed so we can get the result of part 1 println("What is the sum of the priorities of those item types?\n${partOne(inputRead)}") } if (checkIfAlphabetIsCorrect() && partTwo(readDayInput(3, true)) == 70) { // Test has been passed so we can get the result of part 2 println("What is the sum of the priorities of those item types?|\n${partTwo(inputRead)}") } }
0
Kotlin
0
0
4bb3df5eb017eda769b29c03c6f090ca5cdef5bb
3,696
my-advent-of-code
Apache License 2.0
src/main/kotlin/Excercise02.kt
underwindfall
433,989,850
false
{"Kotlin": 55774}
private fun part1() { getInputAsTest("02") { split("\n") } .map { it.split(" ") } .map { it[0] to it[1].toInt() } .fold(0 to 0) { (y, x), (move, unit) -> when (move) { "forward" -> y to x + unit "down" -> y + unit to x "up" -> y - unit to x else -> throw IllegalArgumentException("Unknown move: $move") } } .apply { println("Part 1: ${this.first * this.second}") } } private fun part2() { getInputAsTest("02") { split("\n") } .map { it.split(" ") } .map { it[0] to it[1].toInt() } .fold(Triple(0, 0, 0)) { (depth, horizontal, aim), (move, unit) -> when (move) { "forward" -> Triple(depth + (aim * unit), horizontal + unit, aim) "up" -> Triple(depth, horizontal, aim - unit) else -> Triple(depth, horizontal, aim + unit) } } .apply { println("Part 2: ${this.first * this.second}") } } fun main() { part1() part2() }
0
Kotlin
0
0
4fbee48352577f3356e9b9b57d215298cdfca1ed
945
advent-of-code-2021
MIT License
src/day3/day3.kt
bienenjakob
573,125,960
false
{"Kotlin": 53763}
package day3 import inputTextOfDay import testTextOfDay private val Char.priority: Int get() = when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("$this is unknown, check your input!") } fun part1(text: String): Int = text.lines() .map { it.chunked(it.length / 2) { it.toSet()} } .map { (a, b) -> a.single { item -> b.count { it == item } >= 1 } } .sumOf { it.priority } fun part2(text: String): Int = text.lines() .chunked(3) { elves -> elves.map { elf -> elf.toSet()} } .map { (a, b, c) -> a.single { item -> b.count { it == item } >= 1 && c.count { it == item } >= 1 } } .sumOf { it.priority } fun main() { val day = 3 val testInput = testTextOfDay(day) check(part1(testInput) == 157) val input = inputTextOfDay(day) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6ff34edab6f7b4b0630fb2760120725bed725daa
924
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2023/day9/Day9.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day9 import com.jacobhyphenated.advent2023.Day /** * Day 9: Mirage Maintenance * * Each line of the puzzle input is a series of readings from an instrument. */ class Day9: Day<List<List<Int>>> { override fun getInput(): List<List<Int>> { return parseInput(readInputFile("9")) } /** * Part 1: Extrapolate the next number in the sequence * * Do this by finding the difference of each of the values. * If the difference of all values is not 0, repeat this process * example: * 1 3 6 10 15 21 * 2 3 4 5 6 * 1 1 1 1 * 0 0 0 * * To extrapolate the next number, add the last value of each of the difference lines * 1 3 6 10 15 21 28 * 2 3 4 5 6 7 * 1 1 1 1 1 * 0 0 0 0 * * Giving the value of 28. Add this value for each line of the puzzle input */ override fun part1(input: List<List<Int>>): Int { return input.sumOf { measure -> val differences = mutableListOf(measure) var currentDiff = measure while (currentDiff.any { it != 0 }) { currentDiff = currentDiff.windowed(2).map { (a, b) -> b - a } differences.add(currentDiff) } differences.sumOf { it.last() } } } /** * Part 2: Now extrapolate the first value. * Instead of adding the last values, fill in a 0 at the beginning of the final difference list, * and calculate the value in the previous list necessary to result in the below value: * 5 10 13 16 21 30 45 * 5 3 3 5 9 15 * -2 0 2 4 6 * 2 2 2 2 * 0 0 0 */ override fun part2(input: List<List<Int>>): Int { return input.sumOf { measure -> val differences = mutableListOf(measure) var currentDiff = measure while (currentDiff.any { it != 0 }) { currentDiff = currentDiff.windowed(2).map { (a, b) -> b - a } differences.add(currentDiff) } differences.map { it.first() } .reversed() .reduce { a,b -> b - a } } } fun parseInput(input: String): List<List<Int>> { return input.lines().map { line -> line.split(" ").map { it.toInt() } } } override fun warmup(input: List<List<Int>>) { part1(input) } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day9().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
2,400
advent2023
The Unlicense
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[47]全排列 II.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.collections.ArrayList //给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。 // // // // 示例 1: // // //输入:nums = [1,1,2] //输出: //[[1,1,2], // [1,2,1], // [2,1,1]] // // // 示例 2: // // //输入:nums = [1,2,3] //输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] // // // // // 提示: // // // 1 <= nums.length <= 8 // -10 <= nums[i] <= 10 // // Related Topics 数组 回溯算法 // 👍 734 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun permuteUnique(nums: IntArray): List<List<Int>> { //递归 回溯剪枝 dfs 重点是先排序数组 好判断是否重复剪枝 var res = ArrayList<ArrayList<Int>>() Arrays.sort(nums) var isUse = BooleanArray(nums.size) dfs(0,isUse,nums.size,nums,LinkedList<Int>(),res) return res } private fun dfs(index: Int, use: BooleanArray, size: Int, nums: IntArray, stack: LinkedList<Int>, res: java.util.ArrayList<java.util.ArrayList<Int>>) { //递归结束条件 if(index == size){ res.add(ArrayList(stack)) } //逻辑处理进入下层循环 for (i in nums.indices){ //剪枝 是否已经使用 或者是否重复数 if(use[i]) continue //如果没有使用该数 并且该数与上一个数相等 重复 跳过 if(i > 0 &&(nums[i] == nums[i-1]) && !use[i-1]) continue //正常处理逻辑 回溯 use[i] = true stack.addLast(nums[i]) dfs(index+1,use,size,nums,stack,res) //回溯 use[i] = false stack.removeLast() } //数据reverse } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,892
MyLeetCode
Apache License 2.0
src/Day02_part2.kt
jmorozov
573,077,620
false
{"Kotlin": 31919}
import java.util.EnumMap fun main() { val inputData = readInput("Day02") var myTotalScore = 0 for (line in inputData) { val trimmedLine = line.trim() val opponent = Shape.from(trimmedLine.take(1)) val roundOutcome = RoundOutcome.from(trimmedLine.takeLast(1)) val roundOutcomePoints = roundOutcome.point val shapePoints = Shape.chooseForOpponentAndRoundOutcome(opponent, roundOutcome).point myTotalScore += shapePoints + roundOutcomePoints } println("My total score: $myTotalScore") } enum class Shape(val point: Int) { ROCK(1), PAPER(2), SCISSORS(3), UNKNOWN(0); companion object { private val defeat: EnumMap<Shape, Shape> = EnumMap(mapOf( ROCK to SCISSORS, PAPER to ROCK, SCISSORS to PAPER, UNKNOWN to UNKNOWN )) private val win: EnumMap<Shape, Shape> = EnumMap(mapOf( ROCK to PAPER, PAPER to SCISSORS, SCISSORS to ROCK, UNKNOWN to UNKNOWN )) fun from(str: String): Shape = when (str) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS else -> UNKNOWN } fun chooseForOpponentAndRoundOutcome(opponent: Shape, roundOutcome: RoundOutcome): Shape = when (roundOutcome) { RoundOutcome.LOST -> defeat[opponent] ?: UNKNOWN RoundOutcome.DRAW -> opponent RoundOutcome.WON -> win[opponent] ?: UNKNOWN } } } enum class RoundOutcome(val point: Int) { LOST(0), DRAW(3), WON(6); companion object { fun from(str: String): RoundOutcome = when (str) { "X" -> LOST "Y" -> DRAW "Z" -> WON else -> LOST } } }
0
Kotlin
0
0
480a98838949dbc7b5b7e84acf24f30db644f7b7
1,839
aoc-2022-in-kotlin
Apache License 2.0
dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestNQueens.kt
tuProlog
230,784,338
false
{"Kotlin": 3879230, "Java": 18690, "ANTLR": 10366, "CSS": 1535, "JavaScript": 894, "Prolog": 818}
package it.unibo.tuprolog.dsl.solve import it.unibo.tuprolog.core.Integer import it.unibo.tuprolog.core.Tuple import it.unibo.tuprolog.solve.Solution import kotlin.test.Test import kotlin.test.assertEquals class TestNQueens { private val solutions = listOf( listOf((1 to 3), (2 to 1), (3 to 4), (4 to 2)), listOf((1 to 2), (2 to 4), (3 to 1), (4 to 3)), ) private fun nQueens(n: Int): Sequence<List<Pair<Int, Int>>> = prolog { staticKb( rule { "no_attack"(("X1" and "Y1"), ("X2" and "Y2")) `if` ( ("X1" arithNeq "X2") and ("Y1" arithNeq "Y2") and (("Y2" - "Y1") arithNeq ("X2" - "X1")) and (("Y2" - "Y1") arithNeq ("X1" - "X2")) ) }, fact { "no_attack_all"(`_`, emptyList) }, rule { "no_attack_all"("C", consOf("H", "Hs")) `if` ( "no_attack"("C", "H") and "no_attack_all"("C", "Hs") ) }, fact { "solution"(`_`, emptyList) }, rule { "solution"("N", consOf(("X" and "Y"), "Cs")) `if` ( "solution"("N", "Cs") and between(1, "N", "Y") and "no_attack_all"(("X" and "Y"), "Cs") ) }, ) solve("solution"(n, (1..n).map { it and "Y$it" })) .filterIsInstance<Solution.Yes>() .map { it.solvedQuery[1].castToRecursive() } .map { it.toList() } .map { list -> list.map { it as Tuple } .map { (it.left as Integer).value.toIntExact() to (it.right as Integer).value.toIntExact() } } } @Test fun testNQueens() { nQueens(4).forEachIndexed { i, actual -> assertEquals(solutions[i], actual) } } }
71
Kotlin
13
79
804e57913f072066a4e66455ccd91d13a5d9299a
2,184
2p-kt
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day271/day271.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day271 // day271.kt // <NAME>, 20202. import kotlin.math.min // Use a technique called the Fibonacci search. // https://en.wikipedia.org/wiki/Fibonacci_search_technique fun List<Int>.fibContains(x: Int): Boolean { if (x > last() || x < first()) return false val n: Int = this.size // We are trying to find t. // 1. q is the smallest fib # greater than or equal to the size of the array, i.e. fib(q) >= list.length && // if fib(p) >= list.length, then fib(p) >= fib(q). // Let p, q be consecutive numbers. // * If x == array[p], we have found the element. // * If x < array[p], move p and q down two indices each. // * If x > array[p], move p and q down one each index each, but add an offset of p to the net search term? fun fibonacci() = generateSequence(Pair(0, 1), { Pair(it.second, it.first + it.second) }).map{ it.first } // Get the fibonacci sequence with its indices. // We need one extra term to get the first term q such that F_q > n. // We have an issue between it.value > / >= b and qTerm / qTerm + 1 with the first element. // To resolve it, if this is the first element in the list, return true. if (this[0] == x) return true val fibs = fibonacci().takeWhile { it < n }.withIndex().toList() // We use a tailrec look to traverse the array by fib numbers so we can achieve O(log n) performance. tailrec fun aux(p: Int, q: Int, offset: Int = 0): Boolean { if (q <= 0) return false val index = min(offset + fibs[p].value, n - 1) require(index >= 0){"index is $index, offset is $offset"} return when { x == this[index] -> true x < this[index] -> aux(p - 2, q - 2, offset) else -> aux(p - 1, q - 1, index) } } return aux(fibs.size - 2, fibs.size - 1) }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,897
daily-coding-problem
MIT License
src/main/kotlin/d11/D11_2.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d11 import input.Input import kotlin.math.abs fun findEmptyRows(universe: List<String>): List<Int> { val empty = mutableListOf<Int>() for (i in universe.indices) { if (universe[i].all { it == '.' }) { empty.add(i) } } return empty } fun findEmptyCols(universe: List<String>): List<Int> { val empty = mutableListOf<Int>() for (i in universe[0].indices) { val col = universe.map { it[i] }.joinToString("") if (col.all { it == '.' }) { empty.add(i) } } return empty } fun findDistanceComplex(g1: Galaxy, g2: Galaxy, emptyRows: List<Int>, emptyCols: List<Int>): Long { val loc1 = g1.loc val loc2 = g2.loc var distance: Long = (abs(loc1.first - loc2.first) + abs(loc1.second - loc2.second)).toLong() emptyRows.forEach { if (it.between(loc1.first, loc2.first)) { distance += 999_999 } } emptyCols.forEach { if (it.between(loc1.second, loc2.second)) { distance += 999_999 } } return distance } fun Int.between(a: Int, b: Int): Boolean { return this in a..b || this in b..a } fun main() { val universe = Input.read("input.txt") val emptyRows = findEmptyRows(universe) val emptyCols = findEmptyCols(universe) val galaxies = findGalaxies(universe) val pairs = findPairs(galaxies) var sum = 0L pairs.forEach { sum += findDistanceComplex(it.first, it.second, emptyRows, emptyCols) } println(sum) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
1,537
aoc2023-kotlin
MIT License
src/main/aoc2018/Day15.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2018 import AMap import Pos import Search class Day15(val input: List<String>) { data class Player(val team: PlayerType, var pos: Pos, var attackPower: Int = 3, var hp: Int = 200) { fun isAlive() = hp > 0 } enum class PlayerType(val symbol: Char) { ELF('E'), GOBLIN('G') } class Graph(val map: AMap) : Search.WeightedGraph<Pos> { override fun neighbours(id: Pos): List<Pos> { return id.allNeighbours().filter { map[it] == '.' } } override fun cost(from: Pos, to: Pos): Float { // Need to use fractions that are powers of two to avoid rounding errors when summing cost (floats). return when { from.y - to.y == 1 -> 1 + 1 / 1024f // up from.x - to.x == 1 -> 1 + 2 / 1024f // left from.x - to.x == -1 -> 1 + 3 / 1024f // right from.y - to.y == -1 -> 1 + 4 / 1024f // down else -> error("moving to invalid position") } } } private val players = mutableListOf<Player>() private val map = AMap() private val graph = Graph(map) private var lastAction = "Start of game" // Only used for debugging init { for (y in input.indices) { for (x in input[0].indices) { val char = input[y][x] val pos = Pos(x, y) map[pos] = char when (char) { 'G' -> players.add(Player(PlayerType.GOBLIN, pos)) 'E' -> players.add(Player(PlayerType.ELF, pos)) } } } } fun playerAt(pos: Pos) = players.find { it.pos == pos && it.isAlive() } fun printableMap(withHp: Boolean = false): List<String> { val ret = mutableListOf<String>() for (y in 0..map.keys.maxByOrNull { it.y }!!.y) { val hp = mutableListOf<Pair<Char, Int>>() ret.add("") for (x in 0..map.keys.maxByOrNull { it.x }!!.x) { val pos = Pos(x, y) val char = map[pos]!! ret[y] = ret[y] + char if (listOf('G', 'E').contains(char)) { val p = players.find { it.pos == pos && it.isAlive() }!! hp.add(Pair(p.team.symbol, p.hp)) } } if (withHp) { val hpStrings = hp.map { "${it.first}(${it.second})" } ret[y] = "${ret[y]} ${hpStrings.joinToString(", ")}" } } return ret } private fun move(player: Player, to: Pos) { map[player.pos] = '.' map[to] = player.team.symbol player.pos = to } private fun attack(player: Player) { val target = players.filter { it.team != player.team && it.isAlive() && player.pos isAdjacentTo it.pos } .sortedWith(compareBy({ it.pos.y }, { it.pos.x })) // If many adjacent and same hp, do reading order .minByOrNull { it.hp }!! target.hp -= player.attackPower if (target.hp <= 0) { map[target.pos] = '.' } lastAction = "${player.team} at ${player.pos} attacks ${target.team} (hp left: ${target.hp}) at ${target.pos}" } // Returns true if combat ends fun takeTurn(player: Player): Boolean { // Identify all possible targets, sorted by closest first as that likely leads to cheaper cost val targets = players.filter { it.team != player.team && it.isAlive() } .sortedBy { player.pos.distanceTo(it.pos) } // If no targets remain, combat ends if (targets.isEmpty()) { lastAction = "${player.team} at ${player.pos} finds no targets, game ends" return true } // If adjacent to at least one target, attack without moving if (targets.any { enemy -> player.pos isAdjacentTo enemy.pos }) { attack(player) lastAction += " without moving" return false } // Find all adjacent open spaces next to all targets val possibleTargets = targets.flatMap { enemy -> enemy.pos.allNeighbours().filter { map[it] == '.' } } // Find the position to move to var cheapestSoFar = Float.MAX_VALUE var posToMoveTo: Pos? = null for (target in possibleTargets) { // Only find the shortest path to positions that are theoretically possible to reach if (player.pos.distanceTo(target) < cheapestSoFar) { // Optimization: Abort search when cost becomes higher than the cheapest path so far val result = Search.djikstra(graph, player.pos, target, maxCost = cheapestSoFar) val cost = result.cost[target] if (cost != null && cost < cheapestSoFar) { cheapestSoFar = cost posToMoveTo = result.getPath(target).first() } } } if (posToMoveTo == null) { // No reachable open spaces, end turn lastAction = "${player.team} at ${player.pos} does nothing" return false } val posBeforeMove = player.pos // Move to the selected position move(player, posToMoveTo) // If in range of enemy, attack if (targets.any { enemy -> player.pos isAdjacentTo enemy.pos }) { attack(player) lastAction += " after moving from $posBeforeMove" } else { lastAction = "${player.team} moved from $posBeforeMove to ${player.pos}" } return false } // Returns true if combat ends fun doRound(): Boolean { players.filter { it.isAlive() } .sortedWith(compareBy({ it.pos.y }, { it.pos.x })) .forEach { player -> if (player.isAlive()) { val ends = takeTurn(player) if (ends) { return true } } } return false } private fun playGame(): Int { var round = 1 while (true) { val ends = doRound() if (ends) { return round - 1 } round++ if (round > 1000) { println("Bailing out after 1000 rounds") return -1 } } } private fun scoreForRounds(rounds: Int): Int { return rounds * players.filter { it.isAlive() }.sumOf { it.hp } } fun solvePart1(): Int { val rounds = playGame() return scoreForRounds(rounds) } private fun playWithPower(power: Int): Pair<Int, Int> { val game = Day15(input) game.players.filter { it.team == PlayerType.ELF }.forEach { it.attackPower = power } val rounds = game.playGame() val deadElves = game.players.filter { !it.isAlive() && it.team == PlayerType.ELF }.size return Pair(deadElves, game.scoreForRounds(rounds)) } fun solvePart2(): Int { return binarySearch() } private fun binarySearch(): Int { var tooLow = 4 var highEnough = Int.MAX_VALUE var score = 0 while (tooLow < highEnough - 1) { val toTry = if (highEnough == Int.MAX_VALUE) tooLow * 2 else tooLow + (highEnough - tooLow) / 2 val result = playWithPower(toTry) if (result.first == 0) { highEnough = toTry score = result.second } else { tooLow = toTry } } return score } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
7,676
aoc
MIT License
year2020/day07/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day07/part1/Year2020Day07Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 7: Handy Haversacks --- You land at the regional airport in time for your next flight. In fact, it looks like you'll even have time to grab some food: all flights are currently delayed due to issues in luggage processing. Due to recent aviation regulations, many rules (your puzzle input) are being enforced about bags and their contents; bags must be color-coded and must contain specific quantities of other color-coded bags. Apparently, nobody responsible for these regulations considered how long they would take to enforce! For example, consider the following rules: light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags. These rules specify the required contents for 9 bag types. In this example, every faded blue bag is empty, every vibrant plum bag contains 11 bags (5 faded blue and 6 dotted black), and so on. You have a shiny gold bag. If you wanted to carry it in at least one other bag, how many different bag colors would be valid for the outermost bag? (In other words: how many colors can, eventually, contain at least one shiny gold bag?) In the above rules, the following options would be available to you: - A bright white bag, which can hold your shiny gold bag directly. - A muted yellow bag, which can hold your shiny gold bag directly, plus some other bags. - A dark orange bag, which can hold bright white and muted yellow bags, either of which could then hold your shiny gold bag. - A light red bag, which can hold bright white and muted yellow bags, either of which could then hold your shiny gold bag. So, in this example, the number of bag colors that can eventually contain at least one shiny gold bag is 4. How many bag colors can eventually contain at least one shiny gold bag? (The list of rules is quite long; make sure you get all of it.) */ package com.curtislb.adventofcode.year2020.day07.part1 import com.curtislb.adventofcode.year2020.day07.baggage.BagRules import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 7, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val file = inputPath.toFile() val rules = BagRules(file.readText()) return rules.findBagsContaining("shiny gold").size } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,816
AdventOfCode
MIT License
src/Day11.kt
vlsolodilov
573,277,339
false
{"Kotlin": 19518}
fun main() { val monkeyListTest = listOf<Monkey>( Monkey(0, mutableListOf(79, 98), { old -> old * 19}, 23, 2, 3), Monkey(1, mutableListOf(54, 65, 75, 74), {old -> old + 6}, 19, 2, 0), Monkey(2, mutableListOf(79, 60, 97), {old -> old * old}, 13, 1, 3), Monkey(3, mutableListOf(74), {old -> old + 3}, 17, 0, 1), ) val monkeyList = listOf<Monkey>( Monkey(0, mutableListOf(62, 92, 50, 63, 62, 93, 73, 50), { old -> old * 7}, 2, 7, 1), Monkey(1, mutableListOf(51, 97, 74, 84, 99), {old -> old + 3}, 7, 2, 4), Monkey(2, mutableListOf(98, 86, 62, 76, 51, 81, 95), {old -> old + 4}, 13, 5, 4), Monkey(3, mutableListOf(53, 95, 50, 85, 83, 72), {old -> old + 5}, 19, 6, 0), Monkey(4, mutableListOf(59, 60, 63, 71), { old -> old * 5}, 11, 5, 3), Monkey(5, mutableListOf(92, 65), { old -> old * old}, 5, 6, 3), Monkey(6, mutableListOf(78), { old -> old + 8}, 3, 0, 7), Monkey(7, mutableListOf(84, 93, 54), { old -> old + 1}, 17, 2, 1), ) fun startRound(monkeys: List<Monkey>, worryDivider: Int) { val commonDivisor = monkeys.map { it.divisibleBy }.reduce(Long::times) monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { monkey.inspectedItems++ var item = monkey.items.removeFirst() item = monkey.operation(item) / worryDivider % commonDivisor val toMonkey = if (item % monkey.divisibleBy == 0L) { monkey.firstMonkey } else { monkey.secondMonkey } monkeys[toMonkey].items.add(item) } } } fun part1(monkeys: List<Monkey>): Long { val monkeysCopy = monkeys.map { it.copy() }.toMutableList() repeat(20) { startRound(monkeysCopy, 3) } return monkeysCopy.map { it.inspectedItems }.sortedDescending().take(2).reduce(Long::times) } fun part2(monkeys: List<Monkey>): Long { val monkeysCopy = monkeys.map { it.copy() }.toMutableList() repeat(10_000) { startRound(monkeysCopy, 1) } return monkeysCopy.map { it.inspectedItems }.sortedDescending().take(2).reduce(Long::times) } // test if implementation meets criteria from the description, like: check(part1(monkeyListTest) == 10605L) check(part2(monkeyListTest) == 2_713_310_158L) println(part1(monkeyList)) println(part2(monkeyList)) } data class Monkey( val name: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val divisibleBy: Long, val firstMonkey: Int, val secondMonkey: Int, var inspectedItems: Long = 0, )
0
Kotlin
0
0
b75427b90b64b21fcb72c16452c3683486b48d76
2,755
aoc22
Apache License 2.0
src/main/kotlin/day05/Problem.kt
xfornesa
572,983,494
false
{"Kotlin": 18402}
package day05 import java.util.* fun solveProblem01(input: List<String>): String { val stackInput = Stack<String>() val movements = mutableListOf<String>() var stackHalf = true for (value in input) { if (value.isEmpty()) { stackHalf = false continue } if (stackHalf) { stackInput.push(value) } else { movements.add(value) } } val stacks = buildInitialStack(stackInput) for (movement in movements) { val (num, from, to) = parseMovement(movement) repeat(num) { val value = stacks[from]?.pop() stacks[to]?.push(value) } } return (1..stacks.size) .mapNotNull { stacks[it]?.pop() } .joinToString("") } fun parseMovement(movement: String): List<Int> { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() val matchResult = regex.find(movement) val destructured = matchResult!!.destructured return destructured.toList().map { it.toInt() } } fun buildInitialStack(stackInput: Stack<String>): MutableMap<Int, Stack<String>> { val result = mutableMapOf<Int, Stack<String>>() val keys = stackInput .pop() .trim().split("\\s+".toRegex()) .map { it.toInt() } keys .forEach { result[it] = Stack<String>() } val rowLength = keys.count()*4 - 1 for (value in stackInput.reversed()) { val row = value.padEnd(rowLength) row.asSequence() .windowed(3, 4) .forEachIndexed { index, letters -> val letter = letters.filter { it.isLetter() }.joinToString("") if (letter.isNotBlank()) { result[index+1]?.push(letter) } } } return result } fun solveProblem02(input: List<String>): String { val stackInput = Stack<String>() val movements = mutableListOf<String>() var stackHalf = true for (value in input) { if (value.isEmpty()) { stackHalf = false continue } if (stackHalf) { stackInput.push(value) } else { movements.add(value) } } val stacks = buildInitialStack(stackInput) for (movement in movements) { val (num, from, to) = parseMovement(movement) val temp = Stack<String>() repeat(num) { val value = stacks[from]?.pop() temp.push(value) } repeat(num) { val value = temp.pop() stacks[to]?.push(value) } } return (1..stacks.size) .mapNotNull { stacks[it]?.pop() } .joinToString("") }
0
Kotlin
0
0
dc142923f8f5bc739564bc93b432616608a8b7cd
2,733
aoc2022
MIT License
app/src/main/java/com/canerkorkmaz/cicek/jobdistribution/model/Solution.kt
nberktumer
173,110,988
false
{"Kotlin": 47340}
package com.canerkorkmaz.cicek.jobdistribution.model import com.canerkorkmaz.cicek.jobdistribution.util.sum import com.canerkorkmaz.cicek.jobdistribution.util.sumByDouble data class Solution( val store: StoreData, val jobs: Set<JobData> ) { val isValid by lazy { store.min <= jobs.size && jobs.size <= store.max } val cost by lazy { jobs.sumByDouble { store.distanceSqr(it) } } } data class SolutionPack( val stores: Map<String, Solution>, val data: InputDataFormatted ) { val isValid by lazy { stores.all { entry -> entry.value.isValid } && data.jobList.size == stores.sum { _, solution -> solution.jobs.size } } val totalCost by lazy { stores.sumByDouble { _, sol -> sol.cost } } override fun toString(): String { return "Solution is ${if (isValid) "valid" else "invalid"}, cost is $totalCost" } fun printWithExtraDetails(): String { val builder = StringBuilder() for ((storeName, solution) in stores) { builder.append("Store ").append(storeName).append(": ") .append(solution.jobs.size).append(" jobs: \n") .append(solution.jobs.joinToString(separator = ", ", prefix = "[", postfix = "]", transform = { it.id.toString() })) .append("\n") } return builder.toString() } }
0
Kotlin
0
0
bd3356d1dcd0da1fa4a4ed5967205ea488724d3a
1,428
CicekSepeti-Hackathon
Apache License 2.0