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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day14/NanoFactory.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019.day14
import kotlin.math.max
class NanoFactory(private val recipes: Map<String, Pair<Long, List<Chemical>>>) {
fun calculateTotalOresRequiredToMakeFuel() = requiredOre(Chemical("FUEL", 1), mutableMapOf())
fun calculateFuelGeneratedByOneTrillionOres(): Long {
var l = 0L
var r = TRILLION
var best = 0L
while (l <= r) {
val m = (l + r) / 2
val result = requiredOre(Chemical("FUEL", m), mutableMapOf())
when {
result < TRILLION -> {
l = m + 1
best = m
}
result > TRILLION -> r = m - 1
else -> return m
}
}
return best
}
private fun requiredOre(chemical: Chemical, surplus: MutableMap<String, Long>): Long {
val (product, quantity) = chemical.name to chemical.quantity
val (recipeQuantity, ingredients) = recipes[product] ?: error("Could not find recipe for $chemical")
val existing = surplus[product] ?: 0
val required = quantity - existing
val multiplier = (max(required, 0) + recipeQuantity - 1) / recipeQuantity
val used = recipeQuantity * multiplier
val extra = used - required
surplus[product] = extra
return ingredients.fold(0L) { acc, ingredient ->
acc + if (ingredient.name == "ORE") {
multiplier * ingredient.quantity
} else {
requiredOre(Chemical(ingredient.name, multiplier * ingredient.quantity), surplus)
}
}
}
companion object {
const val TRILLION = 1_000_000_000_000L
fun parse(input: String) =
NanoFactory(
input.lines()
.map { line ->
val (input, output) = line.split("=>")
val target = Chemical.parse(output.trim())
val ingredients = input.split(',').map { Chemical.parse(it.trim()) }.toList()
target.name to Pair(target.quantity, ingredients)
}.toMap()
)
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 2,205 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day11.kt | TheMrMilchmann | 571,779,671 | false | {"Kotlin": 56525} | /*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
fun main() {
class Monkey(
val startingItems: List<Long>,
val operation: (Long) -> Long,
val testDivisor: Int,
val findTarget: (Long) -> Int
)
val monkeys = readInput().asSequence()
.filter { it.isNotBlank() }
.chunked(size = 6) { lines ->
val startingItems = lines[1].trim().removePrefix("Starting items: ").split(", ").map(String::toLong)
val operation: (Long) -> Long = lines[2].trim().removePrefix("Operation: new = old ").let { src ->
val op: Long.(Long) -> Long = when (src[0]) {
'+' -> Long::plus
'*' -> Long::times
else -> error("Unknown operation: $src")
}
when (val value = src.substring(startIndex = 2)) {
"old" -> {{ it.op(it) }}
else -> {{ it.op(value.toLong()) }}
}
}
val testDivisor = lines[3].substringAfterLast(' ').toInt()
val testPositiveTarget = lines[4].substringAfterLast(' ').toInt()
val testNegativeTarget = lines[5].substringAfterLast(' ').toInt()
val findTarget: (Long) -> Int = { if (it % testDivisor == 0L) testPositiveTarget else testNegativeTarget }
Monkey(
startingItems,
operation,
testDivisor,
findTarget
)
}.toList()
fun solve(rounds: Int, reduceWorryLevel: (Long) -> Long): Long {
val inspections = IntArray(monkeys.size)
val inventories = List(monkeys.size) { ArrayList(monkeys[it].startingItems) }
repeat(rounds) {
monkeys.forEachIndexed { index, monkey ->
val items = inventories[index]
inspections[index] += items.size
val itr = items.iterator()
while (itr.hasNext()) {
var item = itr.next()
itr.remove()
item = monkey.operation(item)
item = reduceWorryLevel(item)
val target = monkey.findTarget(item)
inventories[target].add(item)
}
}
}
return inspections.sortedDescending().take(2).map(Int::toLong).reduce(Long::times)
}
println("Part 1: ${solve(20) { it / 3 }}")
val base = monkeys.map(Monkey::testDivisor).reduce(Int::times)
println("Part 2: ${solve(10_000) { it % base }}")
} | 0 | Kotlin | 0 | 1 | 2e01ab62e44d965a626198127699720563ed934b | 3,668 | AdventOfCode2022 | MIT License |
src/Day06.kt | kuolemax | 573,740,719 | false | {"Kotlin": 21104} | fun main() {
fun part1(input: List<String>): Int {
return findFourDifferentCharactersInARow(input[0], 4)
}
fun part2(input: List<String>): Int {
return findFourDifferentCharactersInARow(input[0], 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
private fun findFourDifferentCharactersInARow(str: String, size: Int): Int {
val chars = str.toCharArray()
var differentCharacter = mutableListOf<Char>()
var index = 0
while (differentCharacter.size < size){
val it = chars[index]
val sameCharacterIndex = differentCharacter.indexOf(it)
if (sameCharacterIndex != -1) {
differentCharacter = differentCharacter.subList(sameCharacterIndex + 1, differentCharacter.size)
}
differentCharacter.add(it)
index++
}
return index
}
| 0 | Kotlin | 0 | 0 | 3045f307e24b6ca557b84dac18197334b8a8a9bf | 1,065 | aoc2022--kotlin | Apache License 2.0 |
src/main/kotlin/aoc22/Day11.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc22
import common.Collections.partitionedBy
import common.Collections.product
import aoc22.Day11Solution.part1Day11
import aoc22.Day11Solution.part2Day11
import aoc22.Day11Domain.Item
import aoc22.Day11Domain.Monkey
import aoc22.Day11Parser.toMonkeys
import aoc22.Day11Runner.doRounds
import common.Year22
object Day11: Year22 {
fun List<String>.part1(): Long = part1Day11()
fun List<String>.part2(): Long = part2Day11()
}
object Day11Solution {
fun List<String>.part1Day11(): Long =
toMonkeys(reliefDivisor = 3)
.doRounds(times = 20)
.productOfInspectedTimes(top = 2)
fun List<String>.part2Day11(): Long =
toMonkeys(reliefDivisor = 1)
.doRounds(times = 10000)
.productOfInspectedTimes(top = 2)
private fun Monkeys.productOfInspectedTimes(top: Int): Long =
map { it.inspectedTimes }
.sortedBy { it }
.takeLast(top)
.product()
}
private typealias Monkeys = List<Monkey>
object Day11Runner {
fun Monkeys.doRounds(times: Int): Monkeys =
apply {
repeat(times) {
this.forEach { monkey ->
val itemsToThrow =
generateSequence {
monkey.items.removeFirstOrNull()?.let { item ->
with(monkey) {
item
.inspect()
.getBored()
.reduceWorryLevel(using = productOftestDivisibleBy())
.let { inspected -> inspected to targetMonkeyFor(inspected) }
}
}
}
itemsToThrow.forEach { (item, targetMonkey) ->
this.throwItem(item = item, toMonkey = targetMonkey)
}
}
}
}
private fun Monkeys.throwItem(item: Item, toMonkey: Int) {
this[toMonkey].items.add(item)
}
private fun Monkeys.productOftestDivisibleBy() = map { it.testDivisibleBy }.product()
}
object Day11Domain {
data class Item(
// only used with % testDivisibleBy to work out where to throw an item
// reduce with % of testDivisibleBy lcm to make it a manageable size in part 2
// continues to work with % testDivisibleBy because of maths
val worryLevel: Long,
)
data class Monkey(
val items: MutableList<Item>,
val operationParts: List<String>,
val testDivisibleBy: Int,
val monkeyTrue: Int,
val monkeyFalse: Int,
var inspectedTimes: Long,
val reliefDivisor: Int,
) {
fun Item.inspect(): Item = this@Monkey.operation(this, operationParts).also { inspectedTimes++ }
fun Item.getBored(): Item = this.copy(worryLevel = (this.worryLevel / reliefDivisor))
fun Item.reduceWorryLevel(using: Int?): Item = using?.let { copy(worryLevel = this.worryLevel % it) } ?: this
fun targetMonkeyFor(item: Item): Int = if (item.test()) monkeyTrue else monkeyFalse
private fun Item.test(): Boolean = worryLevel % testDivisibleBy == 0L
private fun operation(item: Item, operationParts: List<String>): Item {
fun String.toLongWith(item: Item): Long = if (this == "old") item.worryLevel else this.toLong()
val first = operationParts[0].toLongWith(item)
val operator = operationParts[1]
val second = operationParts[2].toLongWith(item)
return when {
operator == "*" -> first * second
operator == "+" -> first + second
else -> error("dunno")
}.let(::Item)
}
}
}
object Day11Parser {
fun List<String>.toMonkeys(reliefDivisor: Int): Monkeys =
partitionedBy("").map { monkeyText ->
val trimmed = monkeyText.map(String::trim)
Monkey(
items = trimmed[1].replace("Starting items: ", "").split(", ").map { Item(it.toLong()) }.toMutableList(),
operationParts = trimmed[2].replace("Operation: new = ", "").split(" "),
testDivisibleBy = trimmed[3].replace("Test: divisible by ", "").toInt(),
monkeyTrue = trimmed[4].replace("If true: throw to monkey ", "").toInt(),
monkeyFalse = trimmed[5].replace("If false: throw to monkey ", "").toInt(),
inspectedTimes = 0L,
reliefDivisor = reliefDivisor,
)
}
} | 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 4,660 | aoc | Apache License 2.0 |
src/Day03.kt | erwinw | 572,913,172 | false | {"Kotlin": 87621} | @file:Suppress("MagicNumber")
private const val DAY = "03"
private const val PART1_CHECK = 157
private const val PART2_CHECK = 70
fun String.toCompartments(): List<String> =
(length / 2).let {
listOf(take(it), drop(it))
}
fun itemPriority(item: Char): Int =
when (item) {
in 'a'..'z' -> item.code - 'a'.code + 1
in 'A'..'Z' -> item.code - 'A'.code + 27
else -> throw IllegalArgumentException("Item '${item}' out of range")
}
fun main() {
fun part1(input: List<String>): Int =
input.sumOf { ruckSack ->
ruckSack.toCompartments()
.map(String::toSet)
.reduce(Iterable<Char>::intersect)
.sumOf(::itemPriority)
}
fun part2(input: List<String>): Int =
input.chunked(3)
.sumOf { rucksacks ->
rucksacks.map(String::toSet)
.reduce(Iterable<Char>::intersect)
.sumOf(::itemPriority)
}
println("Day $DAY")
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${DAY}_test")
check(part1(testInput).also { println("Part1 output: $it") } == PART1_CHECK)
check(part2(testInput).also { println("Part2 output: $it") } == PART2_CHECK)
val input = readInput("Day$DAY")
println("Part1 final output: ${part1(input)}")
println("Part2 final output: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 57cba37265a3c63dea741c187095eff24d0b5381 | 1,450 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day05.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2021
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
import at.mpichler.aoc.lib.Vector2i
import at.mpichler.aoc.lib.max
import org.jetbrains.kotlinx.multik.api.mk
import org.jetbrains.kotlinx.multik.api.zeros
import org.jetbrains.kotlinx.multik.ndarray.data.D2Array
import org.jetbrains.kotlinx.multik.ndarray.data.get
import org.jetbrains.kotlinx.multik.ndarray.data.set
import org.jetbrains.kotlinx.multik.ndarray.operations.map
open class Part5A : PartSolution() {
lateinit var lines: List<Line>
override fun parseInput(text: String) {
lines = text.split("\n")
.map { getPoints(it) }
.map { Line(it.first, it.second) }
}
private fun getPoints(line: String): Pair<Vector2i, Vector2i> {
val result = Regex("""(\d+),(\d+) -> (\d+),(\d+)""").find(line)
val (x1, y1, x2, y2) = result!!.destructured
val p1 = Vector2i(x1.toInt(), y1.toInt())
val p2 = Vector2i(x2.toInt(), y2.toInt())
return Pair(p1, p2)
}
override fun compute(): Int {
val (width, height) = getFieldSize()
val diagram = mk.zeros<Int>(width, height)
lines.filter { it.isHV }.forEach { it.paint(diagram) }
return mk.math.sum(diagram.map { if (it > 1) 1 else 0 })
}
fun getFieldSize(): Pair<Int, Int> {
val max = lines.flatMap { listOf(it.from, it.to) }
.reduce { acc, it -> max(acc, it) }
return Pair(max.x + 1, max.y + 1)
}
override fun getExampleAnswer(): Int {
return 5
}
data class Line(val from: Vector2i, val to: Vector2i) {
val isHV get() = from.x == to.x || from.y == to.y
fun paint(diagram: D2Array<Int>) {
val direction = (to - from).sign()
var pos = from
diagram[pos.x, pos.y] += 1
while (pos != to) {
pos += direction
diagram[pos.x, pos.y] += 1
}
}
}
}
class Part5B : Part5A() {
override fun compute(): Int {
val (width, height) = getFieldSize()
val diagram = mk.zeros<Int>(width, height)
lines.forEach { it.paint(diagram) }
return mk.math.sum(diagram.map { if (it > 1) 1 else 0 })
}
override fun getExampleAnswer(): Int {
return 12
}
}
fun main() {
Day(2021, 5, Part5A(), Part5B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 2,402 | advent-of-code-kotlin | MIT License |
calendar/day04/Day4.kt | divgup92 | 726,169,029 | false | {"Kotlin": 16931} | package day04
import Day
import Lines
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
class Day4 : Day() {
override fun part1(input: Lines): Any {
var sum = 0
for(line in input) {
val lineSplit = line.split(":", "|")
val winningNums = lineSplit[1].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
val myNums = lineSplit[2].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
var matching = 0
for(winningNum in winningNums) {
if(myNums.contains(winningNum)) {
matching++
}
}
val two = 2.0
sum += two.pow(matching-1).toInt()
println("$matching $sum")
}
return sum
}
override fun part2(input: Lines): Any {
var sum = 0
val numCardMap = mutableMapOf<Int, Int>()
for(i in 1..input.size) {
numCardMap[i] = 1
}
for(line in input) {
val lineSplit = line.split(":", "|")
val cardNum = lineSplit[0].filter { it.isDigit() }.toInt()
if(cardNum == input.size) {
break
}
val winningNums = lineSplit[1].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
val myNums = lineSplit[2].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
var matching = 0
for(winningNum in winningNums) {
if(myNums.contains(winningNum)) {
matching++
}
}
val base = numCardMap[cardNum]
for(i in min(cardNum+1, input.size)..min(input.size, cardNum+matching)) {
print("$i,$cardNum ")
numCardMap[i] = numCardMap[i]!! + base!!
}
println()
}
println(numCardMap)
return numCardMap.values.sum()
}
} | 0 | Kotlin | 0 | 0 | 38dbf3b6eceea8d5b0eeab82b384acdd0c205852 | 1,941 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/io/undefined/BestTimeToBuyAndSellStock.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.undefined
import io.utils.runTests
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
class BestTimeToBuyAndSellStock {
fun execute(input: IntArray): Int {
if (input.isEmpty()) return 0
val maximums = run {
var max = Int.MIN_VALUE
input.indices.map { index -> maxOf(input[input.lastIndex - index], max).also { max = it } }.reversed()
}
val minimums = run {
var min = Int.MAX_VALUE
input.map { value -> minOf(min, value).also { min = it } }
}
var max = 0
(1 until input.size).forEach { index ->
max = maxOf(maximums[index] - minimums[index], max)
}
return max
}
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solution/
fun maxProfit(prices: IntArray): Int {
var minprice = Int.MAX_VALUE
var maxprofit = 0
for (i in prices.indices) {
when {
prices[i] < minprice -> minprice = prices[i]
prices[i] - minprice > maxprofit -> maxprofit = prices[i] - minprice
}
}
return maxprofit
}
}
fun main() {
runTests(listOf(
intArrayOf(7, 1, 5, 3, 6, 4) to 5
)) { (input, value) -> value to BestTimeToBuyAndSellStock().execute(input) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,203 | coding | MIT License |
TwoSum.kt | sammyHa | 188,499,821 | false | null | /**
@author <NAME>
5/24/2019 4:36 AM
*/
/**
*
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true or print the indices of the two values in the list since 10 + 7 is 17.
*/
/**
* Time complexity: O(n) we iterate through the list only once.
* Space complexity: O(1) because we are not using any auxiliary data structure.
*/
fun twoSum(nums: List<Int>, target: Int):Boolean{
var i = 0 // i starts at the index zero
var j = nums.size - 1 // j start at the last index
while (i<= j){
if (nums[i] + nums[j] == target){
println("${nums[i]}, ${nums[j]} at index $i, $j")
return true
}else if (nums[i] + nums[j] < target){ // if the value at the index i + j is less than the target goto the next index.
i+= 1
}else{ // if the value at the index i + j is greater than the target decrease (j--)
j -= 1
}
}
return false
}
/**
* Timce complexity: O(n^2)
*/
// fun twoSum(list: List<Int>, k:Int):Boolean{
// for (i in list){
// for (j in list){
// if (i != j && i + j == k){
// return true
// }
// }
// }
// return false
// }
/**
* Time complexity : O(n^2)
* Space complexity: O(n)
*/
// fun twoSum1(list:List<Int>, k:Int):Boolean{
// val seen = mutableListOf<Int>()
// for (i in list){
// if (k - i in seen){
// return true
// }
// seen.add(i)
// }
// return false
// }
/**
* Time complexity : O(n)
* Space complexity: O(n)
*/
// private fun twoSum(nums: IntArray, target:Int):IntArray {
// val hashMap = HashMap<Int, Int>()
// for (i in 0 until nums.size){
// if (hashMap.containsKey(target - nums[i])){
// val intArray = intArrayOf(hashMap.get(target- nums[i])!!, i)
// println(intArray.joinToString ())
// return intArray // return the indexes
// }
// hashMap.put(nums[i], i)
// }
// val intArray = intArrayOf(-1,-1)
// print(intArray.joinToString ())
// return intArray
// }
fun main() {
val nums = intArrayOf(10, 15, 7,4,52,13,1,3)
val lst = listOf(10, 15, 7,4,52,13,1,3)
val target = 53
twoSum(nums, target)
println()
println(twoSum(lst, target))
println(twoSum1(lst, target))
}
| 0 | Java | 0 | 0 | 29e74c19e03fb1e4af5048ed5463f0edcc2f7070 | 2,585 | Coding-Problems | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2023/Day14.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day14(input: List<String>) {
private val platform = Platform(input.toGrid(ignore = '.'))
private class Platform(originalGrid: Grid<Char>) {
private val region = originalGrid.region()
private var roundRockPositions = originalGrid.filterValues { it == 'O' }.keys
private val cubeRockPositions = originalGrid.filterValues { it == '#' }.keys
fun tilt(dir: Direction): Platform {
val movedRocks = mutableSetOf<Vector2>()
// Sort the rocks so we iterate in the ideal order
roundRockPositions
.sortedBy {
when (dir) {
Direction.NORTH -> it.y
Direction.SOUTH -> -it.y
Direction.WEST -> it.x
Direction.EAST -> -it.x
}
}
.forEach { oldPos ->
// Move as far as we can in this direction until we hit something (or reach the edge)
var nextPos = oldPos
while (true) {
val newPos = nextPos + dir.vector()
if (newPos in cubeRockPositions || newPos in movedRocks || newPos !in region) {
break
}
nextPos = newPos
}
movedRocks.add(nextPos)
}
roundRockPositions = movedRocks
return this
}
fun spin(iterations: Int): Platform {
val cycleCache = mutableMapOf<Set<Vector2>, Int>()
var i = 0
while (i < iterations) {
tilt(Direction.NORTH)
tilt(Direction.WEST)
tilt(Direction.SOUTH)
tilt(Direction.EAST)
i++
// Have we seen this exact configuration before? If so, we can skip ahead!
if (roundRockPositions in cycleCache) {
val cycleStart = cycleCache[roundRockPositions]!!
val cycleLength = i - cycleStart
val remainingIterations = (iterations - i) % cycleLength
repeat(remainingIterations) {
tilt(Direction.NORTH)
tilt(Direction.WEST)
tilt(Direction.SOUTH)
tilt(Direction.EAST)
}
break
}
cycleCache[roundRockPositions] = i
}
return this
}
fun calculateTotalLoad() = roundRockPositions.sumOf { region.bottomRight.y - it.y + 1 }
}
fun solvePart1() = platform.tilt(Direction.NORTH).calculateTotalLoad()
fun solvePart2() = platform.spin(1_000_000_000).calculateTotalLoad()
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 2,890 | advent-2023 | MIT License |
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/ReverseBetween.kt | scientificCommunity | 352,868,267 | false | {"Java": 154453, "Kotlin": 69817} | package org.baichuan.sample.algorithms.leetcode.middle
/**
* @author: kuntang (<EMAIL>)
* @date: 2022/4/12
* https://leetcode-cn.com/problems/reverse-linked-list-ii/
*
* 执行用时:136 ms, 在所有 Kotlin 提交中击败了97.62%的用户
* 内存消耗:32.7 MB, 在所有 Kotlin 提交中击败了100.00%的用户
*/
class ReverseBetween {
fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode? {
if (head == null) {
return null
}
if (left == right) {
return head
}
var currIndex = 0
var currNode = head
var preNode: ListNode? = null
var leftNode: ListNode? = head
var rightNode: ListNode?
var reverseRightNode: ListNode? = head
var reverseLeftNode: ListNode? = head
while (currNode != null) {
val nextNode = currNode.next
if (currIndex > left - 2 && currIndex < right) {
if (currIndex == left - 1) {
leftNode = preNode
reverseRightNode = currNode
}
if (currIndex == right - 1) {
rightNode = nextNode
reverseRightNode?.next = rightNode
reverseLeftNode = currNode
leftNode?.next = reverseLeftNode
}
currNode.next = preNode
}
preNode = currNode
currNode = nextNode
currIndex++
}
return if (left == 1) {
reverseLeftNode
} else {
head
}
}
private fun doReverse(head: ListNode?) {
if (head == null) {
return
}
var currNode = head
var preNode: ListNode? = null
while (currNode != null) {
val nextNode = currNode.next
currNode.next = preNode
preNode = currNode
currNode = nextNode
}
}
}
fun main() {
//case 1
val a = ListNode(1)
val b = ListNode(2)
val c = ListNode(3)
val d = ListNode(4)
val e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
val reverseBetween = ReverseBetween()
val reverseBetween1 = reverseBetween.reverseBetween(a, 2, 4)
//case 2
// val a = ListNode(3)
// val b = ListNode(5)
// a.next = b
// val reverseBetween = ReverseBetween()
// val reverseBetween1 = reverseBetween.reverseBetween(a, 1, 2)
println(reverseBetween1)
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
} | 1 | Java | 0 | 8 | 36e291c0135a06f3064e6ac0e573691ac70714b6 | 2,611 | blog-sample | Apache License 2.0 |
src/Day01.kt | kipwoker | 572,884,607 | false | null | fun main() {
fun getStructure(input: List<String>): MutableList<List<Int>> {
val result = mutableListOf<List<Int>>()
var bucket = mutableListOf<Int>()
result.add(bucket)
input.forEach { line ->
run {
if (line.isBlank()) {
bucket = mutableListOf()
result.add(bucket)
} else {
bucket.add(line.toInt())
}
}
}
return result
}
fun part1(input: List<String>): Int {
val structure = getStructure(input)
return structure.maxOf { it.sum() }
}
fun part2(input: List<String>): Int {
val structure = getStructure(input)
return structure
.map { it.sum() }
.sortedByDescending { it }
.take(3)
.sumOf { it }
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 1,056 | aoc2022 | Apache License 2.0 |
src/oop/algorithm/ProgressionNextNumber.kt | jjeda | 517,337,782 | false | {"Kotlin": 27953} | package oop.algorithm
class ProgressionNextNumber {
fun solution(common: IntArray): Int {
return ProgressionHelper(progression = common.toList()).nextInt()
}
}
class ProgressionHelper(
private val progression: List<Int>
) {
fun nextInt(): Int {
val metadata = getMetadata()
val nextNumberGenerator = when (metadata.type) {
ProgressionType.ARITHMETIC -> ArithmeticalProgressionNextNumberGenerator
ProgressionType.GEOMETRIC -> GeometricProgressionNextNumberGenerator
}
return nextNumberGenerator.generateWith(metadata)
}
private fun getMetadata(): ProgressionInformation {
val (first, second) = progression
return if (isArithmetic()) {
ProgressionInformation(progression, ProgressionType.ARITHMETIC, second - first)
} else {
ProgressionInformation(progression, ProgressionType.GEOMETRIC, second / first)
}
}
private fun isArithmetic(): Boolean {
val (first, second, third) = progression
return second * 2 == first + third
}
}
data class ProgressionInformation(
val progression: List<Int>,
val type: ProgressionType,
val distance: Int,
)
enum class ProgressionType {
ARITHMETIC, GEOMETRIC
}
sealed interface ProgressionNextNumberGenerator {
fun generateWith(metadata: ProgressionInformation): Int
}
object ArithmeticalProgressionNextNumberGenerator : ProgressionNextNumberGenerator {
override fun generateWith(metadata: ProgressionInformation) = metadata.progression.last() + metadata.distance
}
object GeometricProgressionNextNumberGenerator : ProgressionNextNumberGenerator {
override fun generateWith(metadata: ProgressionInformation) = metadata.progression.last() * metadata.distance
} | 0 | Kotlin | 0 | 0 | 5d1ee6c2635fd8c1443cfe2b5d56be110dea9c10 | 1,697 | playground | MIT License |
src/main/kotlin/tw/gasol/aoc/aoc2022/Day15.kt | Gasol | 574,784,477 | false | {"Kotlin": 70912, "Shell": 1291, "Makefile": 59} | package tw.gasol.aoc.aoc2022
import java.awt.Point
import java.awt.geom.Path2D
import kotlin.math.abs
import kotlin.math.absoluteValue
class Day15 {
private fun getPairPointList(input: String): List<Pair<Point, Point>> {
val numbersPattern = "[\\d\\-]+"
val regex =
Regex("Sensor at x=($numbersPattern), y=($numbersPattern): closest beacon is at x=($numbersPattern), y=($numbersPattern)")
return input.lines().filterNot { it.isBlank() }.map {
try {
val (x1, y1, x2, y2) = regex.matchEntire(it)!!.destructured
Point(x1.toInt(), y1.toInt()) to Point(x2.toInt(), y2.toInt())
} catch (e: Exception) {
error("Failed to parse $it")
}
}
}
fun part1(input: String, row: Int): Int {
val pairPointsList = getPairPointList(input)
return testCoverage(pairPointsList, row)
}
private fun testCoverage(pairPointsList: List<Pair<Point, Point>>, row: Int): Int {
val points = pairPointsList.flatMap { it.toList() }
var minX = points.minOf { it.x }
var maxX = points.maxOf { it.x }
val rectangles = pairPointsList.map { (sensor, beacon) ->
val size = sensor.distanceTo(beacon)
minX = minOf(minX, sensor.x - size)
maxX = maxOf(maxX, sensor.x + size)
Rectangle(
Point(sensor.x - size, sensor.y),
Point(sensor.x, sensor.y - size),
Point(sensor.x, sensor.y + size + 1),
Point(sensor.x + size + 1, sensor.y)
)
}
var count = 0
for (i in minX..maxX) {
val point = Point(i, row)
if (!points.contains(point) && rectangles.any { it.contains(point) }) {
count++
}
}
return count
}
fun part2(input: String): Long {
val pairPointList = getPairPointList(input)
val validRange = 0..4_000_000
val sensors = pairPointList.map { (sensor, beacon) ->
sensor to sensor.distanceTo(beacon)
}
sensors.forEach { (sensor, distance) ->
val checkPoints = (-distance - 1..distance + 1).flatMap { deltaX ->
val deltaY = distance - deltaX.absoluteValue + 1
listOf(
Point(sensor.x + deltaX, sensor.y - deltaY),
Point(sensor.x + deltaX, sensor.y + deltaY),
).filter { it.x in validRange && it.y in validRange }
}
val distress = checkPoints.firstOrNull { point ->
sensors.all { (sensor, distance) ->
sensor.distanceTo(point) >= distance + 1
}
} ?: return@forEach
return distress.x.toLong() * validRange.last + distress.y
}
return 0
}
}
data class Rectangle(val topLeft: Point, val topRight: Point, val bottomLeft: Point, val bottomRight: Point) {
private val path = Path2D.Double().also {
it.moveTo(topLeft.x.toDouble(), topLeft.y.toDouble())
it.lineTo(topRight.x.toDouble(), topRight.y.toDouble())
it.lineTo(bottomRight.x.toDouble(), bottomRight.y.toDouble())
it.lineTo(bottomLeft.x.toDouble(), bottomLeft.y.toDouble())
it.closePath()
}
fun contains(point: Point) = path.contains(point)
}
fun Point.distanceTo(other: Point): Int {
return abs(this.x - other.x) + abs(this.y - other.y)
}
| 0 | Kotlin | 0 | 0 | a14582ea15f1554803e63e5ba12e303be2879b8a | 3,495 | aoc2022 | MIT License |
advent-of-code/aoc-2023/src/test/kotlin/dev/mikeburgess/adventofcode/Day03.kt | mddburgess | 469,258,868 | false | {"Kotlin": 47737} | package dev.mikeburgess.adventofcode
import dev.mikeburgess.adventofcode.day03.PartNumber
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
class Day03 {
private val input = readInput(3)
private val schematic = LinkedHashMap<Pair<Int, Int>, PartNumber>()
@BeforeTest
fun readSchematic() {
input.forEachIndexed { row, s ->
var part = PartNumber()
s.forEachIndexed { col, c ->
if (c in '0'..'9') {
part.append(c)
schematic[row to col] = part
} else {
part = PartNumber()
}
}
}
}
@Test
fun part1() {
input.forEachIndexed { row, s ->
s.forEachIndexed { col, c ->
if (c != '.' && c !in '0'..'9') {
schematic[row - 1 to col - 1]?.included = true
schematic[row - 1 to col]?.included = true
schematic[row - 1 to col + 1]?.included = true
schematic[row to col - 1]?.included = true
schematic[row to col + 1]?.included = true
schematic[row + 1 to col - 1]?.included = true
schematic[row + 1 to col]?.included = true
schematic[row + 1 to col + 1]?.included = true
}
}
}
val result = schematic.filter { it.value.included }
.values
.distinct()
.sumOf { it.value }
assertEquals(538046, result)
}
@Test
fun part2() {
var result = 0
input.forEachIndexed { row, s ->
s.forEachIndexed { col, c ->
if (c == '*') {
val parts = arrayOf(
schematic[row - 1 to col - 1],
schematic[row - 1 to col],
schematic[row - 1 to col + 1],
schematic[row to col - 1],
schematic[row to col + 1],
schematic[row + 1 to col - 1],
schematic[row + 1 to col],
schematic[row + 1 to col + 1]
).filterNotNull().distinct()
if (parts.size == 2) {
result += parts[0].value * parts[1].value
}
}
}
}
assertEquals(81709807, result)
}
}
| 0 | Kotlin | 0 | 0 | 9ad8f26583b204e875b07782c8d09d9d8b404b00 | 2,499 | code-kata | MIT License |
contest1904/src/main/kotlin/D1.kt | austin226 | 729,634,548 | false | {"Kotlin": 23837} | // https://codeforces.com/contest/1904/problem/D1
private fun String.splitWhitespace() = split("\\s+".toRegex())
private fun readInt(): Int = readln().toInt()
private fun readInts(): List<Int> = readln().splitWhitespace().map { it.toInt() }
fun canABecomeB(n: Int, a: MutableList<Int>, b: List<Int>): Boolean {
// If any b[i] < a[a], return false
if ((0..<n).any { i -> b[i] < a[i] }) {
return false
}
for (g in 0..n) {
for (i in 0..<n) {
if (b[i] == g && a[i] < g) {
// Find an l to the left
var l = i
while (l > 0 && a[l - 1] <= g && b[l - 1] >= g) {
l--
}
// Find r
var r = i
while (r < n - 1 && a[r + 1] <= g && b[r + 1] >= g) {
r++
}
if (!(l..r).any { j -> a[j] == g }) {
return false
}
for (j in l..r) {
a[j] = g
}
}
}
}
return a == b
}
fun main() {
val t = readInt()
(0..<t).forEach { _ ->
val n = readInt()
val a = readInts().toMutableList()
val b = readInts()
// operation: Choose l and r, where 1 <= l <= r <= n
// let x = max(a[l]..a[r])
// Set all a[l]..a[r] to max
// Output YES if a can become b with any number of operations
// Output NO if not
if (canABecomeB(n, a, b)) {
println("YES")
} else {
println("NO")
}
}
}
| 0 | Kotlin | 0 | 0 | 4377021827ffcf8e920343adf61a93c88c56d8aa | 1,606 | codeforces-kt | MIT License |
src/day2/Day02.kt | behnawwm | 572,034,416 | false | {"Kotlin": 11987} | package day2
import day2.Move.*
import day2.WinStatus.*
import readInput
fun main() {
// val fileLines = readInput("day02-test", "day2")
val fileLines = readInput("day02", "day2")
var score = 0
fun parseInput(text: String): Pair<String, String> {
text.split(" ").apply {
return Pair(get(0), get(1))
}
}
fun part1(first: String, second: String) {
val firstMove = first.toMove()
val secondMove = second.toMove()
score += secondMove.getValue()
score +=
if (secondMove == firstMove)
3
else if (secondMove < firstMove)
0
else
6
}
fun part2(first: String, second: String) {
val firstMove = first.toMove()
val winStatus = second.toWinStatus()
score += winStatus.getValue()
val chosenMove = winStatus.getAccordingMove(firstMove)
score += chosenMove.getValue()
}
fileLines.forEach { text ->
val (first, second) = parseInput(text)
// part1(first, second)
part2(first, second)
}
println(score)
}
sealed interface Move : Comparable<Move> {
fun getValue(): Int
object Rock : Move {
override fun getValue(): Int = 1
override fun compareTo(other: Move): Int {
return when (other) {
Rock -> 0
Paper -> -1
Scissors -> 1
}
}
}
object Paper : Move {
override fun getValue(): Int = 2
override fun compareTo(other: Move): Int {
return when (other) {
Rock -> 1
Paper -> 0
Scissors -> -1
}
}
}
object Scissors : Move {
override fun getValue(): Int = 3
override fun compareTo(other: Move): Int {
return when (other) {
Rock -> -1
Paper -> 1
Scissors -> 0
}
}
}
}
fun String.toMove(): Move {
return when (this) {
"X" -> Rock
"A" -> Rock
"Y" -> Paper
"B" -> Paper
"C" -> Scissors
"Z" -> Scissors
else -> Rock
}
}
enum class WinStatus {
SHOULD_WIN {
override fun getValue(): Int = 6
},
SHOULD_LOSE {
override fun getValue(): Int = 0
},
SHOULD_TIE {
override fun getValue(): Int = 3
};
abstract fun getValue(): Int
fun getAccordingMove(firstMove: Move): Move {
return when (this) {
SHOULD_WIN ->
when (firstMove) {
Paper -> Scissors
Rock -> Paper
Scissors -> Rock
}
SHOULD_LOSE ->
when (firstMove) {
Paper -> Rock
Rock -> Scissors
Scissors -> Paper
}
SHOULD_TIE ->
when (firstMove) {
Paper -> Paper
Rock -> Rock
Scissors -> Scissors
}
}
}
}
fun String.toWinStatus(): WinStatus {
return when (this) {
"X" -> SHOULD_LOSE
"Y" -> SHOULD_TIE
"Z" -> SHOULD_WIN
else -> SHOULD_TIE
}
} | 0 | Kotlin | 0 | 2 | 9d1fee54837cfae38c965cc1a5b267d7d15f4b3a | 3,340 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day01.kt | yalexaner | 573,141,113 | false | {"Kotlin": 4235} | @file:JvmName("Day1Kt")
import kotlin.math.max
fun main() {
runTests()
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
private fun runTests() {
val testInput = readInput("Day01_test")
val part1Result = part1(testInput)
check(part1Result == 24000) { "part1 is $part1Result, but expected 24000" }
val part2Result = part2(testInput)
check(part2Result == 45000) { "part2 is $part2Result, but exprected 45000"}
}
private fun part1(input: List<String>): Int {
var maxCalories = 0
var currentElfCalories = 0
for (line in input) {
if (line.isEmpty()) {
maxCalories = maxOf(maxCalories, currentElfCalories)
currentElfCalories = 0
continue
}
currentElfCalories += line.toInt()
}
if (currentElfCalories != 0) {
maxCalories = maxOf(maxCalories, currentElfCalories)
}
return maxCalories
}
private fun part2(input: List<String>): Int {
val topElvesCalories = Array(3) { 0 }
var currentElfCalories = 0
for (line in input) {
if (line.isEmpty()) {
topElvesCalories.addOrReplaceIfPossible(currentElfCalories)
currentElfCalories = 0
continue
}
currentElfCalories += line.toInt()
}
if (currentElfCalories != 0) {
topElvesCalories.addOrReplaceIfPossible(currentElfCalories)
}
return topElvesCalories.sum()
}
private fun Array<Int>.addOrReplaceIfPossible(num: Int) {
var currentMin = num
var currentIdx = 0
while (currentIdx < size) {
if (get(currentIdx) < currentMin) {
val tmp = this[currentIdx]
this[currentIdx] = currentMin
currentMin = tmp
}
currentIdx++
}
} | 0 | Kotlin | 0 | 0 | 58c2bf57543253db544fa8950aac4dc67896b808 | 1,789 | advent-of-code-2022 | Apache License 2.0 |
compiler/src/main/kotlin/edu/cornell/cs/apl/viaduct/util/Lists.kt | s-ren | 386,161,765 | true | {"Kotlin": 878757, "Java": 43761, "C++": 13898, "Python": 11991, "Lex": 6620, "Dockerfile": 1844, "Makefile": 1785, "SWIG": 1212, "Shell": 698} | package edu.cornell.cs.apl.viaduct.util
/**
* Returns the list of all pairs where the first element is from [this] list,
* and the second element is from [other].
*/
internal fun <A, B> List<A>.pairedWith(other: List<B>): List<Pair<A, B>> {
val result = mutableListOf<Pair<A, B>>()
for (a in this) {
for (b in other) {
result += Pair(a, b)
}
}
return result
}
/** Returns all subsequences of this list sorted from the smallest in size to the largest. */
internal fun <E> List<E>.subsequences(): Iterable<List<E>> {
val result = mutableListOf<List<E>>()
for (i in 0..this.size) {
result += this.subsequences(i)
}
return result
}
/** Returns all subsequences of this list of length [length]. */
// TODO: this can be sped up with dynamic programming.
private fun <E> List<E>.subsequences(length: Int): Iterable<List<E>> =
when {
length == 0 ->
listOf(listOf())
length == this.size ->
listOf(this)
length > this.size ->
listOf()
else ->
this.drop(1).let {
it.subsequences(length - 1).map { s -> listOf(this.first()) + s } +
it.subsequences(length)
}
}
| 0 | null | 0 | 0 | 337b3873e10f642706b195b10f939e9c1c7832ef | 1,258 | viaduct | MIT License |
leetcode/src/offer/middle/Offer46.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
import kotlin.math.sign
fun main() {
// 剑指 Offer 46. 把数字翻译成字符串
// https://leetcode.cn/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof/
println(translateNum3(12258))
}
fun translateNum3(num: Int): Int {
if (num in 0..9) {
return 1
}
if (num in 10..25) {
return 2
}
val numStr = num.toString()
// dp[i] 表示,以 num[i] 结尾的数的翻译数量
// 比如对于 2341,dp[0] 表示以2结尾的数的翻译的数量,就是1
// dp[1] 表示以 num[1],也就是3结尾的数,也就是23这个数的翻译数量,可以是 23,也可以是 2 3,所以23有两种翻译,也就是 dp[1]=2
val dp = IntArray(numStr.length)
dp[0] = 1
val firstTwo = numStr.substring(0, 2)
dp[1] = if (firstTwo >= "10" && firstTwo <= "25") {
2
}else {
1
}
// 对于以 num[i] 结尾的数的翻译数量 dp[i],取决于 num[i-1,i+1) 构成的字符串 substring 是否可以合并翻译,如果 "10"<=substring<="25",则 substring 可以合并翻译,否则则不行
// 如果 substring 合并翻译,则 dp[i] = dp[i-2],比如 123 中,23 如果合并翻译,那翻译数量就是 1,也就是 dp[0];
// 如果 substring 分开翻译,则 dp[i] = dp[i-1],比如 123 中,2 3 拆开翻译,那翻译的方法有 (1 2 3)、(12 3) 两种,也就是 dp[1]
// 所以 dp[i] = dp[i-2]+dp[i-1](num[i-1, i+1)可以合并翻译)
// dp[i] = dp[i-1] (num[i-1, i+1)不能合并翻译)
for (i in 2 until numStr.length) {
val substring = numStr.substring(i - 1, i + 1)
if (substring >= "10" && substring <= "25") {
dp[i] = dp[i-1] + dp[i-2]
}else {
dp[i] = dp[i-1]
}
}
return dp[numStr.length-1]
}
fun translateNum(num: Int): Int {
// 参考 https://leetcode.cn/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof/solution/mian-shi-ti-46-ba-shu-zi-fan-yi-cheng-zi-fu-chua-6/
// 方法一的图解
// 长度为1时,只有一种翻译方法
var a = 1
// 长度为0时,只有一种翻译方法
var b = 1
val numString = num.toString()
for (i in 2..numString.length) {
val substring = numString.substring(i - 2, i)
if (substring >= "10" && substring <= "25") {
// f(i) = f(i-1) + f(i-2) (10<=substring<=25)
val tmp = a
a += b
b = tmp
}else {
// f(i) = f(i-1) (
b = a
}
}
return a
}
fun translateNum1(num: Int): Int {
if (num < 10) {
return 1
}
if (num in 10..25) {
return 2
}
val numStr = num.toString()
// 假设 num = x1x2x3x4x5
// 对于 x1x2x3x4 的翻译数量是 f(4)
// 对于 x1x2x3 的翻译数量是 f(3)
// 当 x4x5 作为一个整体翻译时,x1x2x3x4x5 的翻译数量是f(3)
// 当 单独翻译 x5 时,x1x2x3x4x5 的翻译数量是f(4)
// 所以当 x4x5 可以作为一个整体翻译时, f(5) = f(3) + f(4);
// 当 x4x5 不能合并翻译时,只能单独翻译 x5,此时 f(5) = f(4)
// 状态定义
// dp[i] 表示以 numStr[i] 结尾的数字的翻译数量
// 状态转移方程
// 1)dp[i] = dp[i-2] + dp[i-1],当 nums[i-2, i) 构成的数字>=10 && <=25
// 2)dp[i] = dp[i-1],当 nums[i-2,i) 构成的数字<10 || >25
val dp = IntArray(numStr.length + 1)
dp[0] = 1
dp[1] = 1
for (i in 2 .. numStr.length) {
val substring = numStr.substring(i - 2, i)
if (substring >= "10" && substring <= "25") {
dp[i] = dp[i-1] + dp[i-2]
}else {
dp[i] = dp[i-1]
}
}
return dp[numStr.length]
}
fun translateNum2(num: Int): Int {
if (num in 0..9) {
return 1
}
if (num in 10..25) {
return 2
}
val numStr = num.toString()
// dp[i] 表示以 num[i-1] 结尾的数的翻译方法数,数组长度 n = numStr.length,要求以 num[n-1] 结尾的数的翻译数量,其实就是求 dp[n]
val dp = IntArray(numStr.length+1)
// dp[0]=1,表示以第 1 个数结尾的数的翻译方法数是1
dp[0] = 1
// dp[1],根据前面的if条件,可以知道 num 是大于 25 的,所以以 num[1] 结尾的的数,只有一种翻译方法,就是 num[0]、num[1] 单独翻译
dp[1] = 1
for (i in 2..numStr.length) {
val substring = numStr.substring(i - 2, i)
if (substring > "10" && substring < "25") {
// substring 可以合并翻译成一个字母,对应的翻译数量是 dp[i-2];也可以拆个翻译成两个字母,对应的数量是 dp[i-1]
dp[i] = dp[i-1] + dp[i-2]
}else {
//
dp[i] = dp[i-1]
}
}
return dp[numStr.length]
}
| 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 4,848 | kotlin-study | MIT License |
src/Day11.kt | MwBoesgaard | 572,857,083 | false | {"Kotlin": 40623} | fun main() {
class Monkey(var items: MutableList<Int>, val operation: Pair<String, String>, val test: List<Int>) {
val monkeyMailbox: MutableList<Pair<Int, Int>> = mutableListOf()
var totalNumberOfItemsInspected = 0L
fun inspect() {
val increaseBy = operation.second.toIntOrNull()
for (item in items) {
var inspectedItem = when (operation.first) {
"+" -> item + (increaseBy ?: item)
"*" -> item * (increaseBy ?: item)
else -> error("Unknown item operation")
}
inspectedItem /= 3
testAndPassToMailbox(inspectedItem)
totalNumberOfItemsInspected++
}
items.clear()
}
fun testAndPassToMailbox(itemToTest: Int) {
val denominator = test[0]
val monkeyToSendIfTrue = test[1]
val monkeyToSendIfFalse = test[2]
if (itemToTest % denominator == 0) {
monkeyMailbox.add(Pair(monkeyToSendIfTrue, itemToTest))
} else {
monkeyMailbox.add(Pair(monkeyToSendIfFalse, itemToTest))
}
}
}
class MonkeyGame(val monkeys: List<Monkey>, val roundsToPlay: Int) {
fun start() {
for (round in 1..roundsToPlay) {
for (monkey in monkeys) {
if (monkey.items.size == 0) {
continue
}
monkey.inspect()
handleMonkeyMail(monkey)
}
}
}
private fun handleMonkeyMail(monkey: Monkey) {
for (mail in monkey.monkeyMailbox) {
val recipient = mail.first
val item = mail.second
monkeys[recipient].items.add(item)
}
monkey.monkeyMailbox.clear()
}
}
fun part1(input: String): Long {
val monkey0 = Monkey(mutableListOf(65, 78), Pair("*", "3"), listOf(5, 2, 3))
val monkey1 = Monkey(mutableListOf(54, 78, 86, 79, 73, 64, 85, 88), Pair("+", "8"), listOf(11, 4, 7))
val monkey2 = Monkey(mutableListOf(69, 97, 77, 88, 87), Pair("+", "2"), listOf(2, 5, 3))
val monkey3 = Monkey(mutableListOf(99), Pair("+", "4"), listOf(13, 1, 5))
val monkey4 = Monkey(mutableListOf(60, 57, 52), Pair("*", "19"), listOf(7, 7, 6))
val monkey5 = Monkey(mutableListOf(91, 82, 85, 73, 84, 53), Pair("+", "5"), listOf(3, 4, 1))
val monkey6 = Monkey(mutableListOf(88, 74, 68, 56), Pair("*", "old"), listOf(17, 0, 2))
val monkey7 = Monkey(mutableListOf(54, 82, 72, 71, 53, 99, 67), Pair("+", "1"), listOf(19, 6, 0))
val monkeys = listOf(monkey0, monkey1, monkey2, monkey3, monkey4, monkey5, monkey6, monkey7)
val game = MonkeyGame(monkeys, 20)
game.start()
return game.monkeys
.map { it.totalNumberOfItemsInspected }
.sortedDescending()
.take(2)
.reduce { first, second -> first * second }
}
class Item(value: Int) {
val remainderByFactor = mutableMapOf<Int, Int>()
val listOfFactors = listOf(2, 3, 5, 7, 11, 13, 17, 19)
init {
decompose(value)
}
fun decompose(decomposable: Int) {
for (factor in listOfFactors) {
remainderByFactor[factor] = decomposable % factor
}
}
fun add(number: Int) {
for (factor in listOfFactors) {
val currentRemainder = remainderByFactor[factor]!!
remainderByFactor[factor] = (currentRemainder + number) % factor
}
}
fun multiply(number: Int) {
for (factor in listOfFactors) {
val currentRemainder = remainderByFactor[factor]!!
remainderByFactor[factor] = (currentRemainder * number) % factor
}
}
fun double() {
for (factor in listOfFactors) {
val currentRemainder = remainderByFactor[factor]!!
remainderByFactor[factor] = (currentRemainder * currentRemainder) % factor
}
}
}
class ItemMonkey(var items: MutableList<Item>, val operation: Pair<String, String>, val test: List<Int>) {
val monkeyMailbox: MutableList<Pair<Int, Item>> = mutableListOf()
var totalNumberOfItemsInspected = 0L
fun inspect() {
val increaseBy = operation.second.toIntOrNull()
for (item in items) {
when (operation.first) {
"+" -> item.add(increaseBy!!)
"*" -> if (increaseBy != null) item.multiply(increaseBy) else item.double()
else -> error("Unknown item operation")
}
testAndPassToMailbox(item)
totalNumberOfItemsInspected++
}
items.clear()
}
fun testAndPassToMailbox(itemToTest: Item) {
val denominator = test[0]
val monkeyToSendIfTrue = test[1]
val monkeyToSendIfFalse = test[2]
if (itemToTest.remainderByFactor[denominator] == 0) {
monkeyMailbox.add(Pair(monkeyToSendIfTrue, itemToTest))
} else {
monkeyMailbox.add(Pair(monkeyToSendIfFalse, itemToTest))
}
}
}
class ItemMonkeyGame(val monkeys: List<ItemMonkey>, val roundsToPlay: Int) {
fun start() {
for (round in 1..roundsToPlay) {
for (monkey in monkeys) {
if (monkey.items.size == 0) {
continue
}
monkey.inspect()
handleMonkeyMail(monkey)
}
}
}
private fun handleMonkeyMail(monkey: ItemMonkey) {
for (mail in monkey.monkeyMailbox) {
val recipient = mail.first
val item = mail.second
monkeys[recipient].items.add(item)
}
monkey.monkeyMailbox.clear()
}
}
fun part2(input: String): Long {
val monkey0 = ItemMonkey(mutableListOf(Item(65), Item(78)), Pair("*", "3"), listOf(5, 2, 3))
val monkey1 = ItemMonkey(
mutableListOf(Item(54), Item(78), Item(86), Item(79), Item(73), Item(64), Item(85), Item(88)),
Pair("+", "8"),
listOf(11, 4, 7)
)
val monkey2 =
ItemMonkey(mutableListOf(Item(69), Item(97), Item(77), Item(88), Item(87)), Pair("+", "2"), listOf(2, 5, 3))
val monkey3 = ItemMonkey(mutableListOf(Item(99)), Pair("+", "4"), listOf(13, 1, 5))
val monkey4 = ItemMonkey(mutableListOf(Item(60), Item(57), Item(52)), Pair("*", "19"), listOf(7, 7, 6))
val monkey5 = ItemMonkey(
mutableListOf(Item(91), Item(82), Item(85), Item(73), Item(84), Item(53)),
Pair("+", "5"),
listOf(3, 4, 1)
)
val monkey6 =
ItemMonkey(mutableListOf(Item(88), Item(74), Item(68), Item(56)), Pair("*", "old"), listOf(17, 0, 2))
val monkey7 = ItemMonkey(
mutableListOf(Item(54), Item(82), Item(72), Item(71), Item(53), Item(99), Item(67)),
Pair("+", "1"),
listOf(19, 6, 0)
)
val monkeys = listOf(monkey0, monkey1, monkey2, monkey3, monkey4, monkey5, monkey6, monkey7)
val game = ItemMonkeyGame(monkeys, 10_000)
game.start()
return game.monkeys
.map { it.totalNumberOfItemsInspected }
.sortedDescending()
.take(2)
.reduce { first, second -> first * second }
}
printSolutionFromInputRaw("Day11", ::part1)
printSolutionFromInputRaw("Day11", ::part2)
}
| 0 | Kotlin | 0 | 0 | 3bfa51af6e5e2095600bdea74b4b7eba68dc5f83 | 7,864 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem223/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem223
/**
* LeetCode page: [223. Rectangle Area](https://leetcode.com/problems/rectangle-area/);
*/
class Solution {
/* Complexity:
* Time O(1) and Space O(1);
*/
fun computeArea(ax1: Int, ay1: Int, ax2: Int, ay2: Int, bx1: Int, by1: Int, bx2: Int, by2: Int): Int {
val rec1Area = calculateRectangleArea(ax1, ax2, ay1, ay2)
val rec2Area = calculateRectangleArea(bx1, bx2, by1, by2)
val xOverlapLen = findOverlapLength(ax1..ax2, bx1..bx2)
val yOverlapLen = findOverlapLength(ay1..ay2, by1..by2)
val overlapArea = xOverlapLen * yOverlapLen
return rec1Area + rec2Area - overlapArea
}
private fun calculateRectangleArea(
xBottomLeft: Int, xTopRight: Int,
yBottomLeft: Int, yTopRight: Int
): Int {
return (xTopRight - xBottomLeft) * (yTopRight - yBottomLeft)
}
private fun findOverlapLength(intRange1: IntRange, intRange2: IntRange): Int {
val range1 = if (intRange1.first < intRange1.last) intRange1 else intRange1.reversed()
val range2 = if (intRange2.first < intRange2.last) intRange2 else intRange2.reversed()
val startOfOverlap = maxOf(range1.first, range2.first)
val endOfOverlap = minOf(range1.last, range2.last)
return (endOfOverlap - startOfOverlap).coerceAtLeast(0)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,372 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/adventofcode/day12.kt | Kvest | 163,103,813 | false | null | package adventofcode
import java.io.File
import java.math.BigInteger
fun main(args: Array<String>) {
println(first12("##.#..#.#..#.####.#########.#...#.#.#......##.#.#...##.....#...#...#.##.#...##...#.####.##..#.#..#.", File("./data/day12_1.txt").readLines(), 20))
println(second12())
}
fun second12(): BigInteger {
//Note: Solution was found in an analytical way
val target = BigInteger("50000000000")
return (target - BigInteger("500")) * BigInteger("87") + BigInteger("44457")
}
fun first12(initial: String, data: List<String>, generationsCount: Int): Int {
val more = (generationsCount * 1.5).toInt()
val arr = CharArray(more * 2 + initial.length) {
if (it < more || it >= (more + initial.length)) {
'.'
} else {
initial[it - more]
}
}
val rules = data.map { Rule(it) }
repeat(generationsCount) {
val old = arr.copyOf()
(2 until (arr.size - 2)).forEach { i ->
arr[i] = rules.fold('.') { acc, rule ->
if (rule.match(old, i)) rule.result else acc
}
}
}
var sum = 0
arr.forEachIndexed { i, ch ->
if (ch == '#') {
sum += (i - more)
}
}
return sum
}
private class Rule(str: String) {
private val arr: CharArray = charArrayOf(str[0], str[1], str[2], str[3], str[4])
val result: Char = str[9]
fun match(src: CharArray, i: Int): Boolean {
return src[i - 2] == arr[0] &&
src[i - 1] == arr[1] &&
src[i] == arr[2] &&
src[i + 1] == arr[3] &&
src[i + 2] == arr[4]
}
} | 0 | Kotlin | 0 | 0 | d94b725575a8a5784b53e0f7eee6b7519ac59deb | 1,657 | aoc2018 | Apache License 2.0 |
src/main/kotlin/g1201_1300/s1262_greatest_sum_divisible_by_three/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1262_greatest_sum_divisible_by_three
// #Medium #Array #Dynamic_Programming #Greedy
// #2023_06_08_Time_263_ms_(100.00%)_Space_39.9_MB_(33.33%)
class Solution {
fun maxSumDivThree(nums: IntArray): Int {
var sum = 0
var smallestNumWithMod1 = 10001
var secondSmallestNumWithMod1 = 10002
var smallestNumWithMod2 = 10001
var secondSmallestNumWithMod2 = 10002
for (i in nums) {
sum += i
if (i % 3 == 1) {
if (i <= smallestNumWithMod1) {
val temp = smallestNumWithMod1
smallestNumWithMod1 = i
secondSmallestNumWithMod1 = temp
} else if (i < secondSmallestNumWithMod1) {
secondSmallestNumWithMod1 = i
}
}
if (i % 3 == 2) {
if (i <= smallestNumWithMod2) {
val temp = smallestNumWithMod2
smallestNumWithMod2 = i
secondSmallestNumWithMod2 = temp
} else if (i < secondSmallestNumWithMod2) {
secondSmallestNumWithMod2 = i
}
}
}
if (sum % 3 == 0) {
return sum
} else if (sum % 3 == 2) {
val min = Math.min(smallestNumWithMod2, smallestNumWithMod1 + secondSmallestNumWithMod1)
return sum - min
} else if (sum % 3 == 1) {
val min = Math.min(smallestNumWithMod1, smallestNumWithMod2 + secondSmallestNumWithMod2)
return sum - min
}
return sum
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,632 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem2616/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2616
/**
* LeetCode page: [2616. Minimize the Maximum Difference of Pairs](https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs/);
*/
class Solution {
/* Complexity:
* Time O(NLogN+NLogV) and Space O(N) where N is the size of nums, V is the (maxValue - minValue) of nums;
*/
fun minimizeMax(nums: IntArray, p: Int): Int {
if (p == 0) {
return 0
}
val sortedNums = nums.sorted()
var lowerBound = 0
var upperBound = sortedNums.last() - sortedNums[0]
while (lowerBound < upperBound) {
val mid = lowerBound + (upperBound - lowerBound) / 2
if (hasEnoughPairs(sortedNums, p, mid)) {
upperBound = mid
} else {
lowerBound = mid + 1
}
}
return upperBound
}
private fun hasEnoughPairs(sortedNums: List<Int>, numPairs: Int, maxDifference: Int): Boolean {
var index = 0
var pairCount = 0
while (index < sortedNums.lastIndex) {
if (sortedNums[index + 1] - sortedNums[index] <= maxDifference) {
pairCount++
index += 2
} else {
index++
}
if (pairCount >= numPairs) {
return true
}
}
return false
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,398 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day01.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | fun main() {
fun part1(input: List<String>): Int {
return computeCalories(input).max()
}
fun part2(input: List<String>): Int {
return computeCalories(input).sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input)) // 74198
println(part2(input)) // 209914
}
private fun computeCalories(input: List<String>) = input
.partitionBy { it.isEmpty() }
.map { it.sumOf { line -> line.toInt() } }
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 665 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/year2022/day08/Problem.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 154634} | package year2022.day08
import IProblem
import java.util.*
import kotlin.math.max
class Problem : IProblem {
private val matrix = javaClass
.getResource("/2022/08.txt")!!
.readText()
.lines()
.filter(String::isNotEmpty)
.map { it.map(Char::digitToInt).toIntArray() }
.toTypedArray()
override fun part1(): Int {
val n = matrix.size
val seen = Array(n) { BooleanArray(n) }
var count = 0
for (i in 1 until n - 1) {
var max = matrix[i][0]
for (j in 1 until n - 1) {
val height = matrix[i][j]
if (height > max && !seen[i][j]) {
seen[i][j] = true
count++
}
max = max(height, max)
}
}
for (j in 1 until n - 1) {
var max = matrix[0][j]
for (i in 1 until n - 1) {
val height = matrix[i][j]
if (height > max && !seen[i][j]) {
seen[i][j] = true
count++
}
max = max(height, max)
}
}
for (i in 1 until n - 1) {
var max = matrix[i][n - 1]
for (j in n - 2 downTo 1) {
val height = matrix[i][j]
if (height > max && !seen[i][j]) {
seen[i][j] = true
count++
}
max = max(height, max)
}
}
for (j in 1 until n - 1) {
var max = matrix[n - 1][j]
for (i in n - 2 downTo 1) {
val height = matrix[i][j]
if (height > max && !seen[i][j]) {
seen[i][j] = true
count++
}
max = max(height, max)
}
}
return count + 4 * n - 4
}
override fun part2(): Int {
val n = matrix.size
val scenic = Array(n) { IntArray(n) { 1 } }
var max = 0
for (i in 1 until n - 1) {
val map = TreeMap<Int, Int>()
for (j in 1 until n - 1) {
val height = matrix[i][j]
if (height > matrix[i][j - 1]) {
val index = map.ceilingEntry(height)?.value ?: 0
scenic[i][j] *= j - index
max = max(scenic[i][j], max)
}
map[height] = j
}
}
for (j in 1 until n - 1) {
val map = TreeMap<Int, Int>()
for (i in 1 until n - 1) {
val height = matrix[i][j]
if (height > matrix[i - 1][j]) {
val index = map.ceilingEntry(height)?.value ?: 0
scenic[i][j] *= i - index
max = max(scenic[i][j], max)
}
map[height] = i
}
}
for (i in 1 until n - 1) {
val map = TreeMap<Int, Int>()
for (j in n - 2 downTo 1) {
val height = matrix[i][j]
if (height > matrix[i][j + 1]) {
val index = map.ceilingEntry(height)?.value ?: n
scenic[i][j] *= index - j - 1
max = max(scenic[i][j], max)
}
map[height] = j
}
}
for (j in 1 until n - 1) {
val map = TreeMap<Int, Int>()
for (i in n - 2 downTo 1) {
val height = matrix[i][j]
if (height > matrix[i + 1][j]) {
val index = map.ceilingEntry(height)?.value ?: n
scenic[i][j] *= index - i - 1
max = max(scenic[i][j], max)
}
map[height] = i
}
}
return max
}
}
| 0 | Kotlin | 0 | 0 | 455bc8a69527c6c2f20362945b73bdee496ace41 | 3,896 | advent-of-code | The Unlicense |
src/Day14.kt | CrazyBene | 573,111,401 | false | {"Kotlin": 50149} | import java.lang.Integer.max
import java.lang.Integer.min
fun main() {
fun List<String>.toRocks(): Set<Pair<Int, Int>> {
return this.flatMap { line ->
line
.split(" -> ")
.map {
it.split(",").map { it.toInt() }
}
.zipWithNext()
.map {
val (firstX, firstY) = it.first
val (secondX, secondY) = it.second
val rocks = mutableSetOf<Pair<Int, Int>>()
for (y in min(firstY, secondY)..max(firstY, secondY)) {
for (x in min(firstX, secondX)..max(firstX, secondX)) {
rocks.add(x to y)
}
}
rocks
}.fold(mutableSetOf<Pair<Int, Int>>()) { acc, i ->
acc.addAll(i)
acc
}
}.fold(mutableSetOf<Pair<Int, Int>>()) { acc, i ->
acc.add(i)
acc
}
}
fun findNewPosition(
currentPosition: Pair<Int, Int>,
rocks: Set<Pair<Int, Int>>,
restingSand: Set<Pair<Int, Int>>,
ground: Int = Int.MAX_VALUE
): Pair<Int, Int> {
val obstacles = mutableSetOf<Pair<Int, Int>>()
obstacles.addAll(rocks)
obstacles.addAll(restingSand)
if (currentPosition.second + 1 == ground)
return currentPosition
if (currentPosition.first to currentPosition.second + 1 !in obstacles) {
return currentPosition.first to currentPosition.second + 1
}
if (currentPosition.first - 1 to currentPosition.second + 1 !in obstacles) {
return currentPosition.first - 1 to currentPosition.second + 1
}
if (currentPosition.first + 1 to currentPosition.second + 1 !in obstacles) {
return currentPosition.first + 1 to currentPosition.second + 1
}
return currentPosition
}
fun findFinalPosition(
currentPosition: Pair<Int, Int>,
rocks: Set<Pair<Int, Int>>,
restingSand: Set<Pair<Int, Int>>,
ground: Int = Int.MAX_VALUE
): Pair<Int, Int> {
val obstacles = mutableSetOf<Pair<Int, Int>>()
obstacles.addAll(rocks)
obstacles.addAll(restingSand)
var finalPosition: Pair<Int, Int>
var newPosition = currentPosition
do {
finalPosition = newPosition
if (finalPosition.second + 1 == ground)
break
if (finalPosition.first to finalPosition.second + 1 !in obstacles)
newPosition = finalPosition.first to finalPosition.second + 1
else if (finalPosition.first - 1 to finalPosition.second + 1 !in obstacles)
newPosition = finalPosition.first - 1 to finalPosition.second + 1
else if (finalPosition.first + 1 to finalPosition.second + 1 !in obstacles)
newPosition = finalPosition.first + 1 to finalPosition.second + 1
} while (newPosition != finalPosition)
return finalPosition
}
fun printCave(
xRange: IntRange,
yRange: IntRange,
rocks: Set<Pair<Int, Int>>,
restingSand: Set<Pair<Int, Int>>,
ground: Int = -1
) {
for (y in yRange) {
for (x in xRange) {
val symbol = when (x to y) {
x to ground,
in rocks -> "#"
in restingSand -> "o"
else -> "."
}
print(symbol)
}
println()
}
}
fun part1(input: List<String>): Int {
val rocks = input.toRocks()
val lowestRock = rocks.maxOf {
it.second
}
val restingSand = mutableSetOf<Pair<Int, Int>>()
while (true) {
val newSandBlock = findFinalPosition(500 to 0, rocks, restingSand, lowestRock + 2)
if (newSandBlock.second > lowestRock) {
break
}
restingSand += newSandBlock
}
// printCave(494 until 504, 0 until 10, rocks, restingSand)
return restingSand.count()
}
fun part2(input: List<String>): Int {
val rocks = input.toRocks()
val ground = rocks.maxOf {
it.second + 2
}
val restingSand = mutableSetOf<Pair<Int, Int>>()
while (true) {
val newSandBlock = findFinalPosition(500 to 0, rocks, restingSand, ground)
restingSand += newSandBlock
if (newSandBlock == 500 to 0) {
break
}
}
// printCave(500 - ground .. 500 + ground, 0 .. ground, rocks, restingSand, ground)
return restingSand.count()
}
val testInput = readInput("Day14Test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println("Question 1 - Answer: ${part1(input)}")
println("Question 2 - Answer: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26 | 5,094 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/sherepenko/leetcode/solutions/MinPathSum.kt | asherepenko | 264,648,984 | false | null | package com.sherepenko.leetcode.solutions
import com.sherepenko.leetcode.Solution
import kotlin.math.min
class MinPathSum(
private val grid: Array<IntArray>
) : Solution {
companion object {
fun minPathSum(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
val dp = Array(m) {
IntArray(n)
}
dp[0][0] = grid[0][0]
for (i in 1 until m) {
dp[i][0] = dp[i - 1][0] + grid[i][0]
}
for (j in 1 until n) {
dp[0][j] = dp[0][j - 1] + grid[0][j]
}
println(" Initial Matrix:")
dp.forEach {
println(" ${it.joinToString(separator = " ")}")
}
for (i in 1 until m) {
for (j in 1 until n) {
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
}
}
println(" Result Matrix:")
dp.forEach {
println(" ${it.joinToString(separator = " ")}")
}
return dp[m - 1][n - 1]
}
}
override fun resolve() {
val result = minPathSum(grid)
println("Minimum Path Sum:")
println(" Input:")
grid.forEach {
println(" ${it.joinToString(separator = " ")}")
}
println(" Result: $result \n")
}
}
| 0 | Kotlin | 0 | 0 | 49e676f13bf58f16ba093f73a52d49f2d6d5ee1c | 1,450 | leetcode | The Unlicense |
src/main/kotlin/Day2.kt | d1snin | 726,126,205 | false | {"Kotlin": 14602} | /*
* 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.
*/
private const val INPUT =
"""
"""
private const val RED_LIMIT = 12
private const val GREEN_LIMIT = 13
private const val BLUE_LIMIT = 14
private data class Game(
val id: Int,
val handfuls: List<Handful>
)
private data class Handful(
val red: Int,
val green: Int,
val blue: Int
)
private val lines
get() = INPUT.lines()
.map { it.trim() }
.filter { it.isNotEmpty() }
fun day2() {
println("Running AoC Day 2 (1st part)...")
firstPart()
println()
println("Running AoC Day 2 (2nd part)...")
secondPart()
}
private fun firstPart() {
val games = lines.parseGames()
val res = games.sumOf { game ->
val beyondLimit = game.handfuls.any {
it.isBeyondLimit()
}
if (beyondLimit) 0 else game.id
}
println("res: $res")
}
private fun secondPart() {
val games = lines.parseGames()
val res = games.sumOf { game ->
val handfuls = game.handfuls
val minRed = handfuls.maxOf {
it.red
}
val minGreen = handfuls.maxOf {
it.green
}
val minBlue = handfuls.maxOf {
it.blue
}
minRed * minGreen * minBlue
}
println("res: $res")
}
private fun List<String>.parseGames() =
map {
it.parseGame()
}
private fun String.parseGame(): Game {
val id = findId()
val handfuls = findHandfulsString()
.findHandfulDeclarations()
.map { handfulString ->
var red = 0
var green = 0
var blue = 0
handfulString.findCubeStrings().forEach { cubeString ->
val countAndColor = cubeString.split(" ")
val count = countAndColor.first().toInt()
val color = countAndColor.last()
when (color) {
"red" -> red += count
"green" -> green += count
"blue" -> blue += count
}
}
Handful(red, green, blue)
}
return Game(id, handfuls)
}
private fun String.findId() =
requireNotNull("(?<=Game\\s)\\d+".toRegex().find(this)).value.toInt()
private fun String.findHandfulsString() =
replace("Game\\s\\d+:\\s".toRegex(), "")
private fun String.findHandfulDeclarations() =
split("; ")
private fun String.findCubeStrings() =
split(", ")
private fun Handful.isBeyondLimit() =
red > RED_LIMIT || green > GREEN_LIMIT || blue > BLUE_LIMIT | 0 | Kotlin | 0 | 0 | 8b5b34c4574627bb3c6b1a12664cc6b4c9263e30 | 3,105 | aoc-2023 | Apache License 2.0 |
src/day17/Day17.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day17
import readInput
import readTestInput
import kotlin.math.min
private data class Position(val x: Int, val y: Int)
private fun p(x: Int, y: Int) = Position(x = x, y = y)
private sealed interface Shape {
val partPositions: List<Position>
fun fitsInto(chamber: Chamber, at: Position): Boolean {
return partPositions.none { position ->
val x = at.x + position.x
val y = at.y + position.y
x < 0 || x >= 7 || y < 0 || chamber[y][x]
}
}
object Line : Shape {
override val partPositions =
listOf(p(x = 0, y = 0), p(x = 1, y = 0), p(x = 2, y = 0), p(x = 3, y = 0))
}
object Cross : Shape {
override val partPositions =
listOf(p(x = 0, y = 0), p(x = -1, y = 1), p(x = 0, y = 1), p(x = 1, y = 1), p(x = 0, y = 2))
}
object Boomerang : Shape {
override val partPositions =
listOf(p(x = 0, y = 0), p(x = 1, y = 0), p(x = 2, y = 0), p(x = 2, y = 1), p(x = 2, y = 2))
}
object Bar : Shape {
override val partPositions =
listOf(p(x = 0, y = 0), p(x = 0, y = 1), p(x = 0, y = 2), p(x = 0, y = 3))
}
object Cube : Shape {
override val partPositions =
listOf(p(x = 0, y = 0), p(x = 1, y = 0), p(x = 0, y = 1), p(x = 1, y = 1))
}
}
enum class Jet { LEFT, RIGHT }
private fun List<String>.toJetSequence(): Sequence<Jet> {
val jetDefinition = this.single()
return sequence {
while (true) {
for (char in jetDefinition) {
when (char) {
'<' -> yield(Jet.LEFT)
'>' -> yield(Jet.RIGHT)
}
}
}
}
}
private data class Rock(val position: Position, val shape: Shape) {
val x: Int = position.x
val y: Int = position.y
fun moveLeft(chamber: Chamber): Rock =
moveBy(offset = Position(x = -1, y = 0), chamber = chamber)
fun moveRight(chamber: Chamber): Rock =
moveBy(offset = Position(x = 1, y = 0), chamber = chamber)
fun moveDown(chamber: Chamber): Rock =
moveBy(offset = Position(x = 0, y = -1), chamber = chamber)
private fun moveBy(offset: Position, chamber: Chamber): Rock {
val targetPosition = Position(x + offset.x, y + offset.y)
return if (shape.fitsInto(chamber = chamber, at = targetPosition)) {
this.copy(position = targetPosition)
} else this
}
fun placeInto(chamber: Chamber) {
for (partPosition in shape.partPositions) {
val x = x + partPosition.x
val y = y + partPosition.y
chamber[y][x] = true
}
}
}
private typealias Chamber = MutableList<BooleanArray>
private val Chamber.highestRockY: Int
get() {
for (i in indices.reversed()) {
if (this[i].any { isBlocked -> isBlocked }) {
return i
}
}
return -1
}
private fun Chamber.fillWithRowsUpTo(row: Int) {
val chamber = this
if (chamber.size <= row) {
val missingRows = row - chamber.lastIndex
repeat(missingRows) {
chamber.add(BooleanArray(7))
}
}
}
private fun Chamber.insert(rock: Rock, jets: Iterator<Jet>) {
val chamber = this
val rockAtDestination = rock.moveToFinalPosition(chamber, jets)
rockAtDestination.placeInto(chamber)
}
private fun Chamber.calculateHeight() =
indexOfLast { row -> row.any { it } } + 1
private fun Chamber.asHexString() =
this.joinToString(separator = "") { row ->
val binaryRepresentation = row.joinToString(separator = "") { if (it) "1" else "0" }.toInt(2)
binaryRepresentation.toString(16).padStart(2, '0')
}
private fun Chamber.asPrintout(): String {
return this.asReversed().joinToString(separator = "\n") { row ->
row.joinToString(separator = "") { isBlocked ->
if (isBlocked) "#" else "."
}
}
}
private fun simulateSpawningRocks(chamber: Chamber): Sequence<Rock> {
var index = 0
return sequence {
while (true) {
val yOfTallestRock = chamber.highestRockY
chamber.fillWithRowsUpTo(yOfTallestRock + 10)
val shape = when (index) {
0 -> Shape.Line
1 -> Shape.Cross
2 -> Shape.Boomerang
3 -> Shape.Bar
4 -> Shape.Cube
else -> error("Unknown shape index!")
}
val x = 2 - shape.partPositions.minOf { it.x }
val y = yOfTallestRock + 4
yield(Rock(position = p(x = x, y = y), shape = shape))
index = (index + 1) % 5
}
}
}
private fun List<String>.simulateFallingRocks(rockCount: Int): Chamber {
val input = this
val chamber: Chamber = MutableList(1) { BooleanArray(7) }
val jets = input.toJetSequence().iterator()
val rocks = simulateSpawningRocks(chamber).take(rockCount)
for (rock in rocks) {
chamber.insert(rock, jets)
}
return chamber
}
private fun Rock.moveToFinalPosition(chamber: Chamber, jets: Iterator<Jet>): Rock {
var movingRock = this
var heightBeforeMoves: Int
do {
heightBeforeMoves = movingRock.y
val jet = jets.next()
movingRock = when (jet) {
Jet.LEFT -> movingRock.moveLeft(chamber)
Jet.RIGHT -> movingRock.moveRight(chamber)
}
movingRock = movingRock.moveDown(chamber)
} while (heightBeforeMoves != movingRock.y)
return movingRock
}
fun longestCommonPrefix(lhs: String, rhs: String): String {
val n = min(lhs.length, rhs.length)
for (i in 0 until n) {
if (lhs[i] != rhs[i]) {
return lhs.substring(0, i)
}
}
return lhs.substring(0, n)
}
fun String.findLongestRepeatedString(): String {
val suffixes = Array(length) { index ->
substring(index, length)
}
suffixes.sort()
var longestRepeatedSubstring = ""
for (i in 0 until lastIndex) {
val longestCommonPrefix = longestCommonPrefix(suffixes[i], suffixes[i + 1])
if (longestCommonPrefix.length > longestRepeatedSubstring.length) {
longestRepeatedSubstring = longestCommonPrefix
}
}
return longestRepeatedSubstring
}
private fun part1(input: List<String>): Int {
val chamber = input.simulateFallingRocks(2022)
return chamber.calculateHeight()
}
private fun part2(input: List<String>): Long {
val targetRocks = 1_000_000_000_000
// search for repeating pattern in rocks, using first 10_000 rocks as sample
val predictionChamber = input.simulateFallingRocks(10_000)
val predictionBase = predictionChamber.asHexString()
val repeatingPart = predictionBase.findLongestRepeatedString()
val repeatingPattern = repeatingPart.take(repeatingPart.length - repeatingPart.findLongestRepeatedString().length)
val firstRepetitionStart = predictionBase.indexOf(repeatingPattern)
val nonRepeatingStart = predictionBase.take(firstRepetitionStart)
// simulate again, to find
// - tower height before pattern starts to repeat
// - tower height of a single pattern repetition
// - tower height of rocks missing, after rocks before pattern and rocks in N cycles of pattern repetition
val jets = input.toJetSequence().iterator() // use iterator to prevent restarts
val chamber: Chamber = MutableList(1) { BooleanArray(7) }
val rocks = simulateSpawningRocks(chamber).iterator() // use iterator to prevent restarts
var towerHeightBeforePatternRepeats: Int? = null
var towerHeightInASinglePatternRepetition: Int? = null
var towerHeightOfRocksAfterPatternRepetitions: Int = 0
// find tower height before pattern starts to repeat
var rocksFallenBeforePattern = 0L
for (rock in rocks) {
chamber.insert(rock, jets)
rocksFallenBeforePattern += 1
val hexChamber = chamber.asHexString()
if (hexChamber.startsWith(nonRepeatingStart)) {
towerHeightBeforePatternRepeats = chamber.calculateHeight()
break
}
}
checkNotNull(towerHeightBeforePatternRepeats)
// find tower height of a single pattern repetition
var rocksFallenDuringPattern = 0L
for (rock in rocks) {
chamber.insert(rock, jets)
rocksFallenDuringPattern += 1
val hexChamber = chamber.asHexString()
if (hexChamber.contains(repeatingPattern)) {
towerHeightInASinglePatternRepetition = chamber.calculateHeight() - towerHeightBeforePatternRepeats
break
}
}
checkNotNull(towerHeightInASinglePatternRepetition)
// find tower height of rocks missing, after rocks before pattern and rocks in N cycles of pattern repetition
val cyclesOfRepetitionNeeded = (targetRocks - rocksFallenBeforePattern) / rocksFallenDuringPattern
val rocksNeededAfterPatternRepitition =
targetRocks - rocksFallenBeforePattern - (rocksFallenDuringPattern * cyclesOfRepetitionNeeded)
if (rocksNeededAfterPatternRepitition > 0) {
var rocksFallenAfterPatternRepetition = 0L
for (rock in rocks) {
chamber.insert(rock, jets)
rocksFallenAfterPatternRepetition += 1
if (rocksFallenAfterPatternRepetition >= rocksNeededAfterPatternRepitition) {
towerHeightOfRocksAfterPatternRepetitions = chamber.calculateHeight() - towerHeightBeforePatternRepeats - towerHeightInASinglePatternRepetition
break
}
}
}
return towerHeightBeforePatternRepeats +
(cyclesOfRepetitionNeeded * towerHeightInASinglePatternRepetition) +
towerHeightOfRocksAfterPatternRepetitions
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day17")
check(part1(testInput) == 3068)
check(part2(testInput) == 1514285714288)
val input = readInput("Day17")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 10,078 | advent-of-code-kotlin-2022 | Apache License 2.0 |
app/src/main/kotlin/me/leon/ext/math/Matrix.kt | Leon406 | 381,644,086 | false | {"Kotlin": 1392660, "JavaScript": 96128, "Java": 16541, "Batchfile": 4706, "Shell": 259, "CSS": 169} | package me.leon.ext.math
import kotlin.math.pow
import kotlin.math.sqrt
fun Array<IntArray>.determinant(n: Int): Int {
var res: Int
if (n == 1) {
res = this[0][0]
} else if (n == 2) {
res = this[0][0] * this[1][1] - this[1][0] * this[0][1]
} else {
res = 0
for (j1 in 0 until n) {
val m = Array(n - 1) { IntArray(n - 1) }
for (i in 1 until n) {
var j2 = 0
for (j in 0 until n) {
if (j == j1) continue
m[i - 1][j2] = this[i][j]
j2++
}
}
res += ((-1.0).pow(1.0 + j1 + 1.0) * this[0][j1] * m.determinant(n - 1)).toInt()
}
}
return res
}
fun List<Int>.reshape(dimension: Int): Array<IntArray> {
require(sqrt(this.size.toDouble()) == dimension.toDouble()) { "wrong dimension or list" }
return chunked(dimension).map { it.toIntArray() }.toTypedArray()
}
/** 乘法模逆元 3*9 == 1 mod 26 3 9的互为关于26的模逆元 */
fun Int.modInverse(modular: Int = 26): Int {
val tmp = this % modular
for (i in 1 until modular) {
if ((tmp * i) % modular == 1) {
return i
}
}
return -1
}
/** 乘法取余 矩阵乘以 矢量 */
fun Array<IntArray>.multMod(col: IntArray, modular: Int): IntArray {
require(this[0].size == col.size) { "col size must be matrix's row" }
return this.foldIndexed(IntArray(col.size)) { i, acc, ints ->
acc.apply { acc[i] = ints.foldIndexed(0) { j, acc2, int -> acc2 + int * col[j] } % modular }
}
}
fun Array<IntArray>.showMatrix() {
println(
">>>>>\tmatrix row $size col ${this[0].size}\n" +
joinToString("\n") { it.joinToString(" ") } +
"\n<<<<<<"
)
}
fun IntArray.showColum() {
println(">>>>>\tcolum ${this.size}\n" + joinToString("\t\n") + "\n<<<<<<")
}
fun Array<IntArray>.invert2(modular: Int = 26): Array<IntArray> {
val a = determinant(size).modInverse(modular)
return arrayOf(
intArrayOf((this[1][1] * a), (-this[0][1] * a)),
intArrayOf((-this[1][0] * a), (this[0][0] * a)),
)
}
fun Array<IntArray>.invertModMatrix(modular: Int = 26): Array<IntArray> {
if (size == 2) {
return invert2(modular)
}
val b: Array<IntArray> = Array(size) { IntArray(size) }
val fac: Array<IntArray> = Array(size) { IntArray(size) }
var p: Int
var m: Int
var n: Int
var i: Int
var j: Int
var q = 0
while (q < size) {
p = 0
while (p < size) {
m = 0
n = 0
i = 0
while (i < size) {
j = 0
while (j < size) {
b[i][j] = 0
if (i != q && j != p) {
b[m][n] = this[i][j]
if (n < size - 2) {
n++
} else {
n = 0
m++
}
}
j++
}
i++
}
fac[q][p] = (-1.0).pow((q + p).toDouble()).toInt() * b.determinant(size - 1)
p++
}
q++
}
return fac.trans(this, size, modular)
}
fun Array<IntArray>.trans(key: Array<IntArray>, r: Int, modular: Int = 26): Array<IntArray> {
var j: Int
val b: Array<IntArray> = Array(r) { IntArray(r) }
val inv: Array<IntArray> = Array(r) { IntArray(r) }
val d = key.determinant(r)
val mi = d.modInverse(modular)
var i = 0
while (i < r) {
j = 0
while (j < r) {
b[i][j] = this[j][i]
j++
}
i++
}
i = 0
while (i < r) {
j = 0
while (j < r) {
inv[i][j] = b[i][j] % modular
if (inv[i][j] < 0) inv[i][j] += modular
inv[i][j] *= mi
inv[i][j] %= modular
j++
}
i++
}
return inv
}
| 4 | Kotlin | 236 | 1,218 | dde1cc6e8e589f4a46b89e2e22918e8b789773e4 | 4,045 | ToolsFx | ISC License |
src/Day05.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | import java.util.*
class Cargo(private val stacks: List<Deque<Char>>) {
companion object Factory {
fun create(description: List<String>): Cargo {
val cargo = Cargo(List<Deque<Char>>(9) { _ -> ArrayDeque() }) // yep, hardcoded amount of stacks
description.reversed().forEach { s -> cargo.addLayer(s) }
return cargo
}
}
fun addLayer(layer: String) {
layer.chunked(4).forEachIndexed { i, box ->
if (box[1] != ' ') {
stacks[i].addLast(box[1])
}
}
}
/*
fun print() {
for (stack in stacks) {
println(stack.joinToString("") { x -> x.toString() })
}
}
*/
class Move(val from: Int, val to: Int, val amount: Int) {
companion object Factory {
fun create(description: String): Move {
val regex = Regex("""move (\d+) from (\d+) to (\d+)""")
val match = regex.matchEntire(description)!!
val groups = match.groups.drop(1)
val ints = groups.map { x -> x!!.value.toInt() }
val (amount, from, to) = ints
return Move(from - 1, to - 1, amount)
}
}
}
fun moveOneByOne(description: Move) {
for (i in 1..description.amount) {
stacks[description.to].addLast(stacks[description.from].removeLast())
}
}
fun moveTogether(description: Move) {
val tmp = ArrayDeque<Char>()
for (i in 1..description.amount) {
tmp.addLast(stacks[description.from].removeLast())
}
for (i in 1..description.amount) {
stacks[description.to].addLast(tmp.removeLast())
}
}
fun getTops(): String {
return stacks.joinToString("") { stack -> stack.last().toString() }
}
}
fun main() {
fun part1(input: List<String>): String {
val cargoDescription = input.takeWhile { s -> s[1] != '1' }
val cargo = Cargo.create(cargoDescription)
// println("Cargo vv")
// cargo.print()
// println("Cargo ^^")
for (i in cargoDescription.size + 2 until input.size) {
cargo.moveOneByOne(Cargo.Move.create(input[i]))
}
return cargo.getTops()
}
fun part2(input: List<String>): String {
val cargoDescription = input.takeWhile { s -> s[1] != '1' }
val cargo = Cargo.create(cargoDescription)
for (i in cargoDescription.size + 2 until input.size) {
cargo.moveTogether(Cargo.Move.create(input[i]))
}
return cargo.getTops()
}
val input = readInput("Day05")
println("Day 5")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 2,742 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | YunxiangHuang | 572,333,905 | false | {"Kotlin": 20157} | import java.util.ArrayList
fun main() {
val input = readInput("Day03")
fun cal(c: Char): Int {
if (c in 'a'..'z') {
return c.code - 'a'.code + 1
}
if (c in 'A'..'Z') {
return c.code - 'A'.code + 27
}
return 0
}
fun partOne() {
var tp = 0
for (rucksack in input) {
var comp = HashMap<Char, Int>(rucksack.length / 2 + 1)
for (c in rucksack.subSequence(0, rucksack.length / 2)) {
comp[c] = comp.getOrDefault(c, 0) + 1
}
var total = 0
var calculated = HashMap<Char, Boolean>(comp.size)
for (c in rucksack.subSequence(rucksack.length / 2, rucksack.length)) {
if (!comp.containsKey(c) || calculated.containsKey(c)) {
continue
}
calculated[c] = true
total += cal(c)
}
tp += total
}
println("Part I: $tp")
}
fun partTwo() {
var group = ArrayList<String>(3)
var total = 0
for (rucksack in input) {
group.add(rucksack)
if (group.size != 3) {
continue
}
var badge = HashMap<Char, Boolean>(group[0].length)
for (c in group[0]) {
badge[c] = true
}
for (m in group.subList(1, group.size)) {
var rm = HashMap<Char, Boolean>(badge.size)
for (b in badge) {
if (!m.contains(b.key, false)) {
rm[b.key] = true
}
}
for (mutableEntry in rm) {
badge.remove(mutableEntry.key)
}
}
for (b in badge) {
total += cal(b.key)
}
group.clear()
}
println("Part II: $total")
}
partOne()
partTwo()
}
| 0 | Kotlin | 0 | 0 | f62cc39dd4881f4fcf3d7493f23d4d65a7eb6d66 | 1,995 | AoC_2022 | Apache License 2.0 |
src/Day10.kt | brigittb | 572,958,287 | false | {"Kotlin": 46744} | import kotlin.math.abs
fun main() {
fun checkSignalStrength(
cycle: Int,
register: Int,
signalStrengths: MutableList<Int>,
) {
if (cycle in listOf(20, 60, 100, 140, 180, 220)) {
signalStrengths.add(register * cycle)
}
}
fun part1(input: List<String>): Int {
var cycle = 0
var register = 1
val signalStrengths = mutableListOf<Int>()
input
.filter { it.isNotEmpty() }
.forEach {
if (it.contains("noop")) {
cycle++
checkSignalStrength(cycle, register, signalStrengths)
} else {
val value = it.substringAfter(" ").toInt()
repeat(2) {
cycle++
checkSignalStrength(cycle, register, signalStrengths)
}
register += value
}
}
return signalStrengths.sum()
}
fun drawPixel(register: Int, cycle: Int) {
if (abs(register - (cycle % 40)) <= 1) print("#") else print(".")
if ((cycle + 1) % 40 == 0) println()
}
fun part2(input: List<String>) {
var cycle = 0
var register = 1
input
.filter { it.isNotEmpty() }
.forEach {
if (it.contains("noop")) {
drawPixel(register, cycle)
cycle++
} else {
val value = it.substringAfter(" ").toInt()
repeat(2) {
drawPixel(register, cycle)
cycle++
}
register += value
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | 470f026f2632d1a5147919c25dbd4eb4c08091d6 | 2,007 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ArithmeticSubarrays.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 1630. Arithmetic Subarrays
* @see <a href="https://leetcode.com/problems/arithmetic-subarrays">Source</a>
*/
fun interface ArithmeticSubarrays {
operator fun invoke(nums: IntArray, l: IntArray, r: IntArray): List<Boolean>
}
class ArithmeticSubarraysSort : ArithmeticSubarrays {
override fun invoke(nums: IntArray, l: IntArray, r: IntArray): List<Boolean> {
val ans: MutableList<Boolean> = ArrayList()
for (i in l.indices) {
val arr = IntArray(r[i] - l[i] + 1)
for (j in arr.indices) {
arr[j] = nums[l[i] + j]
}
ans.add(check(arr))
}
return ans
}
private fun check(arr: IntArray): Boolean {
arr.sort()
val diff = arr[1] - arr[0]
for (i in 2 until arr.size) {
if (arr[i] - arr[i - 1] != diff) {
return false
}
}
return true
}
}
class ArithmeticSubarraysSet : ArithmeticSubarrays {
override fun invoke(nums: IntArray, l: IntArray, r: IntArray): List<Boolean> {
val ans: MutableList<Boolean> = ArrayList()
for (i in l.indices) {
val arr = IntArray(r[i] - l[i] + 1)
for (j in arr.indices) {
arr[j] = nums[l[i] + j]
}
ans.add(check(arr))
}
return ans
}
private fun check(arr: IntArray): Boolean {
var minElement = Int.MAX_VALUE
var maxElement = Int.MIN_VALUE
val arrSet: MutableSet<Int> = HashSet()
for (num in arr) {
minElement = min(minElement, num)
maxElement = max(maxElement, num)
arrSet.add(num)
}
if ((maxElement - minElement) % (arr.size - 1) != 0) {
return false
}
val diff = (maxElement - minElement) / (arr.size - 1)
var curr = minElement + diff
while (curr < maxElement) {
if (!arrSet.contains(curr)) {
return false
}
curr += diff
}
return true
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,763 | kotlab | Apache License 2.0 |
src/Day06.kt | buczebar | 572,864,830 | false | {"Kotlin": 39213} | fun main() {
fun solve(input: String, distLength: Int) =
input.indexOf(input.windowed(distLength).first { it.toList().allDistinct()}) + distLength
fun part1(input: String) = solve(input, 4)
fun part2(input: String) = solve(input, 14)
val testInput = readInput("Day06_test")
val testResults = listOf(
7 to 19, // mjqjpqmgbljsphdztnvjfqwrcgsmlb
5 to 23, // bvwbjplbgvbhsrlpgdmjqwftvncz
6 to 23, // nppdvjthqldpwncqszvftbrmjlhg
10 to 29, // nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg
11 to 26 // zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw
)
testInput.zip(testResults).forEach { (input, results) ->
check(part1(input) == results.first)
check(part2(input) == results.second)
}
val input = readInput("Day06").first()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cdb6fe3996ab8216e7a005e766490a2181cd4101 | 849 | advent-of-code | Apache License 2.0 |
calendar/day05/Day5.kt | mpetuska | 571,764,215 | false | {"Kotlin": 18073} | package day05
import Day
import Lines
class Day5 : Day() {
override fun part1(input: Lines): Any {
val (rows, stackIds) = input.takeWhile(String::isNotBlank).let {
it.dropLast(1)
.map { row ->
row.chunked(4).map(String::trim).map { item -> item.removeSurrounding("[", "]") }
} to it.last().split(" +".toRegex()).filter(String::isNotBlank).map(String::toInt)
}
val stacks = buildMap {
stackIds.forEach { id ->
val stack = rows.indices.reversed().mapNotNull { i ->
val r = rows[i]
r.getOrNull(id - 1)
}.filter(String::isNotBlank).toMutableList()
put(id, stack)
}
}
input.drop(rows.size + 2)
.takeWhile(String::isNotBlank)
.map { it.split(" ").drop(1) }
.map { (count, _, from, _, to) -> Triple(count.toInt(), from.toInt(), to.toInt()) }
.forEach { (count, from, to) ->
repeat(count) { stacks[from]!!.removeLast().let(stacks[to]!!::add) }
}
return stackIds.mapNotNull(stacks::get).joinToString("", transform = List<String>::last)
}
override fun part2(input: Lines): Any {
val (rows, stackIds) = input.takeWhile(String::isNotBlank).let {
it.dropLast(1)
.map { row ->
row.chunked(4).map(String::trim).map { item -> item.removeSurrounding("[", "]") }
} to it.last().split(" +".toRegex()).filter(String::isNotBlank).map(String::toInt)
}
val stacks = buildMap {
stackIds.forEach { id ->
val stack = rows.indices.reversed().mapNotNull { i ->
val r = rows[i]
r.getOrNull(id - 1)
}.filter(String::isNotBlank).toMutableList()
put(id, stack)
}
}
input.drop(rows.size + 2)
.takeWhile(String::isNotBlank)
.map { it.split(" ").drop(1) }
.map { (count, _, from, _, to) -> Triple(count.toInt(), from.toInt(), to.toInt()) }
.forEach { (count, from, to) ->
// Alternative: stacks[from]!!.let { it.subList(it.size - count, it.size) }.also(stacks[to]!!::addAll).clear()
val target = stacks[to]!!
val idx = target.size
repeat(count) { stacks[from]!!.removeLast().let { target.add(idx, it) } }
}
return stackIds.mapNotNull(stacks::get).joinToString("", transform = List<String>::last)
}
} | 0 | Kotlin | 0 | 0 | be876f0a565f8c14ffa8d30e4516e1f51bc3c0c5 | 2,301 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/leetcode/UniquePaths.kt | ykrytsyn | 424,099,758 | false | {"Kotlin": 8270} | package leetcode
/**
* # 62. Unique Paths
* [https://leetcode.com/problems/unique-paths/](https://leetcode.com/problems/unique-paths/)
*
* ### A robot is located at the top-left corner of 'm x n' grid (marked 'Start' in the diagram below).
* ### The robot can only move either down or right at any point in time.
* ### The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
*
* ### How many possible unique paths are there?
*
*/
class UniquePaths {
fun dynamicProgramming(m: Int, n: Int): Int {
val grid: Array<IntArray> = Array(m) { IntArray(n) }
for (i in m - 1 downTo 0) {
for (j in n - 1 downTo 0) {
if (i == m - 1 || j == n - 1) {
grid[i][j] = 1
} else {
grid[i][j] = grid[i + 1][j] + grid[i][j + 1]
}
}
}
return grid[0][0];
}
fun recursive(m: Int, n: Int): Int {
if (m == 1 || n == 1) {
return 1
}
return recursive(m - 1, n) + recursive(m, n - 1)
}
}
| 0 | Kotlin | 0 | 0 | 0acf2a677f8b4a1777b12688cf48bf420353e040 | 1,119 | leetcode-in-kotlin | Apache License 2.0 |
src/hongwei/leetcode/playground/leetcodecba/M1466ReorderRoutes2MakeAllPathsLead2theCityZero.kt | hongwei-bai | 201,601,468 | false | {"Java": 143669, "Kotlin": 38875} | package hongwei.leetcode.playground.leetcodecba
import hongwei.leetcode.playground.common.print
class M1466ReorderRoutes2MakeAllPathsLead2theCityZero {
fun test() {
val testData = listOf(
arrayOf(
6,
arrayOf(intArrayOf(0, 1), intArrayOf(1, 3), intArrayOf(2, 3), intArrayOf(4, 0), intArrayOf(4, 5)),
3
),
arrayOf(
5,
arrayOf(intArrayOf(1, 0), intArrayOf(1, 2), intArrayOf(3, 2), intArrayOf(3, 4)),
2
),
arrayOf(
5,
arrayOf(intArrayOf(4, 3), intArrayOf(2, 3), intArrayOf(1, 2), intArrayOf(1, 0)),
2
)
)
val onlyTestIndex = 2
testData.forEachIndexed { i, data ->
if (!(onlyTestIndex >= 0 && onlyTestIndex != i)) {
val input1 = data[0] as Int
val input2 = data[1] as Array<IntArray>
val expectedOutput = data[2] as Int
val output = minReorder(input1, input2)
if (expectedOutput == output) {
println("test[$i] passed.")
} else {
println("test[$i] FAILED!")
println(output)
}
}
}
}
fun minReorder(n: Int, connections: Array<IntArray>): Int {
val reachableCities = hashSetOf<Int>().apply { add(0) }
var count = 0
val toProcessCityList = mutableListOf<IntArray>().apply {
addAll(connections)
}
val toProcessCityListNextRound: MutableList<IntArray> = mutableListOf()
while (toProcessCityList.isNotEmpty()) {
toProcessCityListNextRound.clear()
for (i in toProcessCityList.indices) {
val departureCity = toProcessCityList[i].first()
val destinationCity = toProcessCityList[i].last()
if (reachableCities.contains(destinationCity)) {
reachableCities.add(departureCity)
} else if (reachableCities.contains(departureCity)) {
count++
reachableCities.add(destinationCity)
} else {
toProcessCityListNextRound.add(toProcessCityList[i])
}
}
toProcessCityList.clear()
toProcessCityList.addAll(toProcessCityListNextRound)
}
return count
}
}
/*
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/
*/ | 0 | Java | 0 | 1 | 9d871de96e6b19292582b0df2d60bbba0c9a895c | 2,597 | leetcode-exercise-playground | Apache License 2.0 |
kotlin/src/_0018_0.kt | yunshuipiao | 179,794,004 | false | null | import org.testng.annotations.Test
/**
* 常规解法
*/
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val result = arrayListOf<ArrayList<Int>>()
if (nums.size < 4) {
return result
}
nums.sort()
var index = 0
while (index < nums.size) {
if (index > 0 && nums[index] == nums[index - 1]) {
} else {
val tempNums = nums.filterIndexed { i, v -> i > index }.toIntArray()
val tResult = threeSum(tempNums, target - nums[index])
tResult.forEach {
val l = it as ArrayList
l.add(nums[index])
result.add(l)
}
}
index += 1
}
return result
}
fun threeSum(nums: IntArray, target: Int): List<List<Int>> {
val result = arrayListOf<ArrayList<Int>>()
val tempNums = nums
if (tempNums.size < 3) {
return result
}
tempNums.sort()
for (index in 0..tempNums.size - 3) {
if (index - 1 >= 0 && tempNums[index - 1] == tempNums[index]) {
continue
}
var l = index + 1
var r = tempNums.size - 1
while (l < r) {
val sum = tempNums[index] + tempNums[l] + tempNums[r]
if (sum > target) {
do {
r -= 1
} while (r > l && tempNums[r] == tempNums[r + 1])
} else if (sum < target) {
do {
l += 1
} while (r > l && tempNums[l] == tempNums[l - 1])
} else {
result.add(arrayListOf(tempNums[index], tempNums[l], tempNums[r]))
do {
r -= 1
} while (r > l && tempNums[r] == tempNums[r + 1])
do {
l += 1
} while (r > l && tempNums[l] == tempNums[l - 1])
}
}
}
return result
}
// wrong answer
//fun fourSum2(nums: IntArray, target: Int): List<List<Int>> {
// fun findNsum(l: Int, r: Int, target: Int, n: Int, result: ArrayList<Int>, results: ArrayList<ArrayList<Int>>) {
// if (r - l + 1 < n || n < 2 || target < nums[l] * n || target > nums[r] * n) {
// return
// }
// println(result)
// var l1 = l
// var r1 = r
// if (n == 2) {
// while (l1 < r1) {
// val s = nums[l1] + nums[r1]
// if (s == target) {
// result.add(nums[l1])
// result.add(nums[r1])
// results.add(result)
//// println(results)
// l1 += 1
// while (l1 < r1 && nums[l1] == nums[l1 - 1]) {
// l1 += 1
// }
// } else if (s > target) {
// r1 -= 1
// } else {
// l1 += 1
// }
// }
// } else {
// for (i in l until r + 1) {
// if (i == l || (i > l && nums[i - 1] != nums[i])) {
// result.add(nums[i])
// findNsum(i + 1, r, target - nums[i], n - 1, result, results)
// }
// }
// }
// }
//
// val results = arrayListOf<ArrayList<Int>>()
// if (nums.size < 4) {
// return results
// }
// nums.sort()
// findNsum(0, nums.size - 1, target, 4, arrayListOf(), results)
// return results
//}
@Test
fun _0018() {
arrayListOf(intArrayOf(-1, -5, -5, -3, 2, 5, 0, 4)).forEach {
fourSum(it, -7).forEach {
println(it)
}
}
}
| 29 | Kotlin | 0 | 2 | 6b188a8eb36e9930884c5fa310517be0db7f8922 | 3,620 | rice-noodles | Apache License 2.0 |
src/day21/Day21.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day21
import readInput
import kotlin.math.abs
private const val DAY_ID = "21"
private enum class Operator : (Long, Long) -> Long {
ADD {
override fun invoke(a: Long, b: Long): Long = a + b
},
SUBS {
override fun invoke(a: Long, b: Long): Long = a - b
},
MULT {
override fun invoke(a: Long, b: Long): Long = a * b
},
DIV {
override fun invoke(a: Long, b: Long): Long = a / b
};
companion object {
fun fromString(s: String): Operator = when (s) {
"+" -> ADD
"-" -> SUBS
"*" -> MULT
"/" -> DIV
else -> error("Unknown operation: $s")
}
}
}
private sealed class Monkey {
abstract val name: String
data class Primitive(
override val name: String,
val x: Long
) : Monkey()
data class Math(
override val name: String,
val other1: String,
val other2: String,
val op: Operator
) : Monkey()
}
private sealed interface Eval {
fun invoke(op: Operator, other: Eval): Eval
// single number
data class Numeric(val x: Long) : Eval {
override fun invoke(op: Operator, other: Eval): Eval = when (other) {
is Numeric -> Numeric(op(x, other.x))
is Symbolic -> when (op) {
// special case: handle x on the right side of expression:
// a - x <-> x * (-1) + a
Operator.SUBS -> other.invoke(Operator.MULT, Numeric(-1)).invoke(Operator.ADD, this)
Operator.DIV -> error("Unexpected a / x expression")
else -> other.invoke(op, this)
}
}
}
// p * x + q
data class Symbolic(val p: Long, val q: Long, val d: Long) : Eval {
companion object {
val BASIC = Symbolic(1, 0, 1)
}
override fun invoke(op: Operator, other: Eval): Eval = when (other) {
is Numeric -> when (op) {
Operator.ADD -> {
Symbolic(p, q + other.x * d, d)
}
Operator.SUBS -> {
Symbolic(p, q - other.x * d, d)
}
Operator.MULT -> {
val gcd = gcd(other.x, d)
val m = other.x / gcd
Symbolic(p * m, q * m, d / gcd)
}
Operator.DIV -> {
val sign = compareValues(other.x, 0)
val gcd = gcd(gcd(p, q), other.x)
Symbolic(p / gcd * sign, q / gcd * sign, other.x / gcd * d)
}
}
else -> error("Can't evaluate <symbolic> <operator> <symbolic> expression")
}
private fun gcd(a: Long, b: Long): Long {
fun gcdRec(a: Long, b: Long): Long {
return if (b == 0L) a else gcdRec(b, a % b)
}
return gcdRec(abs(a), abs(b))
}
}
}
fun main() {
fun parseInput(input: List<String>): List<Monkey> {
val math = """([a-z]{4}) ([+\-*/]) ([a-z]{4})""".toRegex()
return input.map { line ->
val (name, expression) = line.split(": ")
if (expression[0].isDigit()) {
Monkey.Primitive(name, expression.toLong())
} else {
val (other1, op, other2) = math.find(expression)!!.destructured
Monkey.Math(name, other1, other2, Operator.fromString(op))
}
}
}
fun part1(input: List<String>): Long {
val lookup = parseInput(input).associateBy { it.name }
fun evaluate(name: String): Long = with(lookup[name]!!) {
when (this) {
is Monkey.Primitive -> x
is Monkey.Math -> {
val lhs = evaluate(other1)
val rhs = evaluate(other2)
op(lhs, rhs)
}
}
}
return evaluate("root")
}
fun part2(input: List<String>): Long {
val lookup = parseInput(input).associateBy { it.name }
fun evaluate(name: String): Eval = with(lookup[name]!!) {
when (this) {
is Monkey.Primitive -> {
if (name == "humn") Eval.Symbolic.BASIC else Eval.Numeric(x)
}
is Monkey.Math -> {
val lhs = evaluate(other1)
val rhs = evaluate(other2)
lhs.invoke(op, rhs)
}
}
}
val root = lookup["root"] as Monkey.Math
val lhs = evaluate(root.other1)
val rhs = evaluate(root.other2)
fun yell(lhs: Eval, rhs: Eval): Long {
// (p * x + q) / d = c
// p * x + q = c * d
// x = (c * d - q) / p
fun doYell(lhs: Eval.Symbolic, rhs: Eval.Numeric): Long {
return (rhs.x * lhs.d - lhs.q) / lhs.p
}
return when {
lhs is Eval.Symbolic && rhs is Eval.Numeric -> doYell(lhs, rhs)
rhs is Eval.Symbolic && lhs is Eval.Numeric -> doYell(rhs, lhs)
else -> error("Expected exactly one symbolic expression, but got: $lhs, $rhs")
}
}
return yell(lhs, rhs)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 152L)
check(part2(testInput) == 301L)
val input = readInput("day${DAY_ID}/Day${DAY_ID}")
println(part1(input)) // answer = 70674280581468
println(part2(input)) // answer = 3243420789721
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 5,680 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Day24.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | import java.util.UUID
import kotlin.collections.ArrayDeque
fun main() {
val input = readFileAsList("Day24")
println(Day24.part1(input))
println(Day24.part2(input))
}
object Day24 {
private val start = Vector2d(2, 1)
fun part1(input: List<String>): Long {
val (maxXBlizzard, maxYBlizzard, goal) = calculateMapConstraints(input)
val blizzardsUnique = findUniqueBlizzards(input, maxXBlizzard, maxYBlizzard)
val bestPath = findPath(goal, blizzardsUnique, maxXBlizzard, maxYBlizzard, Path(listOf(start)))
return bestPath.size - 1L
}
fun part2(input: List<String>): Long {
val (maxXBlizzard, maxYBlizzard, goal) = calculateMapConstraints(input)
val blizzardsUnique = findUniqueBlizzards(input, maxXBlizzard, maxYBlizzard)
var path = findPath(goal, blizzardsUnique, maxXBlizzard, maxYBlizzard, Path(listOf(start)))
path = findPath(start, blizzardsUnique, maxXBlizzard, maxYBlizzard, path)
path = findPath(goal, blizzardsUnique, maxXBlizzard, maxYBlizzard, path)
return path.size - 1L
}
private fun findUniqueBlizzards(
input: List<String>,
maxXBlizzard: Int,
maxYBlizzard: Int
): MutableSet<Set<Blizzard>> {
val blizzards = parseBlizzards(input)
val blizzardsUnique = mutableSetOf<Set<Blizzard>>(blizzards)
while (true) {
val next = blizzardsUnique.last()
.map { it.next(maxXBlizzard, maxYBlizzard) }
.toSet()
if (blizzardsUnique.contains(next)) {
break
}
blizzardsUnique.add(next)
}
return blizzardsUnique
}
private fun findPath(
goal: Vector2d,
blizzardsUnique: MutableSet<Set<Blizzard>>,
maxXBlizzard: Int,
maxYBlizzard: Int,
startPath: Path
): Path {
val queue = ArrayDeque<Path>()
queue.add(startPath)
val seenOne = mutableSetOf<Pair<Position2d, Set<Blizzard>>>()
while (queue.isNotEmpty()) {
val path = queue.removeFirst()
val currentPosition = path.positions.last()
if (currentPosition == goal) {
return path
}
val currentBlizzards = getNextBlizzardPositions(path, blizzardsUnique)
val positionBlizzardsPair = currentPosition to currentBlizzards
if (seenOne.contains(positionBlizzardsPair)) {
continue
}
seenOne.add(positionBlizzardsPair)
val currentBlizzardPositions = currentBlizzards.map { it.position }.toSet()
val up = currentPosition + Direction.UP.vector
val right = currentPosition + Direction.RIGHT.vector
val down = currentPosition + Direction.DOWN.vector
val left = currentPosition + Direction.LEFT.vector
val currentIsBlizzard = currentBlizzardPositions.contains(currentPosition)
val rightIsBlizzard = currentBlizzardPositions.contains(right)
val downIsBlizzard = currentBlizzardPositions.contains(down)
val upIsBlizzard = currentBlizzardPositions.contains(up)
val leftIsBlizzard = currentBlizzardPositions.contains(left)
val rightIsValid = (!rightIsBlizzard && isValidPosition(right, maxXBlizzard, maxYBlizzard, goal))
val downIsValid = (!downIsBlizzard && isValidPosition(down, maxXBlizzard, maxYBlizzard, goal))
val upIsValid = (!upIsBlizzard && isValidPosition(up, maxXBlizzard, maxYBlizzard, goal))
val leftIsValid = (!leftIsBlizzard && isValidPosition(left, maxXBlizzard, maxYBlizzard, goal))
if (downIsValid) {
val newPath = Path(path.positions + down)
queue.add(newPath)
}
if (rightIsValid) {
val newPath = Path(path.positions + right)
queue.add(newPath)
}
if (upIsValid) {
val newPath = Path(path.positions + up)
queue.add(newPath)
}
if (leftIsValid) {
val newPath = Path(path.positions + left)
queue.add(newPath)
}
if (!currentIsBlizzard) {
queue.add(Path(path.positions + currentPosition))
}
}
throw RuntimeException("Could not find path")
}
private fun calculateMapConstraints(input: List<String>): Triple<Int, Int, Vector2d> {
val maxXBlizzard = input[0].length - 1
val maxYBlizzard = input.size - 1
val goal = Vector2d(maxXBlizzard, maxYBlizzard + 1)
return Triple(maxXBlizzard, maxYBlizzard, goal)
}
private fun getNextBlizzardPositions(
path: Path,
blizzardsUnique: MutableSet<Set<Blizzard>>
): Set<Blizzard> {
val blizzardsIndex = path.positions.size % blizzardsUnique.size
return blizzardsUnique.elementAt(blizzardsIndex)
}
private fun isValidPosition(position: Position2d, maxXBlizzard: Int, maxYBlizzard: Int, goal: Position2d) =
isInConstraints(position, maxXBlizzard, maxYBlizzard) || position == goal
private fun isInConstraints(position: Position2d, maxX: Int, maxY: Int): Boolean {
return position.x in 2..maxX && position.y in 2..maxY
}
private fun parseBlizzards(input: List<String>): MutableSet<Blizzard> {
val blizzards = mutableSetOf<Blizzard>()
for ((y, line) in input.withIndex()) {
for ((x, c) in line.withIndex()) {
val position = Vector2d(x + 1, y + 1)
if (c == '^') {
val blizzard = Blizzard(position, Direction.UP)
blizzards.add(blizzard)
}
if (c == '>') {
val blizzard = Blizzard(position, Direction.RIGHT)
blizzards.add(blizzard)
}
if (c == 'v') {
val blizzard = Blizzard(position, Direction.DOWN)
blizzards.add(blizzard)
}
if (c == '<') {
val blizzard = Blizzard(position, Direction.LEFT)
blizzards.add(blizzard)
}
}
}
return blizzards
}
data class Blizzard(val position: Position2d, val direction: Direction, val id: UUID = UUID.randomUUID()) : Position2d by position {
fun next(maxXBlizzard: Int, maxYBlizzard: Int): Blizzard {
var nextPosition = position + direction.vector
if (nextPosition.x > maxXBlizzard) {
nextPosition = Vector2d(2, nextPosition.y)
}
if (nextPosition.x < 2) {
nextPosition = Vector2d(maxXBlizzard, nextPosition.y)
}
if (nextPosition.y > maxYBlizzard) {
nextPosition = Vector2d(nextPosition.x, 2)
}
if (nextPosition.y < 2) {
nextPosition = Vector2d(nextPosition.x, maxYBlizzard)
}
return this.copy(position = nextPosition)
}
}
enum class Direction(val vector: Vector2d) {
UP(Vector2d(0, -1)),
RIGHT(Vector2d(1, 0)),
DOWN(Vector2d(0, 1)),
LEFT(Vector2d(-1, 0))
}
data class Path(val positions: List<Position2d>): List<Position2d> by positions
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 7,440 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | wooodenleg | 572,658,318 | false | {"Kotlin": 30668} | object Day10 {
const val xKey = "x"
sealed interface Instruction {
fun Processor.onTick(): Boolean
class AddX(private val number: Int) : Instruction {
private var initialTick = true
override fun Processor.onTick(): Boolean =
if (initialTick) {
initialTick = false
false
} else {
val currentValue = register.getValue(xKey)
register[xKey] = currentValue + number
true
}
}
object NoOp : Instruction {
override fun Processor.onTick(): Boolean = true
}
}
class Processor {
val register = mutableMapOf("x" to 1)
private val scheduledInstructions = ArrayDeque<Instruction>()
fun scheduleInstructions(instructions: List<Instruction>) {
for (ins in instructions) scheduledInstructions.addLast(ins)
}
fun tick() {
if (scheduledInstructions.isEmpty()) return
with(scheduledInstructions.first()) {
if (onTick()) scheduledInstructions.removeFirst()
}
}
}
fun parseInstructions(input: List<String>) = input.map { line ->
val words = line.split(" ")
when (words[0]) {
"noop" -> Instruction.NoOp
else -> Instruction.AddX(words[1].toInt())
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val cpu = Day10.Processor()
cpu.scheduleInstructions(Day10.parseInstructions(input))
val cycleMarks = listOf(20, 60, 100, 140, 180, 220)
var strength = 0
for (cycle in 1..220) {
if (cycle in cycleMarks) {
val registerValue = cpu.register.getValue(Day10.xKey)
strength += cycle * registerValue
}
cpu.tick()
}
return strength
}
fun part2(input: List<String>): String {
val cpu = Day10.Processor()
cpu.scheduleInstructions(Day10.parseInstructions(input))
return buildString {
for (cycle in 0..239) {
val registerValue = cpu.register.getValue(Day10.xKey)
val spritePosition = cycle % 40
val spriteRange = spritePosition - 1..spritePosition + 1
if (spritePosition == 0 && cycle > 1) appendLine()
append(if (registerValue in spriteRange) "#" else ".")
cpu.tick()
}
}
}
val testInput = readInputLines("Day10_test")
check(part1(testInput) == 13140)
check(
part2(testInput) == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
)
val input = readInputLines("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | ff1f3198f42d1880e067e97f884c66c515c8eb87 | 3,109 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/juuxel/basiks/iterable/CombinedIterable.kt | Juuxel | 143,861,676 | false | null | package juuxel.basiks.iterable
/**
* A combined iterable of types [A] and [B].
*
* @param outer the outer iterable of type [A]
* @param inner the inner iterable of type [B]
*/
private class CombinedIterable<A, B>(
private val outer: Iterable<A>,
private val inner: Iterable<B>
): Iterable<Pair<A, B>> {
override fun iterator() = outer.flatMap { i ->
inner.map { j ->
i to j
}
}.iterator()
}
/**
* Combines the two iterables.
*
* ### Example
* ```
* val letters = listOf('A', 'B', 'C')
* val numbers = listOf(1, 2, 3)
*
* for ((letter, number) in combine(letters, numbers))
* println("$letter + $number")
*
* Output:
* A: 1
* A: 2
* A: 3
* B: 1
* B: 2
* B: 3
* C: 1
* C: 2
* C: 3
* ```
*/
fun <A, B> combine(outer: Iterable<A>, inner: Iterable<B>): Iterable<Pair<A, B>> =
CombinedIterable(outer, inner)
inline fun <A, B, R> Iterable<Pair<A, B>>.map(transform: (A, B) -> R): List<R> =
map { (a, b) -> transform(a, b) }
inline fun <A, B, R> Iterable<Pair<A, B>>.flatMap(transform: (A, B) -> Iterable<R>): List<R> =
flatMap { (a, b) -> transform(a, b) }
| 0 | Kotlin | 0 | 0 | 411506cb2f357bed0e937e11fc74a9f184de74f1 | 1,141 | Basiks | MIT License |
app/src/test/java/com/zwq65/unity/algorithm/unionfind/LeetCode990.kt | Izzamuzzic | 95,655,850 | false | {"Kotlin": 449365, "Java": 17918} | package com.zwq65.unity.algorithm.unionfind
import org.junit.Test
/**
* ================================================
* <p>
* <a href="https://leetcode-cn.com/problems/satisfiability-of-equality-equations/">990. 等式方程的可满足性</a>.
* Created by NIRVANA on 2019/7/15.
* Contact with <<EMAIL>>
* ================================================
*/
class LeetCode990 {
@Test
fun test() {
val array = arrayOf("a==b", "b==c", "a==c", "c!=b")
val answer = equationsPossible(array)
print("answer:$answer")
}
private fun equationsPossible(equations: Array<String>): Boolean {
var uf = UF(26)
for (str in equations) {
if (str[1] == '=') {
uf.union(str[0] - 'a', str[3] - 'a')
}
}
for (str in equations) {
if (str[1] == '!' && uf.find(str[0] - 'a') == uf.find(str[3] - 'a')) {
return false
}
}
return true
}
class UF(size: Int) {
private var parent = IntArray(size)
init {
//初始化:parent指向本身
for (i in 0 until size) {
parent[i] = i
}
}
fun find(x: Int): Int {
return if (x == parent[x]) {
x
} else {
parent[x] = find(parent[x])
find(parent[x])
}
}
fun union(x: Int, y: Int) {
parent[find(x)] = parent[find(y)]
}
}
}
| 0 | Kotlin | 0 | 0 | 98a9ad7bb298d0b0cfd314825918a683d89bb9e8 | 1,554 | Unity | Apache License 2.0 |
src/main/kotlin/com/github/leandroborgesferreira/dagcommand/logic/NodeList.kt | krgauthi | 356,499,213 | true | {"Kotlin": 30804} | package com.github.leandroborgesferreira.dagcommand.logic
import com.github.leandroborgesferreira.dagcommand.domain.AdjacencyList
import com.github.leandroborgesferreira.dagcommand.domain.Node
import java.util.*
fun findRootNodes(adjacencyList: AdjacencyList) = adjacencyList.keys - adjacencyList.values.flatten()
fun nodesData(adjacencyList: AdjacencyList): List<Node> {
val edges = createEdgeList(adjacencyList)
val nodeList: List<Node> = adjacencyList.keys.map { module ->
Node(name = module, buildStage = 0, instability = calculateInstability(module, edges, adjacencyList.keys.size))
}
return calculateBuildStages(nodeList, adjacencyList)
}
fun List<Node>.groupByStages(): Map<Int, List<String>> =
groupBy { buildStage ->
buildStage.buildStage
}.mapValues { (_, stageList) ->
stageList.map { it.name }
}.toSortedMap()
private fun calculateBuildStages(nodeList: List<Node>, adjacencyList: AdjacencyList): List<Node> {
val modulesQueue: Queue<String> = LinkedList<String>().apply {
addAll(findRootNodes(adjacencyList))
}
var currentStage = 0
while (modulesQueue.isNotEmpty()) {
nodeList.filter { (module, _) ->
modulesQueue.contains(module)
}.forEach { moduleBuildStage ->
moduleBuildStage.buildStage = currentStage
}
val modulesOfNextLevel = modulesQueue.mapNotNull { module ->
adjacencyList[module]
}.reduce { acc, set -> acc + set }
modulesQueue.clear()
modulesQueue.addAll(modulesOfNextLevel)
currentStage++
}
return nodeList
}
| 0 | Kotlin | 0 | 0 | 9c603e3d36b863bdd5740b70fb4a3cd8463f1116 | 1,628 | dag-command | Apache License 2.0 |
year2022/src/main/kotlin/net/olegg/aoc/year2022/day9/Day9.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2022.day9
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions
import net.olegg.aoc.utils.Directions.DL
import net.olegg.aoc.utils.Directions.DR
import net.olegg.aoc.utils.Directions.UL
import net.olegg.aoc.utils.Directions.UR
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2022.DayOf2022
import kotlin.math.absoluteValue
/**
* See [Year 2022, Day 9](https://adventofcode.com/2022/day/9)
*/
object Day9 : DayOf2022(9) {
private val DIAGONALS = listOf(UL, UR, DL, DR)
override fun first(): Any? {
return solve(2)
}
override fun second(): Any? {
return solve(10)
}
private fun solve(size: Int): Int {
val moves = lines
.map { it.split(" ").toPair() }
.asSequence()
.flatMap { (direction, step) ->
List(step.toInt()) { Directions.valueOf(direction) }
}
val visited = mutableSetOf(Vector2D())
moves.fold(List(size) { Vector2D() }) { oldRope, move ->
val newRope = oldRope.drop(1).runningFold(oldRope.first() + move.step) { head, curr ->
val dist = head - curr
when {
dist.x.absoluteValue <= 1 && dist.y.absoluteValue <= 1 -> curr
dist.manhattan() == 2 -> curr + dist / 2
else -> DIAGONALS.map { curr + it.step }.minBy { (head - it).manhattan() }
}
}
visited += newRope.last()
newRope
}
return visited.size
}
}
fun main() = SomeDay.mainify(Day9)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,501 | adventofcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxVowels.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
/**
* 1456. Maximum Number of Vowels in a Substring of Given Length
* @see <a href="https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length">
* Source</a>
*/
fun interface MaxVowels {
operator fun invoke(s: String, k: Int): Int
}
class MaxVowelsSlidingWindow : MaxVowels {
override operator fun invoke(s: String, k: Int): Int {
val vowels = setOf('a', 'e', 'i', 'o', 'u')
// Build the window of size k, count the number of vowels it contains.
var count = 0
for (i in 0 until k) {
count += if (vowels.contains(s[i])) 1 else 0
}
var answer = count
// Slide the window to the right, focus on the added character and the
// removed character and update "count". Record the largest "count".
for (i in k until s.length) {
count += if (vowels.contains(s[i])) 1 else 0
count -= if (vowels.contains(s[i - k])) 1 else 0
answer = Math.max(answer, count)
}
return answer
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,695 | kotlab | Apache License 2.0 |
src/main/kotlin/grappolo/SimilarityMatrix.kt | xrrocha | 264,292,094 | false | null | package grappolo
class SimilarityMatrix(val size: Int) {
private val similarities = mutableSetOf<Double>()
inner class Vector(private val parentIndex: Int) {
private val elements = mutableMapOf(parentIndex to 1.0)
operator fun get(index: Int): Double {
validateIndex(index)
return elements.getOrDefault(index, 0.0)
}
operator fun set(index: Int, similarity: Double) {
validateIndex(index)
require(!elements.containsKey((index))) { "Reassignment to similarity value with index $index" }
elements[index] = similarity
}
fun elementsAbove(minSimilarity: Double, available: Set<Int>): Set<Int> =
elements.filter { entry -> entry.value >= minSimilarity && available.contains(entry.key) }.keys
fun closestElements(minSimilarity: Double, available: Set<Int>): Set<Int> {
val siblings = elementsAbove(minSimilarity, available) - parentIndex
val maxSimilarity = siblings.map { this[it] }.max()
val set =
if (maxSimilarity == null) {
emptySet()
} else {
siblings.filter { this[it] == maxSimilarity }.toSet()
}
return set + parentIndex
}
}
private val vectors = Array(size) { Vector(it) }
operator fun get(index: Int): Vector {
validateIndex(index)
return vectors[index]
}
fun addSimilarity(index1: Int, index2: Int, similarity: Double) {
require(index1 != index2 || similarity == 1.0) {
"Identity similarity must be 1.0, not $similarity"
}
this[index1][index2] = similarity
this[index2][index1] = similarity
similarities += similarity
}
fun distinctSimilarities(): Set<Double> = similarities.toSet()
private fun validateIndex(index: Int) {
require(index in 0 until size) {
"Index out of bounds: $index; should be between 0 and $size"
}
}
}
| 0 | Kotlin | 0 | 0 | 93a065ab98d5551bc2f2e39ff4b069d524e04870 | 2,139 | grappolo-kotlin | Apache License 2.0 |
src/Day09.kt | GarrettShorr | 571,769,671 | false | {"Kotlin": 82669} | import kotlin.math.abs
fun main() {
fun moveTail(frontX: Int, frontY: Int, tail: Pair<Int, Int>) : Pair<Int, Int> {
var (tailX, tailY) = tail
// diagonal move
if(frontX != tailX && frontY != tailY) {
if(abs(frontX - tailX) == 2 || abs(frontY - tailY) == 2) {
if(frontX < tailX) {
tailX--
} else {
tailX++
}
if(frontY > tailY) {
tailY++
} else {
tailY--
}
}
} else if(frontX - tailX == 2) {
tailX++
} else if(tailX - frontX == 2) {
tailX--
} else if(frontY - tailY == 2) {
tailY++
} else if(tailY - frontY == 2) {
tailY--
}
return Pair(tailX, tailY)
}
fun part1(input: List<String>): Int {
var head = Pair(0, 0)
var tail = Pair(0, 0)
var tailVisited = mutableSetOf<Pair<Int, Int>>()
tailVisited.add(tail)
for(line in input) {
val (dir, distance) = line.split(" ")
var (headX, headY) = head
when(dir) {
"U" -> {
headY += distance.toInt()
for(i in head.second + 1 .. headY) {
tail = moveTail(headX, i, tail)
tailVisited.add(tail)
}
}
"D" -> {
headY -= distance.toInt()
for(i in head.second - 1 downTo headY) {
tail = moveTail(headX, i, tail)
tailVisited.add(tail)
}
}
"L" -> {
headX -= distance.toInt()
for(i in head.first - 1 downTo headX) {
tail = moveTail(i, headY, tail)
tailVisited.add(tail)
}
}
"R" -> {
headX += distance.toInt()
for(i in head.first + 1 .. headX) {
tail = moveTail(i, headY, tail)
tailVisited.add(tail)
}
}
}
head = Pair(headX, headY)
println("head: $head tail $tail")
// check the tail
}
return tailVisited.size
}
fun part2(input: List<String>): Int {
var head = Pair(0, 0)
var tails = mutableListOf<Pair<Int, Int>>()
for(i in 1..9) {
tails.add(Pair(0, 0))
}
var tailVisited = mutableSetOf<Pair<Int, Int>>()
tailVisited.add(tails.last())
for(line in input) {
val (dir, distance) = line.split(" ")
var (headX, headY) = head
when(dir) {
"U" -> {
headY += distance.toInt()
for(i in head.second + 1 .. headY) {
tails[0] = moveTail(headX, i, tails[0])
for(j in 1 until tails.size) {
tails[j] = moveTail(tails[j-1].first,tails[j-1].second, tails[j])
}
tailVisited.add(tails.last())
}
}
"D" -> {
headY -= distance.toInt()
for(i in head.second - 1 downTo headY) {
tails[0] = moveTail(headX, i, tails[0])
for(j in 1 until tails.size) {
tails[j] = moveTail(tails[j-1].first,tails[j-1].second, tails[j])
}
tailVisited.add(tails.last())
}
}
"L" -> {
headX -= distance.toInt()
for(i in head.first - 1 downTo headX) {
tails[0] = moveTail(i, headY, tails[0])
for(j in 1 until tails.size) {
tails[j] = moveTail(tails[j-1].first, tails[j-1].second, tails[j])
}
tailVisited.add(tails.last())
}
}
"R" -> {
headX += distance.toInt()
for(i in head.first + 1 .. headX) {
tails[0] = moveTail(i, headY, tails[0])
for(j in 1 until tails.size) {
tails[j] = moveTail(tails[j-1].first, tails[j-1].second, tails[j])
}
tailVisited.add(tails.last())
}
}
}
head = Pair(headX, headY)
// println("head: $head tails: $tails")
// check the tail
}
return tailVisited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
// println(part1(testInput))
println(part2(testInput))
val input = readInput("Day09")
// output(part1(input))
output(part2(input))
} | 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 4,170 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2019/calendar/day18/SearchDijkstra.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2019.calendar.day18
import me.peckb.aoc.pathing.Dijkstra
import me.peckb.aoc.pathing.DijkstraNodeWithCost
data class SearchArea(val sources: List<Day18.Section.Source>, val foundKeys: Set<Day18.Section.Source.Key>)
class SearchDijkstra(
private val allKeys: Set<Day18.Section.Source.Key>,
private val paths: Map<Day18.Section.Source, Map<Day18.Section.Source.Key, Day18.Route>>
) : Dijkstra<SearchArea, Distance, SearchAreaWithDistance> {
override fun SearchArea.withCost(cost: Distance) = SearchAreaWithDistance(this, cost).withAllKeys(allKeys).withPaths(paths)
override fun Distance.plus(cost: Distance) = this + cost
override fun maxCost() = Int.MAX_VALUE
override fun minCost() = 0
}
class SearchAreaWithDistance(private val searchArea: SearchArea, private val distance: Distance) :
DijkstraNodeWithCost<SearchArea, Distance> {
private lateinit var allKeys: Set<Day18.Section.Source.Key>
private lateinit var paths: Map<Day18.Section.Source, Map<Day18.Section.Source.Key, Day18.Route>>
fun withAllKeys(allKeys: Set<Day18.Section.Source.Key>) = apply { this.allKeys = allKeys }
fun withPaths(paths: Map<Day18.Section.Source, Map<Day18.Section.Source.Key, Day18.Route>>) = apply { this.paths = paths }
override fun compareTo(other: DijkstraNodeWithCost<SearchArea, Distance>): Int = distance.compareTo(other.cost())
override fun cost(): Distance = distance
override fun node(): SearchArea = searchArea
override fun neighbors(): List<SearchAreaWithDistance> {
val (sections, foundKeys) = searchArea
if (foundKeys.size == allKeys.size) { return emptyList() }
val neighbors = mutableListOf<SearchAreaWithDistance>()
sections.forEachIndexed { index, source ->
paths[source]?.forEach { (key, route) ->
val (distance, doors) = route
val doorKeys = doors.map { it.key }
if (foundKeys.containsAll(doorKeys)) {
val newSections = sections.toMutableList().also { it[index] = key }
val searchArea = SearchArea(newSections, foundKeys.plus(key))
val neighbor = SearchAreaWithDistance(searchArea, distance)
.withAllKeys(allKeys)
.withPaths(paths)
neighbors.add(neighbor)
}
}
}
return neighbors
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 2,283 | advent-of-code | MIT License |
src/twentytwo/Day07.kt | mihainov | 573,105,304 | false | {"Kotlin": 42574} | package twentytwo
import readInputTwentyTwo
data class File(val size: Int, val name: String)
typealias FileSystem = MutableMap<String, MutableList<File>>
fun handleCommandCd(arg: String, currentDir: MutableList<String>) {
when (arg) {
"/" -> {
currentDir.removeAll { true }
currentDir.add("")
}
".." -> {
currentDir.removeLast()
}
else -> {
currentDir.add(arg)
}
}
}
fun handleCommand(terminal: String, currentDir: MutableList<String>) {
val splitString = terminal.split(" ")
val command = splitString[1]
// then it's a command
@Suppress("MoveVariableDeclarationIntoWhen")
when (command) {
"cd" -> {
val arg = splitString[2]
handleCommandCd(arg, currentDir)
}
"ls" -> {
if (splitString.size == 3) {
error("Expected size is not 2 when ls command")
}
}
else -> {
error("Command $command not implemented yet")
}
}
}
fun parseInput(terminal: String, currentDir: MutableList<String>, fs: FileSystem) {
val terminalSplit = terminal.split(" ")
// handle directory changes
if (terminalSplit.first() == "$") {
handleCommand(terminal, currentDir)
return
}
// add directories
val path = currentDir.joinToString(separator = "/")
if (!fs.containsKey(path)) {
fs[path] = mutableListOf()
}
if (terminalSplit.first() == "dir") {
fs[path]?.add(File(-1, terminalSplit.component2()!!))
return
}
fs[path]
?.add(File(terminalSplit.first().toInt(), terminalSplit.component2()!!))
}
fun getFoldersContentSizes(fs: MutableMap<String, MutableList<File>>): Map<String, Int> {
val foldersMap = mutableMapOf<String, Int>()
// start by child folders
fs.keys.sortedBy {
it.split("/").size
}.reversed().forEach {
val folderSum = fs[it]!!
.filter { file -> file.size != -1 }
.sumOf { file -> file.size }
foldersMap[it] = folderSum
}
// handle size of contained folders
foldersMap.keys.forEach { subFolder ->
for (folder in foldersMap.keys) {
// make sure that we only count sub-folders that are 1 level lower than the folder
if (folder.split("/").size + 1 != subFolder.split("/").size) {
continue
}
if (subFolder.startsWith(folder)) {
foldersMap[folder] = foldersMap[folder]!!.plus(foldersMap[subFolder]!!)
}
}
}
return foldersMap
}
fun main() {
fun part1(input: List<String>): Int {
val currentDir = mutableListOf<String>()
val fs = mutableMapOf<String, MutableList<File>>()
input.forEach { parseInput(it, currentDir, fs) }
return getFoldersContentSizes(fs).values.filter { it < 100_000 }.sum()
}
fun part2(input: List<String>): Int {
val fsSize = 70000000
val necessarySpace = 30000000
var needToFree: Int
val currentDir = mutableListOf<String>()
val fs = mutableMapOf<String, MutableList<File>>()
input.forEach { parseInput(it, currentDir, fs) }
return getFoldersContentSizes(fs).values.also {
val rootSize = it.max()
val unused = (fsSize - rootSize)
needToFree = necessarySpace - unused
}.filter { it > needToFree }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputTwentyTwo("Day07_test")
check(part1(testInput).also(::println) == 95437)
check(part2(testInput).also(::println) == 24933642)
val input = readInputTwentyTwo("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9aae753cf97a8909656b6137918ed176a84765e | 3,831 | kotlin-aoc-1 | Apache License 2.0 |
src/Day06.kt | binaryannie | 573,120,071 | false | {"Kotlin": 10437} | private const val DAY = "06"
private const val PART_1_CHECK = 7
private const val PART_2_CHECK = 19
fun messageSeeker(input: String, windowSize: Int): Int {
return input.windowed(windowSize).map { it.toSet() }.indexOfFirst { it.size == windowSize } + windowSize
}
fun main() {
fun part1(input: List<String>): Int {
return messageSeeker(input[0], 4)
}
fun part2(input: List<String>): Int {
return messageSeeker(input[0], 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${DAY}_test")
check(part1(testInput).also { println("Part 1 check: $it") } == PART_1_CHECK)
check(part2(testInput).also { println("Part 2 check: $it") } == PART_2_CHECK)
val input = readInput("Day${DAY}")
println("Part 1 solution: ${part1(input)}")
println("Part 2 solution: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 511fc33f9dded71937b6bfb55a675beace84ca22 | 890 | advent-of-code-2022 | Apache License 2.0 |
day03/kotlin/corneil/src/main/kotlin/solution.kt | mehalter | 317,661,818 | true | {"HTML": 2739009, "Java": 348790, "Kotlin": 271053, "TypeScript": 262310, "Python": 198318, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day3
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class Coord(val x: Int, val y: Int) {
fun distance(target: Coord): Int {
return abs(x - target.x) + abs(y - target.y)
}
}
data class Cell(val coord: Coord, val value: Int, val steps: MutableMap<Int, Int> = mutableMapOf())
fun translateInstruction(instruction: String): Pair<Char, Int> {
val direction = instruction[0]
val amount = instruction.substring(1).toInt()
return Pair(direction, amount)
}
class Grid {
val cells = mutableMapOf(Coord(0, 0) to Cell(Coord(0, 0), 0))
private fun addCell(x: Int, y: Int, value: Int, steps: Int) {
if (!(x == 0 && y == 0)) {
val key = <KEY>)
val existing = cells[key]
if (existing != null) {
if (existing.value != value) {
cells[key] = existing.copy(value = value + existing.value)
}
val existingSteps = cells[key]!!.steps[value]
if (existingSteps == null) {
cells[key]!!.steps[value] = steps
}
} else {
cells[key] = Cell(key, value, mutableMapOf(value to steps))
}
}
}
private fun addEntriesX(startX: Int, endX: Int, y: Int, value: Int, steps: Int): Coord {
var stepsCounted = steps
if (startX < endX) {
for (x in startX..endX) {
addCell(x, y, value, stepsCounted)
stepsCounted += 1
}
} else {
for (x in startX downTo endX) {
addCell(x, y, value, stepsCounted)
stepsCounted += 1
}
}
return Coord(endX, y)
}
private fun addEntriesY(startY: Int, endY: Int, x: Int, value: Int, steps: Int): Coord {
var stepsCounted = steps
if (startY < endY) {
for (y in startY..endY) {
addCell(x, y, value, stepsCounted)
stepsCounted += 1
}
} else {
for (y in startY downTo endY) {
addCell(x, y, value, stepsCounted)
stepsCounted += 1
}
}
return Coord(x, endY)
}
fun updateGrid(trace: List<String>, line: Int) {
var position = Coord(0, 0)
var stepsCounted = 0
trace.forEach { instruction ->
val direction = translateInstruction(instruction)
position = when (direction.first) {
'R' -> addEntriesX(position.x, position.x + direction.second, position.y, line, stepsCounted)
'L' -> addEntriesX(position.x, position.x - direction.second, position.y, line, stepsCounted)
'U' -> addEntriesY(position.y, position.y + direction.second, position.x, line, stepsCounted)
'D' -> addEntriesY(position.y, position.y - direction.second, position.x, line, stepsCounted)
else -> error("Unknown instruction $instruction")
}
stepsCounted += direction.second
}
}
fun findNearest(coord: Coord, minValue: Int): Cell {
val closest = cells.values.filter { cell ->
cell.value > minValue
}.minBy { cell ->
coord.distance(cell.coord)
}
requireNotNull(closest) { "Could not find any cells!!!" }
return closest
}
fun findLowestStepsIntersection(minValue: Int): Int {
val best = cells.values.filter { cell ->
cell.value > minValue
}.minBy { cell ->
cell.steps.values.sum()
}
requireNotNull(best) { "Expected a minimum value" }
return best.steps.values.sum()
}
fun findClosestManhattenDistance(coord: Coord, minValue: Int): Int {
return coord.distance(findNearest(coord, minValue).coord)
}
fun printGrid(): List<String> {
val minX = min(cells.values.map { it.coord.x }.min() ?: 0, 0) - 1
val maxX = max(cells.values.map { it.coord.x }.max() ?: 0, 0) + 1
val lines = cells.values.groupBy { it.coord.y }.toSortedMap()
return lines.map { entry ->
val lineOut = StringBuilder()
val lineCells = entry.value.map { it.coord.x to it }.toMap()
for (x in minX..maxX) {
val cellX = lineCells[x]
if (cellX != null) {
lineOut.append(cellX.value.toString())
} else {
lineOut.append('.')
}
}
lineOut.toString()
}.reversed()
}
}
fun stringToInstructions(input: String): List<String> {
return input.split(',').map { it.trim() }
}
fun main(args: Array<String>) {
val fileName = if (args.size > 1) args[0] else "input.txt"
val lines = BufferedReader(FileReader(File(fileName))).readLines().mapNotNull {
val line = it.trim()
if (line.isNotEmpty()) line else null
}
val grid = Grid()
lines.forEachIndexed { index, line ->
grid.updateGrid(stringToInstructions(line), index + 1)
}
val start = Coord(0, 0)
val distance = grid.findClosestManhattenDistance(start, lines.size)
println("Distance=$distance")
val best = grid.findLowestStepsIntersection(lines.size)
// then
println("Best=$best")
}
| 0 | HTML | 0 | 0 | afcaede5326b69fedb7588b1fe771fd0c0b3f6e6 | 5,457 | docToolchain-aoc-2019 | MIT License |
src/Day01.kt | daividssilverio | 572,944,347 | false | {"Kotlin": 10575} | fun main() {
val inventory = readInput("Day01_test")
val highestInventoryInCalories = findTopSumsOfCaloriesInventories(inventory, 1)
val sumOfTopThreeInventories = findTopSumsOfCaloriesInventories(inventory, 3)
println(highestInventoryInCalories)
println(sumOfTopThreeInventories)
}
fun findTopSumsOfCaloriesInventories(foodInventory: List<String>, count: Int): Int {
var currentElfInventoryCaloriesSum = 0
var maxCaloriesInventories = emptyList<Int>()
foodInventory.forEachIndexed { index, food ->
currentElfInventoryCaloriesSum += food.toIntOrNull() ?: 0
if (food.isBlank() || index == foodInventory.lastIndex) {
maxCaloriesInventories = (maxCaloriesInventories + currentElfInventoryCaloriesSum).sortedDescending().take(count)
currentElfInventoryCaloriesSum = 0
}
}
return maxCaloriesInventories.sum()
}
| 0 | Kotlin | 0 | 0 | 141236c67fe03692785e0f3ab90248064a1693da | 896 | advent-of-code-kotlin-2022 | Apache License 2.0 |
Kotlin/src/main/kotlin/org/algorithm/problems/0182_n_queens.kt | raulhsant | 213,479,201 | true | {"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187} | package org.algorithm.problems
// Problem Statement
// The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
// Given an integer n, return all distinct solutions to the n-queens puzzle.
// Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
import java.lang.StringBuilder
class `0182_n_queens` {
private val result = mutableListOf<List<String>>()
private fun checkRDiagonal(board: List<StringBuilder>, row: Int, column: Int): Boolean {
var i = row
var j = column
while (i >= 0 && j < board.size) {
if (board[i][j] == 'Q')
return false
i--
j++
}
return true
}
private fun checkLDiagonal(board: List<StringBuilder>, row: Int, column: Int): Boolean {
var i = row
var j = column
while (i >= 0 && j >= 0) {
if (board[i][j] == 'Q')
return false
i--
j--
}
return true
}
private fun checkColumn(board: List<StringBuilder>, row: Int, column: Int): Boolean {
for (index in row downTo 0) {
if (board[index][column] == 'Q')
return false
}
return true
}
private fun placeQueen(board: MutableList<StringBuilder>, row: Int) {
if (row >= board.size) {
result.add(board.map { it.toString() })
return
}
for (i in board.indices) {
if (checkColumn(board, row, i) &&
checkLDiagonal(board, row, i) &&
checkRDiagonal(board, row, i)) {
board[row][i] = 'Q'
placeQueen(board, row + 1)
board[row][i] = '.'
}
}
}
fun solveNQueens(n: Int): List<List<String>> {
val board = MutableList<StringBuilder>(n){StringBuilder(String(CharArray(n){'.'}))}
placeQueen(board,0)
return result
}
}
| 0 | C++ | 0 | 0 | 1578a0dc0a34d63c74c28dd87b0873e0b725a0bd | 2,108 | algorithms | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year15/Day21.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year15
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.permPairsExclusive
import com.grappenmaker.aoc.splitInts
fun PuzzleSet.day21() = puzzle(21) {
data class SpecialItem(val cost: Int, val dmg: Int, val arm: Int)
operator fun SpecialItem.plus(other: SpecialItem) = SpecialItem(cost + other.cost, dmg + other.dmg, arm + other.arm)
val weapons = listOf(
SpecialItem(8, 4, 0),
SpecialItem(10, 5, 0),
SpecialItem(25, 6, 0),
SpecialItem(40, 7, 0),
SpecialItem(74, 8, 0),
)
val armor = listOf(
SpecialItem(13, 0, 1),
SpecialItem(31, 0, 2),
SpecialItem(53, 0, 3),
SpecialItem(72, 0, 4),
SpecialItem(102, 0, 5),
SpecialItem(0, 0, 0)
)
val rings = listOf(
SpecialItem(25, 1, 0),
SpecialItem(50, 2, 0),
SpecialItem(100, 3, 0),
SpecialItem(20, 0, 1),
SpecialItem(40, 0, 2),
SpecialItem(80, 0, 3),
SpecialItem(0, 0, 0),
SpecialItem(0, 0, 0),
)
val (initialBossHP, bossDMG, bossARM) = input.splitInts()
fun SpecialItem.sim(): Boolean {
var ourHP = 100
var bossHP = initialBossHP
while (true) {
bossHP -= (dmg - bossARM).coerceAtLeast(1)
if (bossHP <= 0) return true
ourHP -= (bossDMG - arm).coerceAtLeast(1)
if (ourHP <= 0) return false
}
}
val ringPairs = rings.permPairsExclusive()
val poss = weapons.flatMap { w -> armor.flatMap { a -> ringPairs.map { (r1, r2) -> w + a + r1 + r2 } } }.toSet()
val (wins, loses) = poss.partition { it.sim() }
partOne = wins.minOf { it.cost }.s()
partTwo = loses.maxOf { it.cost }.s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,761 | advent-of-code | The Unlicense |
2018/kotlin/day13p2/src/main.kt | sgravrock | 47,810,570 | false | {"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488} | import java.util.*
fun main(args: Array<String>) {
val start = Date()
val classLoader = Coord::class.java.classLoader
val input = classLoader.getResource("input.txt").readText()
val rr = MineRailroad.parse(input)
rr.advanceUntilOneCart()
println(rr.remainingCartCoord())
println("in ${Date().time - start.time}ms")
}
data class Coord(val x: Int, val y: Int): Comparable<Coord> {
override fun compareTo(other: Coord): Int {
val lc = y.compareTo(other.y)
return when(lc) {
0 -> x.compareTo(other.x)
else -> lc
}
}
}
enum class Orientation(val x: Int, val y: Int) {
Up(0, -1),
Down(0, 1),
Left(-1, 0),
Right(1, 0)
}
enum class TurnDirection {
Left,
Straight,
Right
}
enum class TrackSegment {
Vertical,
Horizontal,
SlashyTurn,
BackslashyTurn,
Intersection
}
data class MineRailroad(val tracks: Map<Coord, TrackSegment>, val carts: MutableList<Cart>) {
fun advanceUntilOneCart() {
while (carts.count() > 1) {
advance()
}
}
fun advance() {
carts.sortedBy { it.coord }.forEach { cart ->
cart.advance(tracks)
val atSameCoord = carts.filter { it.coord == cart.coord }
if (atSameCoord.count() > 1) {
carts.removeAll(atSameCoord)
}
}
}
fun remainingCartCoord(): Coord? {
return if (carts.count() == 1) carts[0].coord else null
}
companion object {
fun parse(input: String): MineRailroad {
val lines = input.lines()
val tracks = mutableMapOf<Coord, TrackSegment>()
val carts = mutableListOf<Cart>()
for (y in lines.indices) {
for (x in lines[y].indices) {
val maybeSeg = when (lines[y][x]) {
'-', '<', '>' -> TrackSegment.Horizontal
'|', 'v', '^' -> TrackSegment.Vertical
'/' -> TrackSegment.SlashyTurn
'\\' -> TrackSegment.BackslashyTurn
'+' -> TrackSegment.Intersection
' ' -> null
else -> throw Error("Unexpected character: '${lines[y][x]}'")
}
if (maybeSeg != null) {
tracks[Coord(x, y)] = maybeSeg
}
val maybeCart = Cart.fromChar(lines[y][x], Coord(x, y))
if (maybeCart != null) {
carts.add(maybeCart)
}
}
}
return MineRailroad(tracks, carts)
}
}
}
data class Cart(
var coord: Coord,
var orientation: Orientation,
var nextTurnDirection: TurnDirection
) {
fun advance(tracks: Map<Coord, TrackSegment>) {
coord = Coord(coord.x + orientation.x, coord.y + orientation.y)
orientation = when (tracks[coord]!!) {
TrackSegment.Horizontal, TrackSegment.Vertical -> orientation
TrackSegment.SlashyTurn -> {
when (orientation) {
Orientation.Up -> Orientation.Right
Orientation.Right -> Orientation.Up
Orientation.Left -> Orientation.Down
Orientation.Down -> Orientation.Left
}
}
TrackSegment.BackslashyTurn -> {
when (orientation) {
Orientation.Down -> Orientation.Right
Orientation.Right -> Orientation.Down
Orientation.Left -> Orientation.Up
Orientation.Up -> Orientation.Left
}
}
TrackSegment.Intersection -> {
val turn = nextTurnDirection
nextTurnDirection = successor(turnSequence, nextTurnDirection)
when (turn) {
TurnDirection.Left -> predecessor(orientationSequence, orientation)
TurnDirection.Right -> successor(orientationSequence, orientation)
TurnDirection.Straight -> orientation
}
}
}
}
companion object {
fun fromChar(c: Char, coord: Coord): Cart? {
val o = when (c) {
'<' -> Orientation.Left
'>' -> Orientation.Right
'^' -> Orientation.Up
'v' -> Orientation.Down
else -> null
}
return if (o == null) {
null
} else {
Cart(coord, o, TurnDirection.Left)
}
}
private val turnSequence = listOf(TurnDirection.Left, TurnDirection.Straight, TurnDirection.Right)
private val orientationSequence = listOf(Orientation.Up, Orientation.Right, Orientation.Down, Orientation.Left)
}
}
fun <T> successor(list: List<T>, curr: T): T {
return list[(list.indexOf(curr) + 1) % list.count()]
}
fun <T> predecessor(list: List<T>, curr: T): T {
val i = list.indexOf(curr)
return if (i == 0) list.last() else list[i - 1]
}
| 0 | Rust | 0 | 0 | ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3 | 5,187 | adventofcode | MIT License |
src/test/kotlin/com/igorwojda/list/sumzero/challenge.kt | ExpensiveBelly | 308,111,738 | true | {"Kotlin": 244479} | package com.igorwojda.list.sumzero
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
private fun sumZero(list: List<Int>): Pair<Int, Int>? {
if (list.isEmpty()) return null
return list.toSet().combinations(2).map { Pair(it.first(), it.elementAt(1)) }.filter { it.first + it.second == 0 }
.minByOrNull { list.indexOf(it.first) }
}
/**
* https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/master/src/main/java/com/marcinmoskala/math/CombinationsExt.kt
*/
fun <T> Set<T>.combinations(combinationSize: Int): Set<Set<T>> = when {
combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize")
combinationSize == 0 -> setOf(setOf())
combinationSize >= size -> setOf(toSet())
else -> powerset()
.filter { it.size == combinationSize }
.toSet()
}
fun <T> Collection<T>.powerset(): Set<Set<T>> = powerset(this, setOf(setOf()))
private tailrec fun <T> powerset(left: Collection<T>, acc: Set<Set<T>>): Set<Set<T>> = when {
left.isEmpty() -> acc
else -> powerset(left.drop(1), acc + acc.map { it + left.first() })
}
private class Test {
@Test
fun `sumZero empty list return null`() {
sumZero(listOf()) shouldBeEqualTo null
}
@Test
fun `sumZero 1, 2 return null`() {
sumZero(listOf(1, 2)) shouldBeEqualTo null
}
@Test
fun `sumZero 1, 2, 4, 7 return null`() {
sumZero(listOf(1, 2, 4, 7)) shouldBeEqualTo null
}
@Test
fun `sumZero -4, -3, -2, 1, 2, 3, 5 return Pair(-3, 3)`() {
sumZero(listOf(-4, -3, -2, 1, 2, 3, 5)) shouldBeEqualTo Pair(-3, 3)
}
@Test
fun `sumZero -4, -3, -2, 1, 2, 5 return Pair(-2, 2)`() {
sumZero(listOf(-4, -3, -2, 1, 2, 5)) shouldBeEqualTo Pair(-2, 2)
}
}
| 1 | Kotlin | 0 | 0 | f08e5bc1ccf5e1c686e228c7377edff12fd1b35f | 1,821 | kotlin-coding-puzzle-1 | MIT License |
src/Day06.kt | cisimon7 | 573,872,773 | false | {"Kotlin": 41406} | fun main() {
fun posUniqueSequence(signal: String, count: Int): Int {
val idx = signal.windowedSequence(count, 1).indexOfFirst { it.toSet().size == count }
return idx + count
}
fun part1(signals: List<String>): List<Int> {
return signals.map { signal -> posUniqueSequence(signal, 4) }
}
fun part2(signals: List<String>): List<Int> {
return signals.map { signal -> posUniqueSequence(signal, 14) }
}
fun parse(stringList: List<String>): List<String> {
return stringList
}
val testInput = readInput("Day06_test")
check(part1(parse(testInput)) == listOf(5, 6, 10, 11))
check(part2(parse(testInput)) == listOf(23, 23, 29, 26))
val input = readInput("Day06_input")
println(part1(parse(input)))
println(part2(parse(input)))
}
| 0 | Kotlin | 0 | 0 | 29f9cb46955c0f371908996cc729742dc0387017 | 820 | aoc-2022 | Apache License 2.0 |
src/Day01.kt | fonglh | 573,269,990 | false | {"Kotlin": 48950, "Ruby": 1701} | fun main() {
fun part1(input: List<String>): Int {
var maxCalories = 0
var elfCalories = 0
input.forEach {
if(it.isNotBlank()) {
elfCalories += it.toInt()
} else {
if (elfCalories > maxCalories) {
maxCalories = elfCalories
}
elfCalories = 0
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
var elfCalories = 0
var allElfCalories = mutableListOf<Int>()
input.forEach {
if(it.isNotBlank()) {
elfCalories += it.toInt()
} else {
allElfCalories.add(elfCalories)
elfCalories = 0
}
}
return allElfCalories.sortedDescending().slice(0..2).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ef41300d53c604fcd0f4d4c1783cc16916ef879b | 1,101 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc22/Day14.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc22
import aoc22.Day14Domain.Cave
import aoc22.Day14Parser.toCave
import aoc22.Day14Solution.part1Day14
import aoc22.Day14Solution.part2Day14
import common.Space2D.Direction.*
import common.Space2D.Point
import common.Year22
import common.Monitoring
object Day14: Year22 {
fun List<String>.part1(): Int = part1Day14()
fun List<String>.part2(): Int = part2Day14()
}
object Day14Solution {
fun List<String>.part1Day14(): Int =
toCave()
.fillUpAndCount()
fun List<String>.part2Day14(): Int =
toCave()
.apply {
rock.addAll(floor(belowLowest = 2))
lowestRock = rock.minBy { it.y }
}
.fillUpAndCount()
}
object Day14Domain {
data class Cave(
val rock: MutableSet<Point>,
val sandStartsFrom: Point,
var fallingSand: Point,
var lowestRock: Point = rock.minBy { it.y },
var last: Point = lowestRock,
private val monitor: Monitoring.PointMonitor? = null
) {
private var atRest: Int = 0
fun hasNext(): Boolean =
fallingSand.isAbove(lowestRock) &&
last != sandStartsFrom
fun fillUpAndCount(): Int {
while (hasNext()) {
fallingSand.movesBelow().firstOrNull { it !in rock }
.let { stillFallingSand ->
if (stillFallingSand != null) {
fallingSand = stillFallingSand
} else {
rock.add(fallingSand)
last = fallingSand
fallingSand = sandStartsFrom
atRest++
}
}
monitor?.invoke(rock + fallingSand)
}
return atRest
}
fun floor(belowLowest: Int): List<Point> {
val left: Int = rock.minOf { it.x } + lowestRock.y
val right: Int = rock.maxOf { it.x } - lowestRock.y
val down: Int = lowestRock.y - belowLowest
return Point(x = left, y = down).lineTo(Point(x = right, y = down))
}
private fun Point.isAbove(other: Point): Boolean = this.y > other.y
private fun Point.movesBelow() =
listOf(
move(South),
move(South).move(West),
move(South).move(East)
)
}
}
object Day14Parser {
fun List<String>.toCave(monitor: Monitoring.PointMonitor? = null): Cave =
Cave(
rock = this.flatMap { row -> row.toPoints().toLine() }.toMutableSet(),
sandStartsFrom = Point(500, 0),
fallingSand = Point(500, 0),
monitor = monitor
)
private fun String.toPoints(): List<Point> =
split(" -> ")
.map {
it.split(",")
.run { Point(this[0].toInt(), -this[1].toInt()) }
}
private fun List<Point>.toLine(): List<Point> =
zipWithNext()
.flatMap { (from, to) -> from.lineTo(to) }
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 3,115 | aoc | Apache License 2.0 |
Essays/Testability/REPL/src/main/kotlin/palbp/laboratory/essays/testability/repl/Parser.kt | palbp | 463,200,783 | false | {"Kotlin": 722657, "C": 16710, "Assembly": 891, "Dockerfile": 610, "Swift": 594, "Makefile": 383} | package palbp.laboratory.essays.testability.repl
/*
* Parser implementation for the following grammar:
*
* expression = operation | constant
* operation = operator , expression , expression
* operator = '-' | '+' | '*' | '/'
* constant = [sign] , {digit}
* sign = '-' | '+'
* digit = '0' | '1' | '2' | '3' | '4'| '5'| '6'| '7'| '8'| '9'
*/
fun parse(input: String): Expression = expression(tokens = tokenize(input), startsAt = 0).first
class UnexpectedToken(val token: Token) : Exception()
private fun expression(tokens: List<Token>, startsAt: Int): Pair<Expression, Int> =
if (isOperation(tokens[startsAt])) operation(tokens, startsAt)
else constant(tokens, startsAt)
private fun isOperation(token: Token): Boolean =
when (token.value) {
"+", "-", "*", "/" -> true
else -> false
}
private fun operation(tokens: List<Token>, startsAt: Int): Pair<Expression, Int> {
val operation = tokens[startsAt]
val left = expression(tokens, startsAt = startsAt + 1)
val right = expression(tokens, startsAt = left.second)
return Pair(
first = when (operation.value) {
"+" -> Addition(left.first, right.first)
"-" -> Subtraction(left.first, right.first)
"*" -> Multiplication(left.first, right.first)
"/" -> Division(left.first, right.first)
else -> throw UnexpectedToken(operation)
},
second = right.second
)
}
private fun constant(tokens: List<Token>, startsAt: Int): Pair<Expression, Int> {
val value = tokens[startsAt].value.toIntOrNull()
return if (value != null) Pair(first = Constant(value), second = startsAt + 1)
else throw UnexpectedToken(tokens[startsAt])
}
| 1 | Kotlin | 0 | 4 | 66fb17fcd9d7b1690492def0bf671cfb408eb6db | 1,746 | laboratory | MIT License |
src/day22/Day22.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | @file:Suppress("MagicNumber")
package day22
import Direction
import Position
import readInput
fun main() {
fun parseInstructions(instructions: String): List<Inst> {
val alteredInstr = instructions.replace("""([RL])""".toRegex(), " $0 ")
return alteredInstr.split(" ")
.windowed(2, 2, partialWindows = true).map { move ->
val (count, rotate) = move.first() to move.last()
Inst(
move = count.toInt(),
rotation = Rotation.value(rotate)
)
}
}
fun parse(input: List<String>): Pair<Board, List<Inst>> {
val divider = input.indexOfFirst { it.isEmpty() }
val board = Board(input.subList(0, divider))
val instructions = parseInstructions(input.last())
return board to instructions
}
fun parseCube(input: List<String>): Pair<Board, List<Inst>> {
val divider = input.indexOfFirst { it.isEmpty() }
val cube = Cube(input.subList(0, divider))
val instructions = parseInstructions(input.last())
return cube to instructions
}
fun simulate(board: Board, insts: List<Inst>) {
insts.forEach { inst ->
board.move(inst)
}
}
fun part1(input: List<String>): Int {
val (board, insts) = parse(input)
simulate(board, insts)
return board.evaluate()
}
fun part2(input: List<String>): Int {
val (cube, insts) = parseCube(input)
simulate(cube, insts)
return cube.evaluate()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day22/Day22_test")
val input = readInput("day22/Day22")
check((part1(testInput)).also { println(it) } == 6032)
println(part1(input))
check(part2(testInput).also { println(it) } == 5031)
println(part2(input))
}
class Cube(rows: List<String>) : Board(rows) {
private val sides: List<List<Int>>
private val n: Int
init {
val height = rows.size
val width = rows.maxOf { it.length }
val tempSides = List(height) { MutableList(width) { 0 } }
val tempN = rows.first().chunked(1).count { it.isNotBlank() }
n = if (tempN < 10) tempN else tempN / 2
rows.forEachIndexed { y, row ->
row.chunked(1).forEachIndexed { x, tile ->
when (tile) {
" " -> tempSides[y][x] = 0
else -> tempSides[y][x] = calculateSide(x, y, n)
}
}
}
sides = tempSides
}
private fun calculateSide(x: Int, y: Int, n: Int): Int {
return if (n < 10) {
testSides(y, n, x)
} else {
normalSides(y, n, x)
}
}
private fun testSides(y: Int, n: Int, x: Int) = when (y) {
in 0 until n -> 1
in n until 2 * n -> {
when (x) {
in 0 until n -> 2
in n until 2 * n -> 3
else -> 4
}
}
else -> {
when (x) {
in 2 * n until 3 * n -> 5
else -> 6
}
}
}
private fun normalSides(y: Int, n: Int, x: Int) = when (y) {
in 0 until n -> {
when (x) {
in n until 2 * n -> 1
else -> 2
}
}
in n until 2 * n -> 3
in 2 * n until 3 * n -> {
when (x) {
in 0 until n -> 4
else -> 5
}
}
else -> 6
}
override fun moveToOtherSide() {
if (n < 10) {
testMoveToOther()
} else {
normalMoveToOther()
}
}
private fun testMoveToOther() {
val side = sides[currentPos]
when (currentDir) {
Direction.U -> {
when (side) {
2 -> moveDir(currentPos.copy(x = 2 * n + reverse(currentPos.x, n), y = 0), Direction.D)
3 -> moveDir(currentPos.copy(x = 2 * n, y = currentPos.x % n), Direction.R)
1 -> moveDir(currentPos.copy(x = reverse(currentPos.x, n), y = n), Direction.D)
6 -> moveDir(currentPos.copy(x = (3 * n - 1), y = 2 * n + reverse(currentPos.x, n)), Direction.L)
else -> error("Wrong state")
}
}
Direction.D -> {
when (side) {
2 -> moveDir(currentPos.copy(x = 2 * n + reverse(currentPos.x, n), y = 3 * n - 1), Direction.U)
3 -> moveDir(currentPos.copy(x = 2 * n, y = 2 * n + reverse(currentPos.x, n)), Direction.R)
5 -> moveDir(currentPos.copy(x = reverse(currentPos.x, n), y = 2 * n - 1), Direction.U)
6 -> moveDir(currentPos.copy(x = 0, y = n + reverse(currentPos.x, n)), Direction.R)
else -> error("Wrong state")
}
}
Direction.L -> {
when (side) {
1 -> moveDir(currentPos.copy(x = n + (currentPos.y % n), y = n), Direction.D)
2 -> moveDir(currentPos.copy(x = 3 * n + reverse(currentPos.y, n), y = 3 * n - 1), Direction.U)
5 -> moveDir(currentPos.copy(x = n + reverse(currentPos.y, n), y = 2 * n - 1), Direction.U)
else -> error("Wrong state")
}
}
Direction.R -> {
when (side) {
1 -> moveDir(currentPos.copy(x = (4 * n - 1), y = 2 * n + reverse(currentPos.y, n)), Direction.L)
4 -> moveDir(currentPos.copy(x = 3 * n + reverse(currentPos.y, n), y = (2 * n)), Direction.D)
6 -> moveDir(currentPos.copy(x = (3 * n - 1), y = reverse(currentPos.y, n)), Direction.L)
else -> error("Wrong state")
}
}
}
}
private fun normalMoveToOther() {
val side = sides[currentPos]
when (currentDir) {
Direction.U -> {
when (side) {
4 -> moveDir(currentPos.copy(x = n, y = n + (currentPos.x % n)), Direction.R)
1 -> moveDir(currentPos.copy(x = 0, y = 3 * n + (currentPos.x % n)), Direction.R)
2 -> moveDir(currentPos.copy(x = (currentPos.x % n), y = 4 * n - 1), Direction.U)
else -> error("Wrong state")
}
}
Direction.D -> {
when (side) {
6 -> moveDir(currentPos.copy(x = 2 * n + (currentPos.x % n), y = 0), Direction.D)
5 -> moveDir(currentPos.copy(x = n - 1, y = 3 * n + (currentPos.x % n)), Direction.L)
2 -> moveDir(currentPos.copy(x = 2 * n - 1, y = n + (currentPos.x % n)), Direction.L)
else -> error("Wrong state")
}
}
Direction.L -> {
when (side) {
1 -> moveDir(currentPos.copy(x = 0, y = 2 * n + reverse(currentPos.y, n)), Direction.R)
3 -> moveDir(currentPos.copy(x = currentPos.y % n, y = 2 * n), Direction.D)
4 -> moveDir(currentPos.copy(x = n, y = reverse(currentPos.y, n)), Direction.R)
6 -> moveDir(currentPos.copy(x = n + (currentPos.y % n), y = 0), Direction.D)
else -> error("Wrong state")
}
}
Direction.R -> {
when (side) {
2 -> moveDir(currentPos.copy(x = 2 * n - 1, y = 2 * n + reverse(currentPos.y, n)), Direction.L)
3 -> moveDir(currentPos.copy(x = 2 * n + (currentPos.y % n), y = n - 1), Direction.U)
5 -> moveDir(currentPos.copy(x = 3 * n - 1, y = reverse(currentPos.y, n)), Direction.L)
6 -> moveDir(currentPos.copy(x = n + (currentPos.y % n), y = 3 * n - 1), Direction.U)
else -> error("Wrong state")
}
}
}
}
private fun reverse(x: Int, n: Int): Int {
return (n - 1) - (x % n)
}
override fun moveDir(newP: Position, dir: Direction) {
var newP1 = newP
while (grid[newP1] == -1) {
newP1 = newP1.newPosition(dir)
}
if (grid[newP1] == 1) return
if (grid[newP1] == 0) {
currentPos = newP1
currentDir = dir
}
}
}
private fun Direction.rotate(rotation: Rotation): Direction {
return when (rotation) {
day22.Rotation.R -> {
when (this) {
Direction.U -> Direction.R
Direction.R -> Direction.D
Direction.L -> Direction.U
Direction.D -> Direction.L
}
}
day22.Rotation.L -> {
when (this) {
Direction.U -> Direction.L
Direction.R -> Direction.U
Direction.L -> Direction.D
Direction.D -> Direction.R
}
}
}
}
data class Inst(
val move: Int,
val rotation: Rotation?,
)
open class Board(
rows: List<String>,
) {
val grid: List<MutableList<Int>>
var currentPos: Position
var currentDir: Direction = Direction.R
init {
val height = rows.size
val width = rows.maxOf { it.length }
val g = List(height) { MutableList(width) { -1 } }
rows.forEachIndexed { y, row ->
row.chunked(1).forEachIndexed { x, tile ->
when (tile) {
" " -> g[y][x] = -1
"." -> g[y][x] = 0
"#" -> g[y][x] = 1
else -> error("Wrong input")
}
}
}
grid = g
currentPos = findStart()
}
private fun findStart(): Position = Position(this.grid.first().indexOfFirst { it == 0 }, 0)
override fun toString(): String {
var y = 0
return grid.joinToString("\n") { line ->
line.mapIndexed { x, char ->
if (currentPos == Position(x, y)) {
"x"
} else {
when (char) {
0 -> "."
1 -> "#"
-1 -> " "
8 -> "8"
else -> "x"
}
}
}.also { y++ }.joinToString("", prefix = "", postfix = "")
}
}
fun move(inst: Inst) {
val (move, rotation) = inst
repeat(move) {
val newPosition = currentPos.newPosition(currentDir)
when (grid[newPosition]) {
0 -> currentPos = newPosition
1 -> return@repeat
-1 -> {
moveToOtherSide()
return@repeat
}
}
}.also {
currentDir = rotation?.let { currentDir.rotate(it) } ?: currentDir
}
}
internal open fun moveToOtherSide() {
when (currentDir) {
Direction.U -> moveDir(currentPos.copy(y = grid.size), Direction.U)
Direction.D -> moveDir(currentPos.copy(y = 0), Direction.D)
Direction.L -> moveDir(currentPos.copy(x = grid.first().size), Direction.L)
Direction.R -> moveDir(currentPos.copy(x = 0), Direction.R)
}
}
internal open fun moveDir(newP: Position, dir: Direction) {
var newP1 = newP
while (grid[newP1] == -1) {
newP1 = newP1.newPosition(dir)
}
if (grid[newP1] == 1) return
if (grid[newP1] == 0) currentPos = newP1
}
fun evaluate(): Int {
return 1000 * (currentPos.y + 1) + (4 * (currentPos.x + 1)) + when (currentDir) {
Direction.R -> 0
Direction.D -> 1
Direction.L -> 2
Direction.U -> 3
}
}
operator fun List<List<Int>>.get(pos: Position): Int {
return try {
this[pos.y][pos.x]
} catch (e: IndexOutOfBoundsException) {
return -1
}
}
}
enum class Rotation {
R, L;
companion object {
fun value(r: String): Rotation? = when (r) {
"R" -> R
"L" -> L
else -> null
}
}
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 12,384 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2023/Day03.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day03(schematic: List<String>) {
private val symbols = mutableSetOf<Symbol>()
private val numbers = mutableSetOf<Number>()
private data class Digit(val value: Int, val position: Vector2)
private class Number(digits: List<Digit>) {
val value = digits.reduce { acc, digit -> Digit(acc.value * 10 + digit.value, acc.position) }.value
val positions = digits.map { it.position }
}
private data class Symbol(val value: Char, val position: Vector2)
init {
var currentDigits = mutableListOf<Digit>()
schematic.forEachIndexed { i, line ->
line.forEachIndexed { j, character ->
if (character.isDigit()) {
currentDigits.add(Digit(character.toString().toInt(), Vector2(i, j)))
} else {
if (character != '.') {
symbols.add(Symbol(character, Vector2(i, j)))
}
if (currentDigits.isNotEmpty()) {
numbers.add(Number(currentDigits))
currentDigits = mutableListOf()
}
}
}
if (currentDigits.isNotEmpty()) {
numbers.add(Number(currentDigits))
currentDigits = mutableListOf()
}
}
}
fun solvePart1() = numbers
// Find all numbers touching a symbol
.filter { number ->
number.positions.any { pos ->
symbols.any { symbol ->
symbol.position.isTouching(pos)
}
}
}
// Calculate the sum of those numbers
.sumOf { it.value }
fun solvePart2() = symbols
// Find the gear symbols
.filter { it.value == '*' }
// Find all numbers touching that gear
.map { symbol ->
numbers.filter { number ->
number.positions.any { pos ->
symbol.position.isTouching(pos)
}
}
}
// We only want gears with exactly two touching numbers
.filter { it.size == 2 }
// Calculate the sum of the gear ratios
.sumOf { it.first().value * it.last().value }
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 2,288 | advent-2023 | MIT License |
src/main/kotlin/aoc/year2021/Day02.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2021
import aoc.Puzzle
/**
* [Day 2 - Advent of Code 2021](https://adventofcode.com/2021/day/2)
*/
object Day02 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int {
class Submarine1 : Submarine() {
override fun down(x: Int) {
depth += x
}
override fun up(x: Int) {
depth -= x
}
override fun forward(x: Int) {
hPos += x
}
}
return solve(input, Submarine1())
}
override fun solvePartTwo(input: String): Int {
class Submarine2 : Submarine() {
private var aim = 0
override fun down(x: Int) {
aim += x
}
override fun up(x: Int) {
aim -= x
}
override fun forward(x: Int) {
hPos += x
depth += aim * x
}
}
return solve(input, Submarine2())
}
private fun solve(input: String, submarine: Submarine): Int =
submarine.apply {
input.lineSequence().forEach { line ->
val (dir, sDelta) = line.split(' ', limit = 2)
val delta = sDelta.toInt()
when (dir) {
"forward" -> forward(delta)
"down" -> down(delta)
"up" -> up(delta)
else -> error("Unexpected direction")
}
}
}.product
private abstract class Submarine {
protected var depth = 0
protected var hPos = 0
val product: Int get() = hPos * depth
abstract fun forward(x: Int)
abstract fun down(x: Int)
abstract fun up(x: Int)
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 1,784 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem279/Solution2.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem279
import kotlin.math.sqrt
/**
* LeetCode page: [279. Perfect Squares](https://leetcode.com/problems/perfect-squares/);
*/
class Solution2 {
/* Complexity:
* Time O(sqrt(n)) and Space O(1);
*/
fun numSquares(n: Int): Int {
return when {
n.isPerfectSquare() -> 1
n.isSumOfTwoPerfectSquares() -> 2
n.isSumOfThreePerfectSquares() -> 3
else -> 4 // Lagrange's four-square theorem
}
}
private fun Int.isPerfectSquare(): Boolean {
val floorRoot = this.floorSqrt()
return this == floorRoot * floorRoot
}
private fun Int.floorSqrt() = sqrt(this.toDouble()).toInt()
private fun Int.isSumOfTwoPerfectSquares(): Boolean {
var first = 0
var second = floorSqrt()
while (first <= second) {
val squareSum = first * first + second * second
when {
squareSum < this -> first++
squareSum > this -> second--
else -> return true
}
}
return false
}
private fun Int.isSumOfThreePerfectSquares(): Boolean {
// Legendre's three-square theorem
var num = this
while (num and 3 == 0) {
num = num shr 2
}
return (num and 7) != 7
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,357 | hj-leetcode-kotlin | Apache License 2.0 |
classroom/src/main/kotlin/com/radix2/algorithms/week5/LLRBTree.kt | rupeshsasne | 190,130,318 | false | {"Java": 66279, "Kotlin": 50290} | package com.radix2.algorithms.week5
import com.radix2.algorithms.week4.SymbolTable
import com.radix2.algorithms.week4.put
import java.lang.StringBuilder
import java.util.*
class LLRBTree<K : Comparable<K>, V> : SymbolTable<K, V> {
private var root: Node<K, V>? = null
private enum class Color { RED, BLACK }
private class Node<K, V>(
var key: K,
var value: V,
var left: Node<K, V>? = null,
var right: Node<K, V>? = null,
var color: Color = Color.RED
)
override fun put(key: K, value: V) {
root = put(root, Node(key, value))
}
override fun get(key: K): V? = get(root, key)?.value
override fun min(): Pair<K, V>? = min(root)?.let { it.key to it.value }
override fun max(): Pair<K, V>? = max(root)?.let { it.key to it.value }
override fun floor(key: K): Pair<K, V>? = floor(root, key)?.let { it.key to it.value }
override fun ceil(key: K): Pair<K, V>? = ceil(root, key)?.let { it.key to it.value }
override fun toString(): String = levelOrder(root)
private fun getNodesAtLevel(root: Node<K, V>?, level: Int, builder: StringBuilder) {
if (root == null) return
if (level == 1) {
builder.append(root.key to root.value)
}
getNodesAtLevel(root.left, level - 1, builder)
getNodesAtLevel(root.right, level - 1, builder)
}
private fun height(root: Node<K, V>?): Int {
if (root == null)
return 0
return 1 + kotlin.math.max(height(root.left), height(root.right))
}
// M, E, R, C, L, P, X, A, H, S
// M, E, R, C, L, P, X, A, H, S
private fun levelOrder(root: Node<K, V>?): String {
if (root == null)
return ""
val queue: Queue<Node<K, V>> = LinkedList()
queue.add(root)
return buildString {
while (!queue.isEmpty()) {
if (length > 0)
append(", ")
append(queue.peek().key)
val node = queue.poll()
if (node.left != null)
queue.add(node.left)
if (node.right != null)
queue.add(node.right)
}
}
}
private fun levelOrder(root: Node<K, V>?, height: Int, builder: StringBuilder) {
for (i in 1..height) {
getNodesAtLevel(root, i, builder)
}
}
private fun inOrder(root: Node<K, V>?, builder: StringBuilder) {
if (root == null)
return
inOrder(root.left, builder)
builder.append(root.key to root.value)
inOrder(root.right, builder)
}
private fun put(root: Node<K, V>?, node: Node<K, V>): Node<K, V>? {
if (root == null)
return node
var trav = root
val cmp = node.key.compareTo(trav.key)
when {
cmp < 0 -> trav.left = put(trav.left, node)
cmp > 0 -> trav.right = put(trav.right, node)
else -> trav.value = node.value
}
when {
trav.right.isRed() && !trav.left.isRed() -> trav = rotateLeft(trav)
trav.left.isRed() && trav.left?.left.isRed() -> trav = rotateRight(trav)
trav.left.isRed() && trav.right.isRed() -> flipColors(trav)
}
return trav
}
private fun get(root: Node<K, V>?, key: K): Node<K, V>? {
if (root == null)
return null
val cmp = key.compareTo(root.key)
return when {
cmp < 0 -> get(root.left, key)
cmp > 0 -> get(root.right, key)
else -> root
}
}
private fun min(root: Node<K, V>?): Node<K, V>? {
if (root?.left == null)
return root
return min(root.left)
}
private fun max(root: Node<K, V>?): Node<K, V>? {
if (root?.right == null)
return root
return max(root.right)
}
private fun floor(root: Node<K, V>?, key: K): Node<K, V>? {
if (root == null)
return null
val cmp = key.compareTo(root.key)
return when {
cmp == 0 -> root
cmp < 0 -> floor(root.left, key)
else -> floor(root.right, key) ?: root
}
}
private fun ceil(root: Node<K, V>?, key: K): Node<K, V>? {
if (root == null)
return null
val cmp = key.compareTo(root.key)
return when {
cmp == 0 -> root
cmp < 0 -> ceil(root.left, key) ?: root
else -> ceil(root.right, key)
}
}
private fun Node<K, V>?.isRed() = (this?.color ?: Color.BLACK) == Color.RED
private fun rotateLeft(node: Node<K, V>): Node<K, V>? {
assert(node.isRed())
val trav = node
val temp = node.right
trav.right = temp?.left
temp?.left = trav
temp?.color = trav.color
trav.color = Color.RED
return temp
}
private fun rotateRight(node: Node<K, V>): Node<K, V>? {
assert(node.isRed())
val trav = node
val temp = node.left
trav.left = temp?.right
temp?.right = trav
temp?.color = trav.color
trav.color = Color.RED
return temp
}
private fun flipColors(node: Node<K, V>) {
assert(!node.isRed())
assert(node.left.isRed())
assert(node.right.isRed())
node.color = Color.RED
node.left?.color = Color.BLACK
node.right?.color = Color.BLACK
}
override fun deleteMin() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun rank(key: K): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun size(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun deleteMax() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun delete(key: K) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
fun main() {
val rbt = LLRBTree<Char, String?>()
rbt.put('S')
rbt.put('E')
rbt.put('A')
rbt.put('R')
rbt.put('C')
rbt.put('H')
rbt.put('X')
rbt.put('M')
rbt.put('P')
rbt.put('L')
println(rbt)
} | 0 | Java | 0 | 1 | 341634c0da22e578d36f6b5c5f87443ba6e6b7bc | 6,493 | coursera-algorithms-part1 | Apache License 2.0 |
src/main/kotlin/sschr15/aocsolutions/Day2.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.Challenge
import sschr15.aocsolutions.util.ReflectivelyUsed
import sschr15.aocsolutions.util.challenge
import sschr15.aocsolutions.util.ints
import sschr15.aocsolutions.util.watched.sum
import sschr15.aocsolutions.util.watched.watched
/**
* AOC 2023 [Day 2](https://adventofcode.com/2023/day/2)
* Challenge: Play a box guessing game, but first you have to see what would work with a predetermined guess,
* then you actually need to guess all on your own
*/
object Day2 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 2) {
// test()
part1 {
val (maxRed, maxGreen, maxBlue) = arrayOf(12, 13, 14)
inputLines.filter {
val (_, data) = it.split(": ")
val matches = data.split("; ")
matches.all { s ->
val pulls = s.split(", ")
pulls.none { pull ->
val (amount, color) = pull.split(" ")
when (color.trimEnd(',')) {
"red" -> amount.toInt() > maxRed
"green" -> amount.toInt() > maxGreen
"blue" -> amount.toInt() > maxBlue
else -> error("Unknown color: $color")
}
}
}
}.map { it.substringBefore(":").substringAfter(" ") }.ints().sum()
}
part2 {
inputLines.map {
val (_, data) = it.split(": ")
val matches = data.split("; ")
val pulls = matches.flatMap { s -> s.split(", ") }
var maxRed = 0
var maxGreen = 0
var maxBlue = 0
pulls.forEach { pull ->
val (amount, color) = pull.split(" ")
when (color.trimEnd(',')) {
"red" -> maxRed = maxRed.coerceAtLeast(amount.toInt())
"green" -> maxGreen = maxGreen.coerceAtLeast(amount.toInt())
"blue" -> maxBlue = maxBlue.coerceAtLeast(amount.toInt())
else -> error("Unknown color: $color")
}
}
maxRed.watched() * maxGreen * maxBlue
}.sum()
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 2,465 | advent-of-code | MIT License |
src/Day05.kt | matheusfinatti | 572,935,471 | false | {"Kotlin": 12612} | val stacks = listOf(
stackOf('W', 'R', 'F'),
stackOf('T', 'H', 'M', 'C', 'D', 'V', 'W', 'P'),
stackOf('P', 'M', 'Z', 'N', 'L'),
stackOf('J', 'C', 'H', 'R'),
stackOf('C', 'P', 'G', 'H', 'Q', 'T', 'B'),
stackOf('G', 'C', 'W', 'L', 'F', 'Z'),
stackOf('W', 'V', 'L', 'Q', 'Z', 'J', 'G', 'C'),
stackOf('P', 'N', 'R', 'F', 'W', 'T', 'V', 'C'),
stackOf('J', 'W', 'H', 'G', 'R', 'S', 'V'),
)
fun main() {
val input = readInput("Day05").split("\n\n")[1]
input
.split(" ", "\n")
.mapNotNull { s ->
if (s.any(Char::isDigit)) {
s.toInt()
} else {
null
}
}
.chunked(3)
// .also { moves ->
// moves.forEach { (amount, src, dst) ->
// repeat(amount) {
// val crate = stacks[src - 1].pop()
// stacks[dst - 1].push(crate!!)
// }
// }
// stacks.joinToString(separator = "") { stack ->
// stack.peek().toString()
// }.also(::println)
// }
.also { moves ->
moves.forEach { (amount, src, dst) ->
val moved = stacks[src - 1]
.subList(
stacks[src - 1].count() - amount,
stacks[src - 1].count()
)
for (i in 0 until amount) {
stacks[dst - 1].push(moved[i])
}
for (i in 0 until amount) {
stacks[src - 1].pop()
}
}
stacks.joinToString(separator = "") { stack ->
stack.peek().toString()
}.also(::println)
}
}
| 0 | Kotlin | 0 | 0 | a914994a19261d1d81c80e0ef8e196422e3cd508 | 1,756 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/com/github/xetra11/ck3workbench/app/validation/grammar/GrammarValidator.kt | xetra11 | 315,437,408 | false | null | package com.github.xetra11.ck3workbench.app.validation.grammar
import com.github.xetra11.ck3workbench.app.validation.grammar.GrammarParser.Grammar
/**
* The grammar parser takes a grammar definition and a list of [Token]
* and searches in that for a match. The match is returned as a subset of [Token]
*
* @author <NAME> aka "xetra11"
*/
open class GrammarValidator {
private val tokenRegexMapping: Map<TokenDefinition, Regex> = mapOf(
TokenType.OBJECT_ID to Regex("(.(\\w+\\.)*\\w*)"),
TokenType.ASSIGNMENT to Regex("^="),
TokenType.ATTRIBUTE_ID to Regex("^(\\w+)"),
TokenType.ATTRIBUTE_VALUE to Regex("^(\"?\\w+\"?)"),
TokenType.BLOCK_START to Regex("^\\{"),
TokenType.BLOCK_END to Regex("^}"),
OptionalTokenType.OBJECT_ID to Regex("(.(\\w+\\.)*\\w*)"),
OptionalTokenType.ASSIGNMENT to Regex("^="),
OptionalTokenType.ATTRIBUTE_ID to Regex("^(\\w+)"),
OptionalTokenType.ATTRIBUTE_VALUE to Regex("^(\"?\\w+\"?)"),
OptionalTokenType.BLOCK_START to Regex("^\\{"),
OptionalTokenType.BLOCK_END to Regex("^}")
)
open fun rule(grammar: Grammar, scriptLines: List<String>): GrammarValidation {
return if (grammar.tokenDefinition.isEmpty()) {
GrammarValidation(hasError = true, errorReason = "Grammar was undefined")
} else {
val formattedLines = scriptLines.prepareScriptString()
val nestedGrammar = nestGrammar(grammar)
var mandatoryTokenToFulfill = nestedGrammar.mandatoryToken().count()
var currentLevel = 0
val scriptValid = formattedLines.all { line ->
val pieces = line.split(" ").filter { it.isNotBlank() }
pieces.all { piece ->
when (piece) {
"{" -> {
currentLevel++
true
}
"}" -> {
currentLevel--
true
}
else -> {
mandatoryTokenToFulfill--
val grammarSection = nestedGrammar.level(currentLevel)
val tokenRegexCandidates = grammarSection
.mapTo(mutableListOf<Regex>()) { tokenRegexMapping[it] ?: Regex("") }
tokenRegexCandidates.any { it.matches(piece) }
}
}
}
}
if (!scriptValid) {
GrammarValidation(true, "Some token are not matching the given grammar")
} else if (mandatoryTokenToFulfill > 0) {
GrammarValidation(true, "Not all mandatory token were matched. $mandatoryTokenToFulfill were left out")
} else {
GrammarValidation()
}
}
}
private fun nestGrammar(grammar: Grammar): GrammarNester.NestedGrammar {
val grammarNester = GrammarNester()
return grammarNester.nest(grammar)
}
private fun List<String>.prepareScriptString(): MutableList<String> {
return this
.asSequence()
.map { it.replace("\\uFEFF", "") } // remove BOM
.map { it.trimStart() }
.map { it.trimEnd() }
.filter { it.isNotBlank() }
.toMutableList()
}
data class GrammarValidation(
val hasError: Boolean = false,
val errorReason: String = ""
)
data class Token(
val value: String,
val type: TokenType
)
companion object {
const val NEXT = 0
}
interface TokenDefinition
enum class TokenType : TokenDefinition {
OBJECT_ID,
ATTRIBUTE_ID,
ATTRIBUTE_VALUE,
BLOCK_START,
BLOCK_END,
ASSIGNMENT,
UNTYPED
}
enum class OptionalTokenType : TokenDefinition {
OBJECT_ID,
ATTRIBUTE_ID,
ATTRIBUTE_VALUE,
BLOCK_START,
BLOCK_END,
ASSIGNMENT,
UNTYPED
}
}
| 20 | Kotlin | 1 | 8 | dc10ec20c8794216bb641f93b7b3c1196063dd24 | 4,149 | CK3-Workbench | MIT License |
src/Day10.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | fun main() {
fun part1(input: List<Cmd>) {
var x = 1
input.mapIndexedNotNull { i, cmd ->
var ret: Int? = null
if (i + 1 in listOf(20, 60, 100, 140, 180, 220)) {
ret = x * (i + 1)
}
when (cmd) {
is Addx -> x += cmd.value
Noop -> {}
}
ret
}.sum().log("part1")
}
fun part2(input: List<Cmd>) {
var x = 1
var sprite = 0 until 3
input.forEachIndexed { i, cmd ->
if (i % 40 in sprite) {
print("██")
} else {
print(" ")
}
when (cmd) {
is Addx -> {
x += cmd.value
sprite = (x - 1) until (x + 2)
}
Noop -> {}
}
if ((i + 1) % 40 == 0) {
println()
}
}
"part2".log()
}
val input = downloadAndReadInput("Day10").flatMap { Cmd.parse(it) }
part1(input)
part2(input)
}
sealed interface Cmd {
companion object {
fun parse(s: String): List<Cmd> {
return if (s == "noop") listOf(Noop)
else if (s.startsWith("addx")) listOf(
Noop, Addx(
s.removePrefix("addx ").toInt()))
else error("unknown")
}
}
}
object Noop : Cmd
data class Addx(val value: Int) : Cmd
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 1,478 | advent-of-code-2022 | Apache License 2.0 |
kotlin/0063-unique-paths-ii.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} | // If we can't do inplace, space O(N)
class Solution {
fun uniquePathsWithObstacles(grid: Array<IntArray>): Int {
val m = grid.lastIndex
val n = grid[0].lastIndex
if (grid[m][n] == 1 || grid[0][0] == 1) return 0
val dp = IntArray(n+1)
dp[n] = 1
for (i in m downTo 0) {
for (j in n downTo 0) {
if (grid[i][j] == 1) dp[j] = 0
else if (j < n) dp[j] = dp[j] + dp[j + 1]
//else dp[j] = dp[j] + 0
}
}
return dp[0]
}
}
// In place O(1)
class Solution {
fun uniquePathsWithObstacles(grid: Array<IntArray>): Int {
val m = grid.lastIndex
val n = grid[0].lastIndex
if (grid[m][n] == 1 || grid[0][0] == 1) return 0
grid[m][n] = 1
for (i in m-1 downTo 0) {
grid[i][n] = if(grid[i][n] == 0 && grid[i + 1][n] == 1) 1 else 0
}
for (i in n-1 downTo 0) {
grid[m][i] = if(grid[m][i] == 0 && grid[m][i + 1] == 1) 1 else 0
}
for (i in m-1 downTo 0) {
for (j in n-1 downTo 0) {
if(grid[i][j] != 1) {
grid[i][j] = grid[i + 1][j] + grid[i][j + 1]
} else {
grid[i][j] = 0
}
}
}
return grid[0][0]
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,391 | leetcode | MIT License |
app/src/main/java/online/vapcom/codewars/numbers/Numbers.kt | vapcomm | 503,057,535 | false | {"Kotlin": 142486} | package online.vapcom.codewars.numbers
import kotlin.math.truncate
// https://www.codewars.com/kata/5aba780a6a176b029800041c/train/kotlin
fun maxMultiple(divisor: Int, bound: Int): Int {
if (divisor <= 0 || bound <= 0 || divisor > bound)
return 0
if (bound % divisor == 0)
return bound
var divCount = 1
while (divCount <= divisor) {
if ((bound - divCount) % divisor == 0)
return bound - divCount
else divCount++
}
return 0
}
// Tribonacci Sequence
// https://www.codewars.com/kata/556deca17c58da83c00002db/train/kotlin
fun tribonacci(signature: DoubleArray, n: Int): DoubleArray {
if (signature.size != 3 || n <= 0)
return doubleArrayOf()
if (n <= signature.size)
return signature.copyOfRange(0, n)
val result = DoubleArray(n)
signature.forEachIndexed { index, d -> result[index] = d }
for (i in signature.size until n) {
result[i] = result[i - 1] + result[i - 2] + result[i - 3]
}
return result
}
// Product of consecutive Fib numbers
// https://www.codewars.com/kata/5541f58a944b85ce6d00006a/train/kotlin
// Есть похожие решения один в один
fun productFib(prod: Long): LongArray {
var x = 0L
var y = 1L
while (x * y < prod) {
val n = x + y
x = y
y = n
}
return longArrayOf(x, y, if (x * y == prod) 1 else 0)
}
/**
* Going to zero or to infinity?
*
* https://www.codewars.com/kata/55a29405bc7d2efaff00007c/train/kotlin
*/
fun going(n: Int): Double {
return when {
n <= 0 -> 0.0
n == 1 -> 1.0
else -> {
var sum = 1.0
var mult = 1.0
for (i in n downTo 2) {
mult *= i
sum += 1 / mult
}
return truncate(sum * 1E6) / 1E6
}
}
}
/**
* Maximum subarray sum
*
* https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c/train/kotlin
*/
fun maxSequence(arr: List<Int>): Int {
if (arr.isEmpty())
return 0
// fast check all negative
var isAllNegative = true
for (a in arr) {
if (a >= 0) {
isAllNegative = false
break
}
}
if (isAllNegative) return 0
fun seqSum(start: Int, end: Int): Int {
var result = 0
for (i in start..end) {
result += arr[i]
}
return result
}
var maxSum = Int.MIN_VALUE
for (windowSize in 1..arr.size) {
for (i in 0..(arr.size - windowSize)) {
val sum = seqSum(i, i + windowSize - 1)
if (sum > maxSum)
maxSum = sum
}
}
return maxSum
}
/**
* RGB To Hex Conversion
*
* https://www.codewars.com/kata/513e08acc600c94f01000001/train/kotlin
*/
fun rgb(r: Int, g: Int, b: Int): String {
fun clearColor(num: Int): Int {
return when {
num < 0 -> 0
num > 255 -> 255
else -> num
}
}
return String.format("%02X%02X%02X", clearColor(r), clearColor(g), clearColor(b))
}
| 0 | Kotlin | 0 | 0 | 97b50e8e25211f43ccd49bcee2395c4bc942a37a | 3,084 | codewars | MIT License |
src/main/kotlin/dev/shtanko/algorithms/dp/MinCoins.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.dp
/**
* Coin Change Problem
* Given a set of coins and a target amount, find the minimum number of coins needed to make up that amount.
*
* Find the minimum number of coins needed to make up a given amount using dynamic programming.
*
* @param coins An array of coin denominations.
* @param amount The target amount to make up.
* @return The minimum number of coins needed to make up the amount. Returns -1 if it's not possible.
*/
fun minCoins(coins: IntArray, amount: Int): Int {
// Create an array to store the minimum number of coins needed for each amount from 0 to the given amount.
val dp = IntArray(amount + 1) { Int.MAX_VALUE }
// Base case: No coins needed to make up amount 0.
dp[0] = 0
// Loop through all amounts from 1 to the target amount.
for (i in 1..amount) {
// Loop through each coin denomination.
for (coin in coins) {
// Check if the current coin can be used to make up the current amount (i) and if
// using this coin leads to a smaller number of coins compared to the previous result.
if (coin <= i && dp[i - coin] != Int.MAX_VALUE) {
// Update the minimum number of coins needed for the current amount (i).
dp[i] = minOf(dp[i], dp[i - coin] + 1)
}
}
}
// If dp[amount] is still Int.MAX_VALUE, it means it's not possible to make up the amount with the given coins.
// Return -1 in such cases, otherwise, return the minimum number of coins needed.
return if (dp[amount] == Int.MAX_VALUE) -1 else dp[amount]
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,222 | kotlab | Apache License 2.0 |
common/number/src/main/kotlin/com/curtislb/adventofcode/common/number/Sequences.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.common.number
import java.math.BigInteger
import kotlin.math.floor
import kotlin.math.sqrt
/**
* Returns the [n]th triangular number, defined as the sum of integers 0..[n].
*
* If [n] < 0, this function instead returns `triangleNumber(abs(n) - 1)`.
*/
fun triangleNumber(n: Int): Int = if (n % 2 == 0) n / 2 * (n + 1) else (n + 1) / 2 * n
/**
* Returns the [n]th triangular number, defined as the sum of integers 0..[n].
*
* If [n] < 0, this function instead returns `triangleNumber(abs(n) - 1)`.
*/
fun triangleNumber(n: Long): Long = if (n % 2L == 0L) n / 2L * (n + 1L) else (n + 1L) / 2L * n
/**
* Returns the [n]th triangular number, defined as the sum of integers 0..[n].
*
* If [n] < 0, this function instead returns `triangleNumber(abs(n) - 1)`.
*/
fun triangleNumber(n: BigInteger): BigInteger = n * (n + BigInteger.ONE) / BigInteger.TWO
/**
* If [n] is a triangular number, returns the unique non-negative integer value `m` such that
* `triangleNumber(m) == n`.
*
* If [n] is *not* a triangular number, the behavior of this function is undefined.
*/
fun triangleNumberInverse(n: Int): Int = floor(sqrt(n * 2.0)).toInt()
/**
* If [n] is a triangular number, returns the unique non-negative integer value `m` such that
* `triangleNumber(m) == n`.
*
* If [n] is *not* a triangular number, the behavior of this function is undefined.
*/
fun triangleNumberInverse(n: Long): Long = floor(sqrt(n * 2.0)).toLong()
/**
* If [n] is a triangular number, returns the unique non-negative integer value `m` such that
* `triangleNumber(m) == n`.
*
* If [n] is *not* a triangular number, the behavior of this function is undefined.
*/
fun triangleNumberInverse(n: BigInteger): BigInteger = (n * BigInteger.TWO).sqrt()
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 1,779 | AdventOfCode | MIT License |
src/Day13_2.kt | jrmacgill | 573,065,109 | false | {"Kotlin": 76362} | import utils.splitBy
class Day13 {
// giberish
fun parse(line : String, nest : MutableList<Any>) : Int {
var i = 0
var digit = ""
while (i < line.length) {
i++
if (line[i].isDigit()) {
digit += line[i]; continue}
when (line[i]) {
'[' -> {
var n = mutableListOf<Any>()
nest.add(n)
i += parse(line.substring(i), n)
}
']' -> {
if (digit.isNotEmpty()) {
nest.add(digit.toInt())
}
return i
}
',' -> if (digit.isNotEmpty()) {nest.add(digit.toInt()); digit=""}
else -> {}
}
}
return -1
}
fun comp(a: MutableList<*>, b: MutableList<*>, depth : Int) : Boolean {
println(" ".repeat(depth) + "Compare " + a + " vs " + b)
if (a.zip(b).any {
println(" ".repeat(depth) + "Compare " + it.first + " vs " + it.second)
when {
it.first is Int && it.second is Int -> {
if ((it.first as Int) < (it.second as Int)) throw Exception("pass")
if ((it.first as Int) > (it.second as Int)) throw Exception("fail")
false
}
it.first is MutableList<*> && it.second is MutableList<*> -> comp(it.first as MutableList<*>,
it.second as MutableList<*>, depth +1
)
it.first is Int -> comp(mutableListOf(it.first), it.second as MutableList<*>, depth+1)
it.second is Int -> comp(it.first as MutableList<*>, mutableListOf(it.second), depth + 1)
else -> false
}
//else -> false
}) return true
if (a.size == b.size) return false
if (b.size < a.size) {
throw Exception("fail")
}
throw Exception("pass")
}
fun go() {
var lines =readInput("dayThirteen")
var pairs = lines.splitBy { a -> a.isEmpty() }
println(pairs.zipWithNext().size)
var sum = 0
pairs.forEachIndexed() { i, e ->
println(" Pair " + (i + 1))
val a = mutableListOf<Any>()
val b = mutableListOf<Any>()
parse(e[0], a)
parse(e[1], b)
try {
if (comp(a, b, 0)) {
println("found")
// sum += (i + 1)
}
} catch (e: Exception) {
println(e)
if (e.message == "pass") {
sum += (i + 1)
} else {
}
}
}
println(sum)
}
}
fun main() {
Day13().go()
} | 0 | Kotlin | 0 | 1 | 3dcd590f971b6e9c064b444139d6442df034355b | 2,910 | aoc-2022-kotlin | Apache License 2.0 |
src/Day10.kt | tomoki1207 | 572,815,543 | false | {"Kotlin": 28654} | data class Cpu(
var x: Int = 1,
var cycle: Int = 0
) {
val signalStrengths = mutableListOf<Int>()
fun exec(instruction: String, arg: Int?) {
when (instruction) {
"noop" -> {
cycle++
signalStrengths.add(x * cycle)
draw()
}
"addx" -> {
repeat(2) {
cycle++
signalStrengths.add(x * cycle)
draw()
}
x += arg!!
}
}
}
private fun draw() {
print(if (inSprite()) "#" else ".")
if (cycle % 40 == 0) {
println()
}
}
private fun inSprite(): Boolean {
val col = cycle % 40
return col in x..x + 2
}
}
fun main() {
fun part1(input: List<String>): Int {
val cpu = Cpu()
input.map { line -> line.split(" ").let { Pair(it[0], if (it.size == 2) it[1].toInt() else null) } }
.forEach {
cpu.exec(it.first, it.second)
}
return cpu.signalStrengths.filterIndexed { index, _ -> ((index + 1) - 20) % 40 == 0 }.sum()
}
fun part2(){
println("Check above!!")
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val input = readInput("Day10")
println(part1(input))
part2()
}
| 0 | Kotlin | 0 | 0 | 2ecd45f48d9d2504874f7ff40d7c21975bc074ec | 1,392 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main.kt | BenjaminEarley | 151,190,621 | false | null | fun main(args: Array<String>) {
//Data
val primes = arrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
val numbers = arrayOf(70, 46, 51, 66, 9, 75, 43)
val tree =
Branch(
Branch(Leaf(4), Leaf(9)),
Branch(
Branch(
Leaf(7),
Branch(Leaf(2), Leaf(1))
),
Branch(
Leaf(5),
Branch(
Leaf(5),
Branch(Leaf(11), Leaf(8))
)
)
)
)
//Execute and Print
println("\nExercises 2\n")
print("Factorial") { fac(5) }
print("Fibonacci") { fib(5) }
print("Sorting") { isSorted(arrayOf(1, 2, 3, 2)) { a, b -> a <= b } }
println("\nExercises 3\n")
print("Tree Size") { tree.size() }
print("Tree Size With Fold") { tree.sizeViaFold() }
print("Tree Max") { tree.max() }
print("Tree Max With Fold") { tree.maxViaFold() }
print("Tree Depth") { tree.depth() }
print("Tree Depth") { tree.depthViaFold() }
print("Tree Map") { tree.map { it + 1 } }
print("Tree Map") { tree.mapViaHold { it + 1 } }
println("\nExercises 4\n")
print("Sequence") { listOf(Some(4), Some(9), Some(3), Some(7)).toConsList().sequence() }
print("Sequence") { listOf(Some(4), Some(9), Some(3), None, Some(7)).toConsList().sequence() }
println("\nAlgorithms\n")
print("Binary Search") { binarySearch(primes.copyOf(), 73) }
print("Selection Sort") { selectionSort(numbers.copyOf()).contentToString() }
print("Insertion Sort") { insertionSort(numbers.copyOf()).contentToString() }
print("Insertion Sort Alt") { insertionSort2(numbers.copyOf().iterator()).asSequence().toList().toString() }
print("Merge Sort") { mergeSort(numbers.copyOf().toList()) }
println("\nChallenges\n")
print("Palindrome", { "RATER".isPalindrome() }, { "ROTOR".isPalindrome() })
print("Power", { power(3, -2) }, { power(3, -1) }, { power(3, 0) }, { power(3, 1) }, { power(3, 2) })
print("Hanoi") { solveHanoi(1, Tower.LEFT, Tower.MIDDLE); "above" }
print("Fibonacci in Linear Time") { linFib(100) }
print("Factorial in Tail Position") { tailRecFactorial(8) }
}
fun print(action: String, f: () -> Any) =
println("$action result is ${f()}")
fun print(action: String, vararg functions: () -> Any) =
println("$action results are: ${functions.fold("") { acc, f -> acc + "\n " + f().toString() }}")
| 0 | Kotlin | 0 | 0 | 1a4278273f3d79d4e5bb7054d0e5fb91274e871c | 2,599 | Functional_Kotlin | MIT License |
2019/src/test/kotlin/com/github/jrhenderson1988/adventofcode2019/day22/DeckTest.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019.day22
import org.junit.Assert.assertEquals
import org.junit.Test
class DeckTest {
@Test
fun cut() =
mapOf(
Pair(Deck.create(0..9), 3) to Deck(listOf(3, 4, 5, 6, 7, 8, 9, 0, 1, 2)),
Pair(Deck.create(0..9), -4) to Deck(listOf(6, 7, 8, 9, 0, 1, 2, 3, 4, 5))
).forEach { (input, expected) ->
assertEquals(expected, input.first.cut(input.second))
}
@Test
fun dealWithIncrement() =
mapOf(
Pair(Deck.create(0..9), 3) to Deck(listOf(0, 7, 4, 1, 8, 5, 2, 9, 6, 3))
).forEach { (input, expected) ->
assertEquals(expected, input.first.dealWithIncrement(input.second))
}
@Test
fun dealIntoNewStack() =
mapOf(
Deck.create(0..9) to Deck.create(9 downTo 0),
Deck.create(9 downTo 0) to Deck.create(0..9)
).forEach { (input, expected) ->
assertEquals(expected, input.dealIntoNewStack())
}
@Test
fun execute() =
mapOf(
Pair(Deck.create(0..9), "deal into new stack") to Deck.create(9 downTo 0),
Pair(Deck.create(0..9), "cut 3") to Deck(listOf(3, 4, 5, 6, 7, 8, 9, 0, 1, 2)),
Pair(Deck.create(0..9), "cut -4") to Deck(listOf(6, 7, 8, 9, 0, 1, 2, 3, 4, 5)),
Pair(Deck.create(0..9), "deal with increment 3") to Deck(listOf(0, 7, 4, 1, 8, 5, 2, 9, 6, 3))
).forEach { (input, expected) ->
assertEquals(expected, input.first.execute(input.second))
}
@Test
fun executeMany() = mapOf(
Pair(
Deck.create(0..9),
listOf(
"deal with increment 7",
"deal into new stack",
"deal into new stack"
)
) to Deck(listOf(0, 3, 6, 9, 2, 5, 8, 1, 4, 7)),
Pair(
Deck.create(0..9),
listOf(
"cut 6",
"deal with increment 7",
"deal into new stack"
)
) to Deck(listOf(3, 0, 7, 4, 1, 8, 5, 2, 9, 6)),
Pair(
Deck.create(0..9),
listOf(
"deal with increment 7",
"deal with increment 9",
"cut -2"
)
) to Deck(listOf(6, 3, 0, 7, 4, 1, 8, 5, 2, 9)),
Pair(
Deck.create(0..9),
listOf(
"deal into new stack",
"cut -2",
"deal with increment 7",
"cut 8",
"cut -4",
"deal with increment 7",
"cut 3",
"deal with increment 9",
"deal with increment 3",
"cut -1"
)
) to Deck(listOf(9, 2, 5, 8, 1, 4, 7, 0, 3, 6))
).forEach { (input, expected) ->
assertEquals(expected, input.first.execute(input.second))
}
@Test
fun positionOf() =
mapOf(
Pair(Deck.create(0..9), 7) to 7,
Pair(Deck.create(9 downTo 0), 7) to 2,
Pair(Deck.create(9 downTo 0), 5) to 4
).forEach { (input, expected) ->
assertEquals(expected, input.first.positionOf(input.second))
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 3,239 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2023/days/Day3.kt | mathstar | 719,656,133 | false | {"Kotlin": 107115} | package com.staricka.adventofcode2023.days
import com.staricka.adventofcode2023.framework.Day
import com.staricka.adventofcode2023.util.BasicCell
import com.staricka.adventofcode2023.util.Grid
import com.staricka.adventofcode2023.util.StandardGrid
class Day3: Day {
/**
* Given the start coordinate of a number, determines the number and the end coordinate
* @return (number, end)
*/
private fun identifyNumber(grid: Grid<BasicCell>, i: Int, j: Int): Pair<Int, Int> {
var j = j
var num = (grid[i, j]!!.symbol - '0')
while (grid[i, j + 1]?.symbol?.isDigit() == true) {
num *= 10
num += grid[i, j + 1]!!.symbol - '0'
j++
}
return Pair(num, j)
}
override fun part1(input: String): Int {
var sum = 0
val grid = StandardGrid.build(input){BasicCell(it)}
for (i in 0..input.lines().filter(String::isNotBlank).size) {
var j = 0
while (j <= input.lines().first().length) {
if (grid[i, j]?.symbol?.isDigit() == true) {
val rangeStart = j
var (num, rangeEnd) = identifyNumber(grid, i, j)
j = rangeEnd
for ((_,cell) in grid.neighbors(i, (rangeStart..rangeEnd))) {
if(cell?.symbol != null && !cell.symbol.isDigit() && cell.symbol != '.') {
sum += num
break
}
}
}
j++
}
}
return sum
}
override fun part2(input: String): Int {
val grid = StandardGrid.build(input){BasicCell(it)}
val gears = HashMap<Pair<Int, Int>, MutableList<Int>>()
for (i in 0..input.lines().filter(String::isNotBlank).size) {
var j = 0
while (j <= input.lines().first().length) {
if (grid[i, j]?.symbol?.isDigit() == true) {
val rangeStart = j
var (num, rangeEnd) = identifyNumber(grid, i, j)
j = rangeEnd
for ((k,cell) in grid.neighbors(i, (rangeStart..rangeEnd))) {
if(cell?.symbol == '*') {
val list = gears.computeIfAbsent(k){_ -> ArrayList()}
list.add(num)
}
}
}
j++
}
}
return gears.values.filter { it.size == 2 }.sumOf { it.reduce { a, n -> a * n } }
}
} | 0 | Kotlin | 0 | 0 | 8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa | 2,596 | adventOfCode2023 | MIT License |
kotlin/app/src/main/kotlin/coverick/aoc/day11/MonkeyInTheMiddle.kt | RyTheTurtle | 574,328,652 | false | {"Kotlin": 82616} | package coverick.aoc.day11
import readResourceFile
val INPUT_FILE = "monkeyInTheMiddle-input.txt"
class Monkey(startingItems: ArrayList<Long>,
op: (Long) -> Long,
test: (Long)-> Int) {
val items = startingItems
val op = op
val test = test
var inspections = 0L
fun inspect(item:Long) :Long{
inspections++
return op(item)
}
}
fun getProgramInput(): ArrayList<Monkey> {
// avoid parsing because that's not the objective of the program, just hardcoding inputs for this one
val monkeys = ArrayList<Monkey>()
monkeys.add(
Monkey(
arrayListOf(84, 72, 58, 51L),
{l -> l * 3},
{l -> if (l % 13 == 0L ) 1 else 7 })
)
monkeys.add(
Monkey(
arrayListOf(88L, 58, 58),
{l -> l + 8},
{l -> if (l % 2 == 0L ) 7 else 5 })
)
monkeys.add(
Monkey(
arrayListOf(93L, 82, 71, 77, 83, 53, 71, 89),
{l -> l * l},
{l -> if (l % 7 == 0L ) 3 else 4})
)
monkeys.add(
Monkey(
arrayListOf(81L, 68, 65, 81, 73, 77, 96),
{l -> l + 2},
{l -> if (l % 17 == 0L ) 4 else 6 })
)
monkeys.add(
Monkey(
arrayListOf(75L, 80, 50, 73, 88),
{l -> l + 3},
{l -> if (l % 5 == 0L ) 6 else 0})
)
monkeys.add(
Monkey(
arrayListOf(59L, 72, 99, 87, 91, 81),
{l -> l * 17},
{l -> if (l % 11 == 0L ) 2 else 3})
)
monkeys.add(
Monkey(
arrayListOf(86L , 69),
{l -> l + 6},
{l -> if (l % 3 == 0L ) 1 else 0 })
)
monkeys.add(
Monkey(
arrayListOf(91L),
{l -> l + 1},
{l -> if (l % 19 == 0L ) 2 else 5 })
)
return monkeys
}
fun part1(): Long {
var monkeys = getProgramInput()
val ROUNDS = 20
val relief : (Long) -> Long = {l -> l / 3}
for(i in 1..ROUNDS){
for(monkey in monkeys){
while(monkey.items.size > 0){
var item = monkey.items.removeAt(0)
// monkey inspects, then we get relief
item = relief(monkey.inspect(item))
val monkeyToThrowTo = monkey.test(item)
monkeys.get(monkeyToThrowTo).items.add(item)
}
}
}
val monkeysSortedByInspections = monkeys.map { it.inspections}.sortedDescending()
return monkeysSortedByInspections.get(0) * monkeysSortedByInspections.get(1)
}
fun part2(): Long {
var monkeys = getProgramInput()
val ROUNDS = 10000
// had to look this one up, relief value is modulo the product of all primes
// being used by the monkeys. effectively, this chunks the value for each worry multiplication
// operation to have the same divisbile remainder but without causing integer overflow and without
// taking an absurd amount of memory and time to compute it using bigDecimal
val superMod: Long = (13*2*7*17*5*11*3*19 )
val relief : (Long) -> Long = {l -> l % superMod}
for(i in 1..ROUNDS){
for(monkey in monkeys){
while(monkey.items.size > 0){
var item = monkey.items.removeAt(0)
// monkey inspects, then we get relief
item = relief(monkey.inspect(item))
val monkeyToThrowTo = monkey.test(item)
monkeys.get(monkeyToThrowTo).items.add(item)
}
}
}
val monkeysSortedByInspections = monkeys.map { it.inspections}.sortedDescending()
println("${monkeysSortedByInspections}")
return monkeysSortedByInspections.get(0).toLong() * monkeysSortedByInspections.get(1).toLong()
}
fun solution(){
println("Monkey In The Middle part 1 solution: ${part1()}")
println("Monkey In The Middle part 2 solution: ${part2()}")
} | 0 | Kotlin | 0 | 0 | 35a8021fdfb700ce926fcf7958bea45ee530e359 | 3,934 | adventofcode2022 | Apache License 2.0 |
src/day3.kts | AfzalivE | 317,962,201 | false | null | println("Start")
val input = readInput("day3.txt").readLines().map {
it.repeat(500)
}
val slopes = listOf(
Slope(1, 1),
Slope(3, 1),
Slope(5, 1),
Slope(7, 1),
Slope(1, 2)
)
val treesHit = slopes.map {
val treesHit1 = treesHit(it)
println("Hit $treesHit1 for $it")
treesHit1
}
val product = treesHit.reduce { acc, i ->
acc * i
}
println(product)
fun treesHit(slope: Slope): Int {
var i = slope.right
var row = slope.down
var treesHit = 0
while (row < input.size) {
val currRow = input[row]
if (currRow[i] == "#".single()) {
treesHit += 1
}
i += slope.right
row += slope.down
}
return treesHit
}
data class Slope(
val right: Int,
val down: Int
) | 0 | Kotlin | 0 | 0 | cc5998bfcaadc99e933fb80961be9a20541e105d | 773 | AdventOfCode2020 | Apache License 2.0 |
src/chapter4/section1/ex14.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter4.section1
import edu.princeton.cs.algs4.In
import edu.princeton.cs.algs4.Stack
/**
* 如果用栈代替队列来实现广度优先搜索,我们还能得到最短路径吗?
*
* 解:能,用两个栈而不是一个栈
* 遍历时,从一个栈中取顶点信息,将顶点的相邻顶点加入另一个栈中,当第一个栈为空时,交换两个栈
* 当两个栈都为空时,遍历结束
* 和用队列实现的广度优先搜索对比,空间复杂度增加了常数值,时间复杂度不变
*/
class StackBreadthFirstPath(graph: Graph, val s: Int) : Paths(graph, s) {
private val marked = BooleanArray(graph.V)
private val edgeTo = IntArray(graph.V)
init {
var inputStack = Stack<Int>()
var outputStack = Stack<Int>()
inputStack.push(s)
marked[s] = true
while (!inputStack.isEmpty) {
val v = inputStack.pop()
graph.adj(v).forEach { w ->
if (!marked[w]) {
outputStack.push(w)
marked[w] = true
edgeTo[w] = v
}
}
if (inputStack.isEmpty) {
val temp = inputStack
inputStack = outputStack
outputStack = temp
}
}
}
override fun hasPathTo(v: Int): Boolean {
return marked[v]
}
override fun pathTo(v: Int): Iterable<Int>? {
if (!hasPathTo(v)) return null
val stack = Stack<Int>()
var w = v
while (w != s) {
stack.push(w)
w = edgeTo[w]
}
stack.push(s)
return stack
}
}
fun main() {
val graph = Graph(In("./data/mediumG.txt"))
val paths1 = BreadthFirstPaths(graph, 0)
val paths2 = StackBreadthFirstPath(graph, 0)
for (v in 0 until graph.V) {
check(paths1.pathTo(v)?.count() == paths2.pathTo(v)?.count())
println("v : $v")
println("paths1 : ${paths1.pathTo(v)?.joinToString()}")
println("paths2 : ${paths2.pathTo(v)?.joinToString()}")
}
println()
println("mediumG check succeed.")
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,148 | Algorithms-4th-Edition-in-Kotlin | MIT License |
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day22/Day22.kt | pfmaggi | 438,378,048 | false | {"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184} | /*
* 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 com.pietromaggi.aoc2021.day22
import com.pietromaggi.aoc2021.readInput
fun part1(input: List<String>): Int {
data class Point(val x: Int, val y: Int, val z: Int)
val cuboids = mutableSetOf<Point>()
input.forEach { line ->
val items = line.split(",")
val on = items[0].startsWith("on")
val (x1, x2) = items[0].removePrefix("on x=").removePrefix("off x=").split("..").map(String::toInt)
val (y1, y2) = items[1].removePrefix("y=").split("..").map(String::toInt)
val (z1, z2) = items[2].removePrefix("z=").split("..").map(String::toInt)
if ((x1 in -50..50) and (y1 in -50..50) and (z1 in -50..50)) {
x1.coerceAtLeast(-50)
x2.coerceAtMost(50)
y1.coerceAtLeast(-50)
y2.coerceAtMost(50)
z1.coerceAtLeast(-50)
z2.coerceAtMost(50)
for (x in x1..x2) for (y in y1..y2) for (z in z1..z2)
if (on)
cuboids.add(Point(x, y, z))
else
cuboids.remove(Point(x, y, z))
}
}
return cuboids.count()
}
fun part2(input: List<String>): Long {
data class Cube(
val x1: Int, val x2: Int,
val y1: Int, val y2: Int,
val z1: Int, val z2: Int,
val sign: Int,
)
var cuboids = listOf<Cube>()
input.forEach { line ->
val items = line.split(",")
val sign = if (items[0].startsWith("on")) 1 else -1
val (nx1, nx2) = items[0].removePrefix("on x=").removePrefix("off x=").split("..").map(String::toInt)
val (ny1, ny2) = items[1].removePrefix("y=").split("..").map(String::toInt)
val (nz1, nz2) = items[2].removePrefix("z=").split("..").map(String::toInt)
val temp = mutableListOf<Cube>()
for ((ex1, ex2, ey1, ey2, ez1, ez2, esign) in cuboids) {
temp.add(Cube(ex1, ex2, ey1, ey2, ez1, ez2, esign))
val ix1 = nx1.coerceAtLeast(ex1)
val ix2 = nx2.coerceAtMost(ex2)
val iy1 = ny1.coerceAtLeast(ey1)
val iy2 = ny2.coerceAtMost(ey2)
val iz1 = nz1.coerceAtLeast(ez1)
val iz2 = nz2.coerceAtMost(ez2)
if ((ix1 <= ix2) and (iy1 <= iy2) and (iz1 <= iz2)) {
temp.add(Cube(ix1, ix2, iy1, iy2, iz1, iz2, -esign))
}
}
if (sign > 0) {
temp.add(Cube(nx1, nx2, ny1, ny2, nz1, nz2, sign))
}
cuboids = temp
}
return cuboids.map { cube ->
(cube.x2 - cube.x1 + 1).toLong() * (cube.y2 - cube.y1 + 1) * (cube.z2 - cube.z1 + 1) * cube.sign
}.fold(0L) { sum, element ->
sum + element
}
}
fun main() {
val input = readInput("Day22")
println("""
### DAY 22 ###
==============
how many cubes are on?
--> ${part1(input)}
how many cubes are on?
--> ${part2(input)}
""")
} | 0 | Kotlin | 0 | 0 | 7c4946b6a161fb08a02e10e99055a7168a3a795e | 3,495 | AdventOfCode | Apache License 2.0 |
src/com/mrxyx/algorithm/SlidingWindow.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
/**
* 滑动窗口
*/
class SlidingWindow {
/**
* 最小覆盖字串
* https://leetcode-cn.com/problems/minimum-window-substring
*/
fun minWindow(s: String, t: String): String {
val need = HashMap<Char, Int>()
val window = HashMap<Char, Int>()
//初始化
for (c in t) {
need[c] = need.getOrDefault(c, 0) + 1
}
var left = 0
var right = 0
var valid = 0
var start = 0
var legth = Int.MAX_VALUE
//移动右边界
while (right < s.length) {
val char = s[right]
right++
if (need.containsKey(char)) {
window[char] = window.getOrDefault(char, 0) + 1
if (window[char] == need[char])
valid++
}
//移动左边界
while (valid == need.size) {
if (right - left < legth) {
start = left
legth = right - left
}
val char = s[left]
left++
if (need.containsKey(char)) {
if (window[char] == need[char])
valid--
window[char] = window.getOrDefault(char, 1) - 1
}
}
}
return if (legth == Int.MAX_VALUE) "" else s.substring(start, start + legth)
}
/**
* 字符串排列
* https://leetcode-cn.com/problems/permutation-in-string/
*/
fun checkInclusion(s: String, t: String): Boolean {
val need = HashMap<Char, Int>()
val window = HashMap<Char, Int>()
var left = 0
var right = 0
var valid = 0
while (right < s.length) {
val char = s[left]
right++
if (need.containsKey(char)) {
window[char] = window.getOrDefault(char, 0)
if (window[char] == need[char])
valid++
}
while (right - left < t.length) {
if (valid == need.size) return true
val char = s[left]
left++
if (need.containsKey(char)) {
if (window[char] == need[char]) valid--
window[char] = window.getOrDefault(char, 1) - 1
}
}
}
return false
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 2,434 | algorithm-test | The Unlicense |
kotlin/Gauss.kt | indy256 | 1,493,359 | false | {"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571} | import kotlin.math.abs
import java.util.Random
// https://en.wikipedia.org/wiki/Gauss–Jordan_elimination
// returns x such that A * x = b. requires |A| > 0
fun gauss(A: Array<DoubleArray>, b: DoubleArray): DoubleArray {
val a = A.mapIndexed { i, Ai -> Ai + b[i] }.toTypedArray()
val n = a.size
for (i in 0 until n) {
val pivot = (i until n).maxByOrNull { abs(a[it][i]) }!!
a[i] = a[pivot].also { a[pivot] = a[i] }
for (j in i + 1..n)
a[i][j] /= a[i][i]
for (j in 0 until n)
if (j != i && a[j][i] != 0.0)
for (k in i + 1..n)
a[j][k] -= a[i][k] * a[j][i]
}
return a.map { it[n] }.toDoubleArray()
}
// random test
fun main() {
val rnd = Random(1)
for (step in 0..9999) {
val n = rnd.nextInt(5) + 1
val a = (0 until n).map { (0 until n).map { (rnd.nextInt(10) - 5).toDouble() }.toDoubleArray() }.toTypedArray()
if (abs(det(a)) > 1e-6) {
val b = (0 until n).map { (rnd.nextInt(10) - 5).toDouble() }.toDoubleArray()
val x = gauss(a, b)
for (i in a.indices) {
val y = a[i].zip(x).sumOf { it.first * it.second }
if (abs(b[i] - y) > 1e-9)
throw RuntimeException()
}
}
}
}
| 97 | Java | 561 | 1,806 | 405552617ba1cd4a74010da38470d44f1c2e4ae3 | 1,323 | codelibrary | The Unlicense |
src/Day07.kt | RickShaa | 572,623,247 | false | {"Kotlin": 34294} | import java.util.*
fun main() {
val fileName = "day07.txt"
val testFileName = "day07_test.txt"
val input = FileUtil.getListOfLines(fileName);
val rootDirectory = Directory("/", null)
var currentDirectory = rootDirectory
fun String.toChar(): Char {
return this.toCharArray()[0]
}
fun getActionType(line:String): ActionType {
return when(line.first()){
"$".toChar() -> ActionType.COMMAND
"d".toChar() -> ActionType.DIRECTORY
else -> {
ActionType.FILE
}
}
}
fun changeDir(id:String): Directory {
return currentDirectory.directories.find { it.id == id }!!
}
fun executeCommand(prompt:String){
val splitPrompt = prompt.split(" ")
if(splitPrompt.size == 3){
val moveTo = splitPrompt[2]
if(moveTo != "/" && moveTo != ".."){
currentDirectory = changeDir(moveTo)
}else if(moveTo == ".."){
currentDirectory = currentDirectory.parentDir!!
}
}
}
fun storeDirectory(prompt:String){
val (_, dirId) = prompt.split(" ")
currentDirectory.directories.add(Directory(dirId, currentDirectory))
}
fun storeFile(prompt:String){
val (size, fileId) = prompt.split(" ")
currentDirectory.files.add(File(fileId,size.toInt()))
}
fun String.performAction(){
when(getActionType(this)){
ActionType.COMMAND -> executeCommand(this)
ActionType.FILE -> storeFile(this)
ActionType.DIRECTORY -> storeDirectory(this)
}
}
input.forEach { it.performAction()}
var sizes = mutableListOf<Int>()
fun getSizes(node:Directory) {
val dirSize = node.getDirectorySize()
if(dirSize <= 100000){
sizes.add(dirSize)
sizes.add(node.directories.sumOf { it.getDirectorySize() })
}else{
println("${node.id} directory is in too large")
if(node.directories.size > 0){
node.directories.forEach { getSizes(it) }
}
}
}
getSizes(rootDirectory)
println(sizes.sum())
//PART 2
val FILE_SYSTEM_SPACE = 70000000
val REQUIRED_SPACE = 30000000
val usedSpace = rootDirectory.getDirectorySize()
val availableSpace = FILE_SYSTEM_SPACE - usedSpace
val missingSpace = REQUIRED_SPACE - availableSpace
var potentialDirsForDeletion = mutableListOf<Int>()
fun findDirectoryForDeletion(node:Directory){
val dirSize = node.getDirectorySize()
if(dirSize >= missingSpace){
potentialDirsForDeletion.add(dirSize)
if(node.directories.size > 0){
node.directories.forEach { findDirectoryForDeletion(it) }
}
}
}
findDirectoryForDeletion(rootDirectory)
println(potentialDirsForDeletion.minOf { it })
}
enum class ActionType {
FILE,
DIRECTORY,
COMMAND
}
class Directory(val id:String,
val parentDir:Directory?,
val files:MutableList<File> = mutableListOf(),
val directories:MutableList<Directory> = mutableListOf())
{
fun getDirectorySize(): Int {
return files.sumOf { it.size } + getChildDirectorySize()
}
private fun getChildDirectorySize():Int {
if(directories.size > 0){
return directories.sumOf { directory: Directory -> directory.getDirectorySize() }
}
return 0
}
}
class File(val id:String, val size:Int) | 0 | Kotlin | 0 | 1 | 76257b971649e656c1be6436f8cb70b80d5c992b | 3,569 | aoc | Apache License 2.0 |
src/Day13.kt | wlghdu97 | 573,333,153 | false | {"Kotlin": 50633} | import kotlin.math.max
sealed class Packet : Comparable<Packet> {
data class Integer(val value: Int) : Packet()
data class PacketList(val value: List<Packet>) : Packet()
override fun compareTo(other: Packet): Int {
when {
(this is Integer && other is Integer) -> {
return this.value.compareTo(other.value)
}
(this is PacketList && other is PacketList) -> {
val max = max(this.value.size, other.value.size)
for (index in 0 until max) {
val first = this.value.getOrNull(index)
val second = other.value.getOrNull(index)
when {
(first != null && second != null) -> {
val comp = first.compareTo(second)
if (comp != 0) {
return comp
}
}
(first == null) -> {
return -1
}
else -> {
return 1
}
}
}
return 0
}
(this is Integer) -> {
return PacketList(listOf(this)).compareTo(other)
}
(other is Integer) -> {
return this.compareTo(PacketList(listOf(other)))
}
else -> {
throw IllegalStateException()
}
}
}
}
private fun parsePackets(input: List<String>): List<Pair<Packet, Packet>> {
val packets = arrayListOf<Pair<Packet, Packet>>()
val iterator = input.iterator()
while (iterator.hasNext()) {
val line = iterator.next()
if (line.isNotBlank()) {
val first = line.toPacket()
val second = iterator.next().toPacket()
packets.add(first to second)
}
}
return packets
}
private fun String.toPacket(): Packet {
return when {
(this.toIntOrNull() != null) -> {
Packet.Integer(this.toInt())
}
(this.startsWith("[") && this.endsWith("]")) -> {
val arrayInside = this.substring(1, this.length - 1)
if (arrayInside.isBlank()) {
Packet.PacketList(emptyList())
} else {
val packetList = arrayListOf<Packet>()
var remaining = arrayInside
while (remaining.isNotBlank()) {
val first = remaining.first()
when {
(first == ',') -> {
remaining = remaining.drop(1)
}
(first.isDigit()) -> {
val element = remaining.substringBefore(',')
packetList.add(Packet.Integer(element.toInt()))
remaining = remaining.drop(element.length)
}
(first == '[') -> {
val element = remaining.substringOuterBracket()
packetList.add(element.toPacket())
remaining = remaining.drop(element.length)
}
else -> {
throw IllegalArgumentException()
}
}
}
Packet.PacketList(packetList)
}
}
else -> {
throw IllegalArgumentException()
}
}
}
// assume it is well-formed
private fun String.substringOuterBracket(): String {
require(this.startsWith('['))
var leftBrackets = 0
var rightBrackets = 0
val iterator = this.iterator()
var acc = ""
while (iterator.hasNext()) {
val char = iterator.nextChar().apply {
acc += this
}
if (char == '[') {
leftBrackets += 1
} else if (char == ']') {
rightBrackets += 1
if (leftBrackets == rightBrackets) {
return acc
}
}
}
return this
}
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
parsePackets(input).forEachIndexed { index, (a, b) ->
if (a < b) {
sum += (index + 1)
}
}
return sum
}
fun part2(input: List<String>): Int {
val dividerPacketA = Packet.PacketList(listOf(Packet.PacketList(listOf(Packet.Integer(2)))))
val dividerPacketB = Packet.PacketList(listOf(Packet.PacketList(listOf(Packet.Integer(6)))))
val packets = ArrayList(parsePackets(input).flatMap { it.toList() }).apply {
add(dividerPacketA)
add(dividerPacketB)
}
val sorted = packets.sorted()
return ((sorted.indexOf(dividerPacketA) + 1) * (sorted.indexOf(dividerPacketB) + 1))
}
val testInput = readInput("Day13-Test01")
val input = readInput("Day13")
println(part1(testInput))
println(part1(input))
println(part2(testInput))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2b95aaaa9075986fa5023d1bf0331db23cf2822b | 5,213 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/Day9.kt | broersma | 574,686,709 | false | {"Kotlin": 20754} | package days
import kotlin.math.absoluteValue
import kotlin.math.sign
class Day9 : Day(9) {
private fun move(tail: Pair<Int, Int>, head: Pair<Int, Int>): Pair<Int, Int> {
val dx = head.first - tail.first
val dy = head.second - tail.second
if (dx.absoluteValue > 1 || dy.absoluteValue > 1) {
return ((tail.first + dx.sign) to (tail.second + dy.sign))
}
return tail
}
override fun partOne(): Any {
val motions =
inputList.map {
it.split(" ").let {
val step =
when (it[0]) {
"U" -> (0 to -1)
"D" -> (0 to +1)
"L" -> (-1 to 0)
"R" -> (+1 to 0)
else -> error("error")
}
step to it[1].toInt()
}
}
var visited: MutableSet<Pair<Int, Int>> = mutableSetOf<Pair<Int, Int>>()
var head = 0 to 0
var tail = 0 to 0
motions.forEach {
var (dir, amount) = it
repeat(amount) {
head = ((head.first + dir.first) to (head.second + dir.second))
tail = move(tail, head)
visited.add(tail)
}
}
return visited.size
}
override fun partTwo(): Any {
val motions =
inputList.map {
it.split(" ").let {
val step =
when (it[0]) {
"U" -> (0 to -1)
"D" -> (0 to +1)
"L" -> (-1 to 0)
"R" -> (+1 to 0)
else -> error("error")
}
step to it[1].toInt()
}
}
var visited: MutableSet<Pair<Int, Int>> = mutableSetOf<Pair<Int, Int>>()
var rope = Array<Pair<Int, Int>>(10) { 0 to 0 }
motions.forEach {
var (dir, amount) = it
repeat(amount) {
rope[0] = ((rope[0].first + dir.first) to (rope[0].second + dir.second))
for (i in 1..9) {
rope[i] = move(rope[i], rope[i - 1])
}
visited.add(rope[9])
}
}
return visited.size
}
}
| 0 | Kotlin | 0 | 0 | cd3f87e89f7518eac07dafaaeb0f6adf3ecb44f5 | 2,604 | advent-of-code-2022-kotlin | Creative Commons Zero v1.0 Universal |
advent-of-code-2022/src/main/kotlin/year_2022/Day04.kt | rudii1410 | 575,662,325 | false | {"Kotlin": 37749} | package year_2022
import util.Runner
fun main() {
fun Int.inRange(range: List<Int>): Boolean = this in range[0]..range[1]
fun List<Int>.withinRange(other: List<Int>): Boolean = get(0).inRange(other) && get(1).inRange(other)
fun List<Int>.isOverlapping(other: List<Int>): Boolean =
get(0).inRange(other) || get(1).inRange(other) || withinRange(other)
fun String.split(): List<List<Int>> = this.split(",").map { s ->
s.split("-").map { it.toInt() }
}
/* Part 1 */
fun part1(input: List<String>): Int {
return input.map { p ->
p.split().let {
return@map if (it[0].withinRange(it[1]) || it[1].withinRange(it[0])) 1 else 0
}
}.sum()
}
Runner.run(::part1, 2)
/* Part 2 */
fun part2(input: List<String>): Int {
return input.map { p ->
p.split().let {
return@map if (it[0].isOverlapping(it[1]) || it[1].isOverlapping(it[0])) 1 else 0
}
}.sum()
}
Runner.run(::part2, 4)
}
| 1 | Kotlin | 0 | 0 | ab63e6cd53746e68713ddfffd65dd25408d5d488 | 1,048 | advent-of-code | Apache License 2.0 |
kotlin/graphs/matchings/MaxGeneralMatchingRandomized.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.matchings
import java.util.Random
object MaxGeneralMatchingRandomized {
const val MOD = 29989
fun pow(a: Int, b: Int): Int {
var a = a
var b = b
var res = 1
while (b > 0) {
if (b and 1 != 0) res = res * a % MOD
a = a * a % MOD
b = b shr 1
}
return res
}
fun rank(a: Array<IntArray>): Int {
var r = 0
val n = a.size
for (j in 0 until n) {
var k: Int
k = r
while (k < n && a[k][j] == 0) {
k++
}
if (k == n) continue
val t = a[r]
a[r] = a[k]
a[k] = t
val inv = pow(a[r][j], MOD - 2)
for (i in j until n) a[r][i] = a[r][i] * inv % MOD
for (u in r + 1 until n) for (v in j + 1 until n) a[u][v] = (a[u][v] - a[r][v] * a[u][j] % MOD + MOD) % MOD
++r
}
return r
}
fun maxMatching(d: Array<BooleanArray>): Int {
val n = d.size
val a = Array(n) { IntArray(n) }
val rnd = Random(1)
for (i in 0 until n) {
for (j in 0 until i) {
if (d[i][j]) {
a[i][j] = rnd.nextInt(MOD - 1) + 1
a[j][i] = MOD - a[i][j]
}
}
}
return rank(a) / 2
}
// Usage example
fun main(args: Array<String?>?) {
val res = maxMatching(arrayOf(booleanArrayOf(false, true), booleanArrayOf(true, false)))
System.out.println(1 == res)
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,595 | codelibrary | The Unlicense |
src/main/java/challenges/cracking_coding_interview/trees_graphs/first_common_ancestor/QuestionE.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.trees_graphs.first_common_ancestor
import challenges.util.TreeNode
/**
* Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree.
* Avoid storing additional nodes in a data structure.
* NOTE: This is not necessarily a binary search tree.
*/
object QuestionE {
class Result(n: TreeNode?, isAnc: Boolean) {
var node: TreeNode?
var isAncestor: Boolean
init {
node = n
isAncestor = isAnc
}
}
private fun commonAncestorHelper(root: TreeNode?, p: TreeNode, q: TreeNode): Result {
if (root == null) {
return Result(null, false)
}
if (root == p && root == q) {
return Result(root, true)
}
val rx = commonAncestorHelper(root.left, p, q)
if (rx.isAncestor) { // Found common ancestor
return rx
}
val ry = commonAncestorHelper(root.right, p, q)
if (ry.isAncestor) { // Found common ancestor
return ry
}
return if (rx.node != null && ry.node != null) {
Result(root, true) // This is the common ancestor
} else if (root == p || root == q) {
/* If were currently at p or q, and we also found one of those
* nodes in a subtree, then this is truly an ancestor and the
* flag should be true. */
val isAncestor = rx.node != null || ry.node != null
Result(root, isAncestor)
} else {
Result(if (rx.node != null) rx.node else ry.node, false)
}
}
fun commonAncestor(root: TreeNode?, p: TreeNode, q: TreeNode): TreeNode? {
val r = commonAncestorHelper(root, p, q)
return if (r.isAncestor) {
r.node
} else null
}
@JvmStatic
fun main(args: Array<String>) {
val array = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val root: TreeNode = TreeNode.createMinimalBST(array) ?: return
val n3: TreeNode = root.find(10)!!
val n7: TreeNode = root.find(6)!!
val ancestor: TreeNode? = commonAncestor(root, n3, n7)
if (ancestor != null) {
println(ancestor.data)
} else {
println("null")
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,322 | CodingChallenges | Apache License 2.0 |
4/a.kt | DarkoKukovec | 159,875,185 | false | {"JavaScript": 38238, "Kotlin": 9620} | import java.io.File;
data class MostAsleep(val time: Int, val id: String)
fun main4A() {
var lastGuard: String = "";
var guards: MutableMap<String, MutableMap<Int, Int>> = mutableMapOf();
File("input.txt")
.readText(Charsets.UTF_8)
.split("\n")
.sorted()
.map({ line: String -> run {
var matchResult = Regex("\\s([0-9]+):([0-9]+)").find(line);
var match = matchResult?.groupValues;
var time: Int = 0;
if ((match?.getOrNull(1)?.toIntOrNull() ?: 0) == 0) {
time = match?.getOrNull(2)?.toIntOrNull() ?: 0;
}
var action: Int = 0;
if (line.indexOf("begins shift") != -1) {
lastGuard = Regex("Guard #([0-9]+)").find(line)?.groupValues?.getOrNull(1) ?: "";
} else if (line.indexOf("falls asleep") != -1) {
action = 1;
} else if (line.indexOf("wakes up") != -1) {
action = -1;
}
var guard = guards.getOrPut(lastGuard) { mutableMapOf() }
for (i in time until 60) {
guard.set(i, guard.getOrDefault(i, 0) + action);
}
}});
var mostAsleep = MostAsleep(0, "");
guards.keys.forEach({ id -> run {
var timetable = guards.getOrDefault(id, mutableMapOf()).toList().map { it.component2() };
var time = timetable.reduce { sum: Int, value: Int -> sum + value };
if (time > mostAsleep.time) {
mostAsleep = MostAsleep(time, id);
}
}});
var timetable = guards.getOrDefault(mostAsleep.id, mutableMapOf()).toList().map { it.component2() };
var maxAsleepTimes = timetable.max() ?: 0;
var mostAsleepTime = timetable.indexOf(maxAsleepTimes);
println(mostAsleep.id.toInt() * mostAsleepTime);
}
| 0 | JavaScript | 0 | 0 | 58a46dcb9c3e493f91d773ccc0440db9bd3b24b5 | 1,674 | adventofcode2018 | MIT License |
kotlin/src/main/kotlin/adventofcode/day7/Day7_1.kt | thelastnode | 160,586,229 | false | null | package adventofcode.day7
import java.io.File
data class Input(val step: String, val dependency: String)
val LINE_REGEX = Regex("Step (\\w+) must be finished before step (\\w+) can begin")
fun parse(line: String): Input {
val match = LINE_REGEX.find(line)
val (_, dependency, step) = match!!.groupValues
return Input(step = step, dependency = dependency)
}
fun process(inputs: List<Input>): String {
val steps = inputs.flatMap { listOf(it.dependency, it.step) }.distinct().toMutableSet()
val dependenciesByStep = inputs
.groupBy { it.step }
.mapValues { it.value.map { input -> input.dependency }.toMutableSet() }
.toMutableMap()
val ordering = mutableListOf<String>()
while (steps.isNotEmpty()) {
val nextStep = steps.filter { step -> (step !in dependenciesByStep) || dependenciesByStep[step]!!.isEmpty() }
.sorted()
.first()
steps.remove(nextStep)
ordering.add(nextStep)
dependenciesByStep.forEach { (_, dependencies) -> dependencies.remove(nextStep) }
}
return ordering.joinToString("")
}
fun main(args: Array<String>) {
val lines = File("./day7-input").readText().split("\n")
val inputs = lines.map { parse(it) }
println(process(inputs))
}
| 0 | Kotlin | 0 | 0 | 8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa | 1,301 | adventofcode | MIT License |
src/main/kotlin/day22/Day22ModeMaze.kt | Zordid | 160,908,640 | false | null | package day22
import shared.*
enum class Type(val c: Char) {
Rock('.'), Wet('='), Narrow('|'), Solid('#');
override fun toString() = c.toString()
}
enum class Equipment { Neither, Torch, ClimbingGear }
data class State(val equipment: Equipment, val c: Coordinate)
class CaveMap(puzzle: List<String>) {
private val depth = puzzle[0].extractAllInts().single()
val origin = 0 toY 0
val target = puzzle[1].extractCoordinate()
var totalCalc = 0L
private val erosionLevelCache = mutableMapOf<Coordinate, Int>()
private fun Coordinate.geologyIndex(): Int {
totalCalc++
if (this == origin || this == target) return 0
if (y == 0)
return x * 16807
if (x == 0)
return y * 48271
val west = this.transposeBy(-1 to 0)
val north = this.transposeBy(0 to -1)
return west.erosionLevel() * north.erosionLevel()
}
private fun Coordinate.erosionLevel() =
erosionLevelCache.getOrPut(this) { (geologyIndex() + depth) % 20183 }
private fun Int.type() = when (this % 3) {
0 -> Type.Rock
1 -> Type.Wet
2 -> Type.Narrow
else -> throw IllegalArgumentException(this.toString())
}
fun draw(marker: Coordinate? = null, path: Collection<Coordinate> = emptySet()) {
val areaOfInterest = erosionLevelCache.keys.enclosingArea()
(areaOfInterest + 1).forEach { c ->
val cachedValue = erosionLevelCache[c]?.type()?.toString() ?: "?"
if (c.x == -1) println()
when (c) {
marker -> print('X')
origin -> print('M')
target -> print('T')
else -> print(if (path.contains(c)) 'O' else cachedValue)
}
}
println()
}
fun totalRiskLevel(): Int {
return Area.from(origin, target).sumOf { this[it].ordinal }
}
operator fun get(c: Coordinate): Type {
if (c.x < 0 || c.y < 0) return Type.Solid
return c.erosionLevel().type()
}
}
class CaveNavigator(puzzle: List<String>) {
val map = CaveMap(puzzle)
private val validityMap = mapOf(
Type.Rock to setOf(Equipment.ClimbingGear, Equipment.Torch),
Type.Wet to setOf(Equipment.ClimbingGear, Equipment.Neither),
Type.Narrow to setOf(Equipment.Torch, Equipment.Neither),
Type.Solid to emptySet()
)
private fun State.possibleMoves(): Set<State> {
val result = mutableSetOf<State>()
val typeHere = map[c]
val validHere = validityMap[typeHere]!!
for (neighbor in c.manhattanNeighbors) {
val neighborType = map[neighbor]
if (neighborType != Type.Solid) {
val neighborValid = validityMap[neighborType]!!
val validBoth = validHere intersect neighborValid
result.addAll(validBoth.map { State(it, neighbor) })
}
}
return result
}
private fun neighbors(s: State) = s.possibleMoves()
private fun cost(s: State, d: State) = if (s.equipment != d.equipment) 8 else 1
private fun costLowerBounds(s: State, d: State) = s.c manhattanDistanceTo d.c
private val aStar = AStar(::neighbors, ::cost, ::costLowerBounds)
private val originState = State(Equipment.Torch, map.origin)
private val targetState = State(Equipment.Torch, map.target)
fun minimumTravelLengthAndPath(): Pair<Int, Collection<State>> {
val (dist, prev) = aStar.search(originState, targetState)
val path = mutableListOf<State>()
var current: State? = targetState
while (current != null) {
path.add(current)
current = prev[current]
}
return dist[targetState]!! to path.reversed()
}
}
fun part1(puzzle: List<String>): Any {
val m = CaveNavigator(puzzle)
return m.map.totalRiskLevel()
}
fun part2(puzzle: List<String>, verbose: Boolean = false): Any {
val m = CaveNavigator(puzzle)
val (length, path) = m.minimumTravelLengthAndPath()
if (verbose) {
println("evaluated ${m.map.totalCalc} cells")
m.map.draw(path = path.map { it.c })
println(" needed $length minutes. ")
val cost = path.switches() * 7 + path.size - 1
println("${path.switches()} * 7 + ${path.size - 1} = $cost")
}
return length
}
fun Collection<State>.switches() = windowed(2, 1).count { (a, b) -> a.equipment != b.equipment }
fun main() {
val puzzle = readPuzzle(22)
measureRuntime {
println(part1(puzzle))
println(part2(puzzle))
}
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 4,610 | adventofcode-kotlin-2018 | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[746]使用最小花费爬楼梯.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //数组的每个索引作为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。
//
// 每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
//
// 您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
//
// 示例 1:
//
// 输入: cost = [10, 15, 20]
//输出: 15
//解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
//
//
// 示例 2:
//
// 输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
//输出: 6
//解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
//
//
// 注意:
//
//
// cost 的长度将会在 [2, 1000]。
// 每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。
//
// Related Topics 数组 动态规划
// 👍 479 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun minCostClimbingStairs(cost: IntArray): Int {
//贪心 动态规划 使用原数组 记录每步花费
//时间复杂度 O(n)
// 0 1 位置依据题意可以看做相等
val len = cost.size
for (i in 2 until len ){
cost[i] += cost[i - 1].coerceAtMost(cost[i - 2])
}
return Math.min(cost[len-2],cost[len-1])
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,521 | MyLeetCode | Apache License 2.0 |
src/y2022/day05.kt | sapuglha | 573,238,440 | false | {"Kotlin": 33695} | package y2022
import readFileAsLines
fun main() {
/*
[M] [N] [Z]
[F] [R] [Z] [C] [C]
[C] [V] [L] [N] [G] [V]
[W] [L] [T] [H] [V] [F] [H]
[T] [T] [W] [F] [B] [P] [J] [L]
[D] [L] [H] [J] [C] [G] [S] [R] [M]
[L] [B] [C] [P] [S] [D] [M] [Q] [P]
[B] [N] [J] [S] [Z] [W] [F] [W] [R]
1 2 3 4 5 6 7 8 9
*/
fun initializeStack(): List<ArrayDeque<String>> = listOf(
ArrayDeque<String>().apply { addAll(listOf("B", "L", "D", "T", "W", "C", "F", "M")) },
ArrayDeque<String>().apply { addAll(listOf("N", "B", "L")) },
ArrayDeque<String>().apply { addAll(listOf("J", "C", "H", "T", "L", "V")) },
ArrayDeque<String>().apply { addAll(listOf("S", "P", "J", "W")) },
ArrayDeque<String>().apply { addAll(listOf("Z", "S", "C", "F", "T", "L", "R")) },
ArrayDeque<String>().apply { addAll(listOf("W", "D", "G", "B", "H", "N", "Z")) },
ArrayDeque<String>().apply { addAll(listOf("F", "M", "S", "P", "V", "G", "C", "N")) },
ArrayDeque<String>().apply { addAll(listOf("W", "Q", "R", "J", "F", "V", "C", "Z")) },
ArrayDeque<String>().apply { addAll(listOf("R", "P", "M", "L", "H")) },
)
data class Instructions(
val quantity: Int,
val origin: Int,
val destination: Int,
)
fun getInstructions(input: String): Instructions =
Instructions(
quantity = input.substringAfter("y2022.move ").substringBefore(" from ").toInt(),
origin = input.substringAfter("from ").substringBefore(" to").toInt(),
destination = input.substringAfter("to ").toInt(),
)
fun part1(input: List<String>): String = initializeStack()
.apply {
input.forEach { line ->
val instructions = getInstructions(line)
repeat(instructions.quantity) {
this[instructions.destination - 1].add(
this[instructions.origin - 1].removeLast()
)
}
}
}
.joinToString(separator = "") {
it.last()
}
fun part2(input: List<String>): String = initializeStack()
.apply {
input.forEach { line ->
val instructions = getInstructions(line)
val tempDeque: ArrayDeque<String> = ArrayDeque()
repeat(instructions.quantity) {
tempDeque.add(
this[instructions.origin - 1].removeLast()
)
}
this[instructions.destination - 1].addAll(tempDeque.reversed())
}
}
.joinToString(separator = "") {
it.last()
}
"y2022/data/day05".readFileAsLines().let { input ->
println("part1: ${part1(input)}")
println("part2: ${part2(input)}")
}
}
| 0 | Kotlin | 0 | 0 | 82a96ccc8dcf38ae4974e6726e27ddcc164e4b54 | 2,945 | adventOfCode2022 | Apache License 2.0 |
src/Day08.kt | juliantoledo | 570,579,626 | false | {"Kotlin": 34375} | fun main() {
fun isVisible(matrix: MutableList<Array<Int>>, x: Int, y: Int): Boolean {
val value = matrix[x][y]
if ( y == 0 || x == 0 || y == matrix[x].lastIndex || x == matrix.lastIndex) {
return true
} else {
var left = true
var right = true
var up = true
var down = true
//left
for (i in y-1 downTo 0) {
if (value <= matrix[x][i]) {left = false; break}
}
// right
for (i in y+1 .. matrix[x].lastIndex) {
if (value <= matrix[x][i]) {right = false; break}
}
// up
for (j in x-1 downTo 0) {
if (value <= matrix[j][y]) {up = false; break}
}
// down
for (j in x+1 .. matrix.lastIndex) {
if (value <= matrix[j][y]) {down = false; break}
}
return left || right || up || down
}
}
fun isVisibleDis(matrix: MutableList<Array<Int>>, x: Int, y: Int): Int {
val value = matrix[x][y]
if ( y == 0 || x == 0 || y == matrix[x].lastIndex || x == matrix.lastIndex) {
return 0
} else {
var left = 1
var right = 1
var up = 1
var down = 1
//left
for (i in y-1 downTo 1) {
if (value <= matrix[x][i]) break else left++
}
// right
for (i in y+1 until matrix[x].lastIndex) {
if (value <= matrix[x][i]) break else right++
}
// up
for (j in x-1 downTo 1) {
if (value <= matrix[j][y]) break else up++
}
// down
for (j in x+1 until matrix.lastIndex) {
if (value <= matrix[j][y]) break else down++
}
return left * right * up * down
}
}
fun findVisible(matrix: MutableList<Array<Int>>): List<Int> {
var visiblePoints = mutableListOf<Int>()
for((x, row) in matrix.withIndex()) {
for((y, value) in row.withIndex()) {
if (isVisible(matrix, x, y)) visiblePoints.add(value)
}
}
return visiblePoints
}
fun findVisibleDis(matrix: MutableList<Array<Int>>): List<Int> {
var visiblePoints = mutableListOf<Int>()
for((x, row) in matrix.withIndex()) {
for((y, value) in row.withIndex()) {
visiblePoints.add(isVisibleDis(matrix, x, y))
}
}
return visiblePoints
}
fun part1(input: List<String>): Int {
var matrix = mutableListOf<Array<Int>>()
for( i in input) {
val row = i.map { it.digitToInt() }.toTypedArray()
matrix.add(row)
}
return findVisible(matrix).size
}
fun part2(input: List<String>): Int {
var matrix = mutableListOf<Array<Int>>()
for( i in input) {
val row = i.map { it.digitToInt() }.toTypedArray()
matrix.add(row)
}
return findVisibleDis(matrix).maxOf { it }
}
var input = readInput("Day08_test")
var x = part1(input)
println(x)
var y = part2(input)
println(y)
input = readInput("Day08_input")
x = part1(input)
println(x)
y = part2(input)
println(y)
} | 0 | Kotlin | 0 | 0 | 0b9af1c79b4ef14c64e9a949508af53358335f43 | 3,401 | advent-of-code-kotlin-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.