path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/Day2.kt | aisanu | 112,855,402 | false | {"Kotlin": 15773} | object Day2 {
fun part1Solution(input: String): Long = splitRows(input)
.map { splitColumns(it) }
.map { minMaxDiff(it) }
.sum()
fun part2Solution(input: String): Long = splitRows(input)
.map { splitColumns(it) }
.map { wholeDivider(it) }
.sum()
fun minMaxDiff(input: List<Long>): Long {
val min = requireNotNull(input.min()) { "Cannot found min" }
val max = requireNotNull(input.max()) { "Cannot found max" }
return Math.abs(max - min)
}
fun wholeDivider(input: List<Long>): Long = input.mapIndexed { index, value ->
val result = input.drop(index + 1).find { it % value == 0L || value % it == 0L }
result?.let { Math.max(result, value) / Math.min(result, value) }
}.filterNotNull().first()
fun splitRows(input: String): List<String> = input.split("\n").filter { it.isNotBlank() }
fun splitColumns(input: String): List<Long> = input.split(Regex("[ \t]")).map { it.toLong() }
} | 0 | Kotlin | 0 | 0 | 25dfe70e2bbb9b83a6ece694648a9271d1e21ddd | 1,024 | advent-of-code | The Unlicense |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D7.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
class Y2020D7 : BaseSolver() {
override val year = 2020
override val day = 7
override fun part1(): Int = parseInput().let { rules ->
rules.keys.count { color -> color.canContain(rules, "shiny gold") }
}
override fun part2(): Int = parseInput().bagCount("shiny gold")
private fun String.canContain(rules: Map<String, List<Pair<Int, String>>>, bagColor: String): Boolean {
val insideColors = (rules[this] ?: error("Color `$this` missing from rules")).map { it.second }
if (bagColor in insideColors) {
return true
}
return insideColors.any { color -> color.canContain(rules, bagColor) }
}
private fun Map<String, List<Pair<Int, String>>>.bagCount(containerColor: String): Int =
(this[containerColor] ?: error("Color `$containerColor` missing from rules")).sumOf { (count, color) ->
count * (bagCount(color) + 1)
}
private fun parseInput(): Map<String, List<Pair<Int, String>>> = readInput {
readLines().associate { line ->
val parts = line.split("contain")
val color = parts[0].dropLast(6)
if (parts[1].trim().startsWith("no ")) {
Pair(color, emptyList())
} else {
val inside = parts[1].replace(".", "").split(",").map { p ->
val parts2 = p.trim().split(" ")
Pair(
parts2[0].toInt(),
parts2.slice(1..2).joinToString(" ")
)
}
Pair(color, inside)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 1,710 | advent-of-code | MIT License |
leetcode2/src/leetcode/minimum-distance-between-bst-nodes.kt | hewking | 68,515,222 | false | null | package leetcode
import leetcode.structure.TreeNode
/**
* 783. 二叉搜索树结点最小距离
* https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
* @program: leetcode
* @description: ${description}
* @author: hewking
* @create: 2019-10-23 09:18
* 给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。
示例:
输入: root = [4,2,6,1,3,null,null]
输出: 1
解释:
注意,root是树结点对象(TreeNode object),而不是数组。
给定的树 [4,2,6,1,3,null,null] 可表示为下图:
4
/ \
2 6
/ \
1 3
最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。
注意:
二叉树的大小范围在 2 到 100。
二叉树总是有效的,每个节点的值都是整数,且不重复。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
object MinimumDIstanceBetweenBstNodes {
class Solution {
/**
* 思路:
* 根据二叉搜索树的性质,还有题设。相邻父子节点之间的值符合
* 题设所要求的的值。然后所有相邻值取最小值。
* 采用递归:
* 1. 基线条件:子节点为null
* 2. 递归条件:当前最小值和 父节点和两个子节点的差值,然后取最小
*
* 3. 二叉搜索树中序遍历 所有节点值从小到大
*/
fun minDiffInBST(root: TreeNode?): Int {
minDiff(root)
return minDiffValue
}
private var minDiffValue: Int = Int.MAX_VALUE
private var preNode: TreeNode? = null
fun minDiff(root: TreeNode?) {
root?:return
minDiff(root?.left)
var minVal = minDiffValue
if (preNode != null) {
minVal = root?.`val` - preNode!!.`val`
}
preNode = root
minDiffValue = Math.min(minDiffValue,minVal)
minDiff(root?.right)
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,161 | leetcode | MIT License |
src/main/kotlin/us/jwf/aoc2015/Day19Medicine.kt | jasonwyatt | 318,073,137 | false | null | package us.jwf.aoc2015
import java.io.Reader
import java.util.LinkedList
import java.util.PriorityQueue
import us.jwf.aoc.Day
/**
* AoC 2015 - Day 19
*/
class Day19Medicine : Day<Int, Int> {
override suspend fun executePart1(input: Reader): Int {
val rules = mutableMapOf<Atom, List<Rule>>()
var doneWithRules = false
var molecule = emptyList<Atom>()
input.readLines().forEach { line ->
if (line.isBlank() || line.isEmpty()) {
doneWithRules = true
} else if (doneWithRules) {
molecule = Atom.parseMolecule(line)
} else {
Rule.parse(line).also {
rules[it.input] = (rules[it.input] ?: emptyList()) + it
}
}
}
val created = mutableSetOf<List<Atom>>()
molecule.forEachIndexed { i, atom ->
val left = if (i > 0) molecule.subList(0, i) else emptyList()
val right = if (i < molecule.size - 1) molecule.subList(i + 1, molecule.size) else emptyList()
val rulesToApply = rules[atom] ?: emptyList()
rulesToApply.forEach { rule ->
created += left + rule.output + right
}
}
return created.size
}
override suspend fun executePart2(input: Reader): Int {
// A* with LevenshteinDistance.
// Or: start from long string and try to find e by going backwards....
val atomsFromRules = mutableMapOf<Rule, Atom>()
var doneWithRules = false
var molecule = emptyList<Atom>()
input.readLines().forEach { line ->
if (line.isBlank() || line.isEmpty()) {
doneWithRules = true
} else if (doneWithRules) {
molecule = Atom.parseMolecule(line)
} else {
Rule.parse(line).also {
atomsFromRules[it] = it.input
}
}
}
val orderedRules = atomsFromRules.keys.sortedBy { -it.output.size }
val visited = mutableSetOf(molecule)
val queue =
PriorityQueue<Pair<List<Atom>, Int>> { a, b -> a.first.size compareTo b.first.size }
.apply { add(molecule to 0) }
while (queue.isNotEmpty()) {
val (currentMolecule, currentSteps) = queue.poll()
if (currentMolecule == listOf(Atom("e"))) return currentSteps
orderedRules.forEach { rule ->
currentMolecule.windowed(rule.output.size)
.withIndex()
.forEach inner@{ (i, window) ->
if (window != rule.output) return@inner
val left = if (i > 0) currentMolecule.subList(0, i) else emptyList()
val right = if (i < currentMolecule.size - rule.output.size) {
currentMolecule.subList(i + rule.output.size, currentMolecule.size)
} else emptyList()
val candidate = left + atomsFromRules[rule]!! + right
if (candidate !in visited && candidate.size <= currentMolecule.size) {
visited.add(candidate)
queue.add(candidate to currentSteps + 1)
}
if (candidate == listOf(Atom("e"))) return currentSteps + 1
}
}
}
return 0
}
data class Atom(val symbol: String) {
override fun toString(): String = symbol
companion object {
private val elementPattern = "[A-Z][a-z]?".toRegex()
fun parseMolecule(input: String): List<Atom> {
return elementPattern.findAll(input).map { Atom(it.value) }.toList()
}
}
}
data class Rule(val input: Atom, val output: List<Atom>) {
companion object {
fun parse(input: String): Rule {
val (lhs, rhs) = input.split(" => ")
return Rule(Atom(lhs), Atom.parseMolecule(rhs))
}
}
}
} | 0 | Kotlin | 0 | 0 | 0c92a62ba324aaa1f21d70b0f9f5d1a2c52e6868 | 3,554 | AdventOfCode-Kotlin | Apache License 2.0 |
src/Day08.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | import kotlin.math.max
import kotlin.math.min
class VisibilityUpdater(val field: Array<Array<Int>>, val visibility: Array<Array<Boolean>>, var max: Int) {
fun update(row: Int, column: Int) {
if (field[row][column] > max) {
max = field[row][column]
visibility[row][column] = true
}
}
}
fun main() {
fun buildField(input: List<String>) =
Array(input.size) { row -> Array(input[0].length) { column -> input[row][column].digitToInt() } }
fun part1(input: List<String>): Long {
val field: Array<Array<Int>> = buildField(input)
val visibility: Array<Array<Boolean>> = Array(input.size) { row ->
Array(input[0].length) { column -> row == 0 || row == input.size - 1 || column == 0 || column == input[0].length - 1 }
}
val visibilityUpdater = { max: Int -> VisibilityUpdater(field, visibility, max) }
// ----->
for (row in 1..field.size - 2) {
val updater = visibilityUpdater(field[row][0])
for (column in 1..field[0].size - 2) {
updater.update(row, column)
}
}
// <-----
for (row in 1..field.size - 2) {
val updater = visibilityUpdater(field[row][field[0].size - 1])
for (column in field[0].size - 2 downTo 1) {
updater.update(row, column)
}
}
// |
// |
// V
for (column in 1..field[0].size - 2) {
val updater = visibilityUpdater(field[0][column])
for (row in 1..field.size - 2) {
updater.update(row, column)
}
}
// /\
// |
// |
for (column in 1..field[0].size - 2) {
val updater = visibilityUpdater(field[field.size - 1][column])
for (row in field.size - 2 downTo 1) {
updater.update(row, column)
}
}
return visibility.sumOf { it.sumOf { point -> if (point) 1L else 0L } }
}
fun part2(input: List<String>): Int {
val field: Array<Array<Int>> = buildField(input)
val columns = field[0].size
val visibility: Array<Array<Int>> = Array(input.size) { row ->
Array(input[0].length) { column ->
if (row == 0 || row == field.size - 1 || column == 0 || column == columns - 1) 0 else 1
}
}
// ----->
for (row in field.indices) {
val visibilityVector = Array(10) { 0 }
visibilityVector[field[row][0]] = 0
for (column in 1 until columns) {
val height = field[row][column]
var closestBlock = 0
for (testHeight in height..9) {
closestBlock = max(closestBlock, visibilityVector[testHeight])
}
visibility[row][column] *= column - closestBlock
visibilityVector[height] = column
}
}
for (row in field.indices) {
val visibilityVector = Array(10) { columns - 1 }
visibilityVector[field[row][columns - 1]] = columns - 1
for (column in columns - 1 downTo 0) {
val height = field[row][column]
var closestBlock = columns - 1
for (testHeight in height..9) {
closestBlock = min(closestBlock, visibilityVector[testHeight])
}
visibility[row][column] *= closestBlock - column
visibilityVector[height] = column
}
}
// |
// |
// V
for (column in 0 until columns) {
val visibilityVector = Array(10) { 0 }
visibilityVector[field[0][column]] = 0
for (row in 1 until field.size) {
val height = field[row][column]
var closestBlock = 0
for (testHeight in height..9) {
closestBlock = max(closestBlock, visibilityVector[testHeight])
}
visibility[row][column] *= row - closestBlock
visibilityVector[height] = row
}
}
for (column in 0 until columns) {
val visibilityVector = Array(10) { field.size - 1 }
visibilityVector[field[field.size - 1][column]] = field.size - 1
for (row in field.size - 1 downTo 0) {
val height = field[row][column]
var closestBlock = field.size - 1
for (testHeight in height..9) {
closestBlock = min(closestBlock, visibilityVector[testHeight])
}
visibility[row][column] *= closestBlock - row
visibilityVector[height] = row
}
}
field.forEach { println(it.contentToString()) }
println()
println()
visibility.forEach { println(it.contentToString()) }
return visibility.maxOf { it.max() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21L)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
check(part1(input) == 1662L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 5,326 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/dmc/advent2022/Day01.kt | dorienmc | 576,916,728 | false | {"Kotlin": 86239} | // --- Day 1: Calorie Counting ---
package com.dmc.advent2022
class Day01 : Day<Int> {
override val index = 1
override fun part1(input: List<String>): Int {
val calories = determineCalories(input)
return calories.max()
}
override fun part2(input: List<String>): Int {
val calories = determineCalories(input)
val bestThree = calories.sortedDescending().take(3)
return bestThree.sum()
}
private fun determineCalories(input : List<String>): List<Int> {
val calories: MutableList<Int> = mutableListOf()
val currentElf: MutableList<Int> = mutableListOf()
for(line:String in input) {
if(line.isNotEmpty()) {
currentElf.add(line.toInt())
} else {
calories.add(currentElf.sum())
currentElf.clear()
}
}
calories.add(currentElf.sum())
return calories
}
}
fun main() {
val day = Day01()
// test if implementation meets criteria from the description, like:
val testInput = readInput(day.index, true)
check(day.part1(testInput) == 24000)
val input = readInput(day.index)
day.part1(input).println()
day.part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 207c47b47e743ec7849aea38ac6aab6c4a7d4e79 | 1,250 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/day11/Day11.kt | afTrolle | 572,960,379 | false | {"Kotlin": 33530} | package day11
import Day
import java.math.BigInteger
fun main() {
Day11("Day11").solve()
}
class Day11(input: String) : Day<List<Day11.Monkey>>(input) {
operator fun List<String>.component6(): String = get(5)
data class Monkey(
val name: Int,
val items: MutableList<BigInteger> = mutableListOf(),
val operation: (old: BigInteger) -> BigInteger,
val divisible: BigInteger,
val onTrue: Int,
val onFalse: Int,
var inspectedItems: Long = 0
)
fun String.getValue(old: BigInteger): BigInteger = when (this) {
"old" -> old
else -> this.toInt().toBigInteger()
}
fun String.getOperationBig(): (BigInteger, BigInteger) -> BigInteger = when (this) {
"+" -> BigInteger::plus
"-" -> BigInteger::minus
"/" -> BigInteger::div
"*" -> BigInteger::times
else -> error("unhandled op")
}
override fun parseInput(): List<Monkey> {
return inputByGroups.mapIndexed { index, (_, items, operation, test, ifTrue, ifFalse) ->
val (constOrVar, op, constOrVarSecond) = operation.trim().removePrefix("Operation: new = ").split(" ")
val opLambda: (old: BigInteger) -> BigInteger = { old ->
val a = constOrVar.getValue(old)
val b = constOrVarSecond.getValue(old)
op.getOperationBig().invoke(a, b)
}
val divisible = test.trim().removePrefix("Test: divisible by ").toInt()
val onTrue = ifTrue.trim().removePrefix("If true: throw to monkey ").toInt()
val onFalse = ifFalse.trim().removePrefix("If false: throw to monkey ").toInt()
Monkey(
index,
items = items.trim().removePrefix("Starting items: ").split(", ").map { it.toInt().toBigInteger() }
.toMutableList(),
operation = opLambda,
divisible = divisible.toBigInteger(),
onTrue = onTrue,
onFalse = onFalse
)
}
}
override fun part1(input: List<Monkey>): Any {
val three = BigInteger.valueOf(3)
repeat(20) {
input.forEach { monkey ->
repeat(monkey.items.size) {
val item = monkey.items.removeFirst()
val updatedItem = monkey.operation.invoke(item).div(three)
val nextMonkey = if (updatedItem.mod(monkey.divisible) == BigInteger.ZERO) {
monkey.onTrue
} else {
monkey.onFalse
}
monkey.inspectedItems += 1
input[nextMonkey].items.add(updatedItem)
}
}
}
val (a, b) = input.map { it.inspectedItems }.sortedDescending().take(2)
return a * b
}
override fun part2(input: List<Monkey>): Any? {
val worry = input.map { it.divisible }.reduce { acc, bigInteger ->
acc * bigInteger
}
repeat(10000) {
input.forEach { monkey ->
repeat(monkey.items.size) {
val item = monkey.items.removeFirst()
val updatedItem = monkey.operation.invoke(item).mod(worry)
val nextMonkey = if (updatedItem.mod(monkey.divisible) == BigInteger.ZERO) {
monkey.onTrue
} else {
monkey.onFalse
}
monkey.inspectedItems += 1
input[nextMonkey].items.add(updatedItem)
}
}
}
val (a, b) = input.map { it.inspectedItems }.sortedDescending().take(2)
return a * b
}
}
| 0 | Kotlin | 0 | 0 | 4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545 | 3,786 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day03/Code.kt | fcolasuonno | 317,324,330 | false | null | package day03
import day01.multiplyTogether
import isDebug
import java.io.File
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
data class Grid(val input: List<String>) {
operator fun get(xy: Pair<Int, Int>) =
input.getOrNull(xy.second)?.let { row -> row.getOrNull(xy.first % row.length) }
}
fun parse(input: List<String>) = Grid(input)
fun part1(input: Grid) {
val res = projectLine(delta = Pair(3, 1)).mapSequence { line -> input[line] }.count { it == '#' }
println("Part 1 = $res")
}
fun part2(input: Grid) {
val res = listOf(Pair(1, 1), Pair(3, 1), Pair(5, 1), Pair(7, 1), Pair(1, 2)).map { delta ->
projectLine(delta).mapSequence { line -> input[line] }.count { it == '#' }
}.multiplyTogether()
println("Part 2 = $res")
}
fun projectLine(delta: Pair<Int, Int>, start: Pair<Int, Int> = Pair(0, 0)) = generateSequence(start) { Pair(it.first + delta.first, it.second + delta.second) }
fun <T, V> Sequence<T>.mapSequence(function: (T) -> V?) = map(function).takeWhile { it != null }
| 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 1,266 | AOC2020 | MIT License |
src/test/kotlin/be/brammeerten/y2022/Day15Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2022
import be.brammeerten.C
import be.brammeerten.extractRegexGroupsI
import be.brammeerten.readFile
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day15Test {
@Test
fun `part 1a`() {
val readings = parseSensorReadings(readFile("2022/day15/exampleInput.txt"))
Assertions.assertEquals(26, solve(readings, 10))
}
@Test
fun `part 1b`() {
val readings = parseSensorReadings(readFile("2022/day15/input.txt"))
Assertions.assertEquals(26, solve(readings, 2000000)) // < 4876694
}
@Test
fun `part 2a`() {
val readings = parseSensorReadings(readFile("2022/day15/exampleInput.txt"))
Assertions.assertEquals(C(14, 11), solve2c(readings, C(0,0), C(20, 20)))
}
@Test
fun `part 2b`() {
val readings = parseSensorReadings(readFile("2022/day15/input.txt"))
val yes = readings.all { canHavePointOutOfReach(it, C(2911363, 2855041), C(2911363, 2855041)) }
Assertions.assertEquals(C(2911363, 2855041), solve2c(readings, C(0,0), C(4000000,4000000)))
val result: Long = 2911363L * 4000000L + 2855041L
println(yes.toString() + " " + result)
}
fun solve(readings: List<Reading>, row: Int): Int {
val beacons = readings.filter { it.beacon.y == row }.map { it.beacon.x }.toHashSet()
val add = hashSetOf<Int>()
readings
.filter { isInRange(it, row) }
.forEach { getBlockingCols(it, row, add) }
// return add.size // minus beacons
return (add - beacons).size // minus beacons
}
fun solve2(readings: List<Reading>, maxCo: Int): C {
val blocked = Array(maxCo) {Array(maxCo){false} }
readings
// .filter { isInArea(0, maxCo, it) }
.forEach { reading ->
if (reading.beacon.y in 0 until maxCo && reading.beacon.x in 0 until maxCo)
blocked[reading.beacon.y][reading.beacon.x] = true
for (xOff in -reading.range..reading.range) {
val x = reading.sensor.x + xOff
if (x !in 0 until maxCo) continue
val left = reading.range - abs(xOff)
for (yOff in -left..left) {
val y = reading.sensor.y + yOff
if (y in 0 until maxCo)
blocked[y][x] = true
}
}
}
// for (row in blocked) {
// for (cell in row) {
// print(if(cell) "X " else ". ")
// }
// println()
// }
for (y in blocked.indices) {
for (x in blocked[y].indices) {
if (!blocked[y][x]) return C(x, y)
}
}
throw IllegalStateException("All blcoked!")
}
fun solve2b(readings: List<Reading>, maxCo: Int): C {
val notBlocked = Array(maxCo) { listOf(0..maxCo) }
readings
// .filter { isInArea(0, maxCo, it) }
.forEach { reading ->
println("processing sensor ${reading.range}")
if (reading.beacon.y in 0 until maxCo && reading.beacon.x in 0 until maxCo)
notBlocked[reading.beacon.y] = notBlocked[reading.beacon.y].flatMap { it.split(reading.beacon.x..reading.beacon.x)}.filter { !it.isEmpty() }
for (xOff in 0..reading.range) {
println("$xOff / ${reading.range}")
val rangeX = max(reading.sensor.x - xOff, 0)..min(reading.sensor.x+xOff, maxCo)
if (rangeX.isEmpty()) continue
val left = reading.range - abs(xOff)
val range = max(reading.sensor.y-left, 0)..min(reading.sensor.y+left, maxCo-1)
for (y in range) {
notBlocked[y] = notBlocked[y].flatMap {it.split(rangeX) }.filter { !it.isEmpty() }
}
}
}
// for (y in 0 until maxCo) {
// val dinges = notBlocked[y].flatMap { s -> s.toList() }.sorted()
// for (x in 0 until maxCo) {
// if (dinges.find { it == x } != null)
// print(". ")
// else
// print("X ")
// }
// println()
// }
println("looking for unblocked")
for (y in notBlocked.indices) {
notBlocked[y].forEach {
return C(it.first, y)
}
}
throw IllegalStateException("All blcoked!")
}
fun solve2c(readings: List<Reading>, topLeft: C, bottomRight: C): C? {
val w = (bottomRight - topLeft).x+1
val h = (bottomRight - topLeft).y+1
if (w==1 && h==1) {
println("Solution: ${topLeft.x}, ${topLeft.y}")
return topLeft
}
// println("${w+1} x ${h+1}")
val diff = bottomRight - topLeft
val mid = topLeft + C(diff.x/2, diff.y/2)
val parts: Array<Pair<C, C>> = arrayOf(
topLeft to mid,
C(mid.x+1, topLeft.y) to C(bottomRight.x, mid.y),
C(topLeft.x, mid.y+1) to C(mid.x, bottomRight.y),
C(mid.x+1, mid.y+1) to bottomRight
)
val solution = parts
.filter { (start, end) -> start.x <= end.x && start.y <= end.y }
.filter { (start, end) -> readings.all { canHavePointOutOfReach(it, start, end) } }
.map { (start, end) -> solve2c(readings, start, end) }.filterNotNull()
if (solution.size > 1)
throw IllegalStateException("Multiple solutions")
return if (solution.size == 1) solution[0] else null
}
}
fun canHavePointOutOfReach(reading: Reading, start: C, end: C): Boolean {
val corners = arrayOf(
start, C(end.x, start.y), C(start.x, end.y), end)
return corners.map { distance(it, reading.sensor) }.max() > reading.range
}
fun isInArea(start: Int, end: Int, reading: Reading): Boolean {
val sensor = reading.sensor
return (sensor.x + reading.range >= start || sensor.x - reading.range <= end)
&& (sensor.y + reading.range >= start || sensor.y - reading.range <= end)
}
fun isInRange(reading: Reading, row: Int): Boolean {
val range = distance(reading.beacon, reading.sensor)
return abs(row - reading.sensor.y) <= range
}
fun getBlockingCols(reading: Reading, y: Int, found: HashSet<Int>) {
val range = distance(reading.beacon, reading.sensor)
val xDiffLeftOver = range - abs(y - reading.sensor.y)
(-xDiffLeftOver.. xDiffLeftOver)
.map { C(reading.sensor.x+it, y) }
.filter { distance(reading.sensor, it) <= range }
.forEach() { found.add(it.x) }
}
fun distance(start: C, end: C): Int {
val diff = start - end
return abs(diff.x) + abs(diff.y)
}
fun parseSensorReadings(lines: List<String>): List<Reading> {
return lines.map { parseSensorReading(it) }
}
fun parseSensorReading(line: String): Reading {
var matches = extractRegexGroupsI("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)", line)
return Reading(C(matches[0], matches[1]), C(matches[2], matches[3]))
}
data class Reading(val sensor: C, val beacon: C) {
val range = distance(beacon, sensor)
}
fun IntRange.split(range: IntRange): List<IntRange> {
if (range.first > this.first && range.last >= this.last) {
return listOf(this.first..(Math.min(range.first-1, this.last)))
}
if (range.first<= this.first && range.last < this.last) {
return listOf(Math.max(range.last+1, this.first)..this.last)
}
if (range.first<=this.first && range.last>= this.last)
return emptyList()
return listOf(
this.first until range.first,
range.last+1..this.last
)
} | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 7,912 | Advent-of-Code | MIT License |
src/y2022/Day21.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2022
import util.readInput
object Day21 {
sealed class Monkey(val name: String) {
//abstract val name: String
companion object {
val allMonkeys: MutableMap<String, Monkey> = mutableMapOf()
val allDependents: MutableMap<String, List<String>> = mutableMapOf()
}
abstract fun result(): Long
abstract fun dependents(): List<String>
class Number(name: String, val result: Long) : Monkey(name) {
override fun result(): Long {
return result
}
override fun dependents(): List<String> {
return listOf(name)
}
}
class Operator(
name: String,
val op1: String,
val op2: String,
val operation: String,
) : Monkey(name) {
override fun result(): Long {
val r1 = allMonkeys[op1]?.result()!!
val r2 = allMonkeys[op2]?.result()!!
return operation.toOperation()(r1, r2)
}
override fun dependents(): List<String> {
if (name !in allDependents) {
allDependents[name] = allMonkeys[op1]!!.dependents() + allMonkeys[op2]!!.dependents()
}
return allDependents[name]!!
}
}
}
fun String.toOperation() = when (this) {
"+" -> { a: Long, b: Long -> a + b }
"-" -> { a: Long, b: Long -> a - b }
"*" -> { a: Long, b: Long -> a * b }
"/" -> { a: Long, b: Long -> a / b }
else -> error("not an operation!")
}
private fun parse(input: List<String>) {
val monkeys = input.associate { line ->
val elements = line.split(": ")
val name = elements.first()
val tail = elements.last().split(" ")
val monke = if (tail.size == 1) {
Monkey.Number(name, elements.last().toLong())
} else {
Monkey.Operator(name, tail[0], tail.last(), tail[1])
}
name to monke
}
Monkey.allMonkeys.putAll(monkeys)
}
fun part1(input: List<String>): Long? {
parse(input)
return Monkey.allMonkeys["root"]?.result()
}
fun part2(input: List<String>): Long {
Monkey.allMonkeys.clear()
Monkey.allDependents.clear()
parse(input)
val monkeyNames = Monkey.allMonkeys.keys
val calledNames = Monkey.allMonkeys.values.filterIsInstance<Monkey.Operator>().flatMap { listOf(it.op1, it.op2) }
println("num monkeys :" + monkeyNames.size)
println("called monkeys :" + calledNames.size)
println("unique called :" + calledNames.toSet().size)
println(monkeyNames - calledNames.toSet())
var c1 = (Monkey.allMonkeys["root"]!! as Monkey.Operator).op1
var c2 = (Monkey.allMonkeys["root"]!! as Monkey.Operator).op2
var (currentRoot, desiredResult) = if ("humn" in Monkey.allMonkeys[c1]!!.dependents()) {
c1 to Monkey.allMonkeys[c2]!!.result()
} else {
c2 to Monkey.allMonkeys[c1]!!.result()
}
while (true) {
if (c1 == "humn" || c2 == "humn") {
return desiredResult
}
val rootMonkey = Monkey.allMonkeys[currentRoot] as Monkey.Operator
c1 = rootMonkey.op1
c2 = rootMonkey.op2
val (nextRoot, subResult) = if ("humn" in Monkey.allMonkeys[c1]!!.dependents()) {
c1 to Monkey.allMonkeys[c2]!!.result()
} else {
c2 to Monkey.allMonkeys[c1]!!.result()
}
desiredResult = nextDesired(rootMonkey, c1, nextRoot, desiredResult, subResult)
currentRoot = nextRoot
}
}
private fun nextDesired(
rootMonkey: Monkey.Operator,
first: String,
nextRoot: String,
currentResult: Long,
subResult: Long,
): Long {
return when (rootMonkey.operation) {
"+" -> currentResult - subResult
"*" -> currentResult / subResult
"-" -> if (nextRoot == first) currentResult + subResult else -currentResult + subResult
"/" -> if (nextRoot == first) currentResult * subResult else subResult / currentResult
else -> error("not operator")
}
}
}
fun main() {
val testInput = """
root: pppw + sjmn
dbpl: 5
cczh: sllz + lgvd
zczc: 2
ptdq: humn - dvpt
dvpt: 3
lfqf: 4
humn: 5
ljgn: 2
sjmn: drzm * dbpl
sllz: 4
pppw: cczh / lfqf
lgvd: ljgn * ptdq
drzm: hmdt - zczc
hmdt: 32
""".trimIndent().split("\n")
println("------Tests------")
println(Day21.part1(testInput))
println(Day21.part2(testInput))
println("------Real------")
val input = readInput("resources/2022/day21")
println(Day21.part1(input))
println(Day21.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 5,046 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day7.kt | andilau | 544,512,578 | false | {"Kotlin": 29165} | package days
@AdventOfCodePuzzle(
name = "Internet Protocol Version 7",
url = "https://adventofcode.com/2016/day/7",
date = Date(day = 7, year = 2016)
)
class Day7(private val input: List<String>) : Puzzle {
override fun partOne(): Int = input.count { address -> IP7.from(address).supportsTLS() }
override fun partTwo(): Int = input.count { address -> IP7.from(address).supportsSSL() }
data class IP7(val parts: List<String>) {
private val supernetSequences = parts.filterIndexed { index, _ -> index % 2 == 0 }
private val hypernetSequences = parts.filterIndexed { index, _ -> index % 2 == 1 }
fun supportsTLS(): Boolean {
return hypernetSequences.none { hasAbba(it) } &&
supernetSequences.any { hasAbba(it) }
}
fun supportsSSL(): Boolean {
val abaSequences = getAbaSequences(supernetSequences)
return abaSequences.map { String(charArrayOf(it[1], it[0], it[1])) }.any { bab -> hypernetSequences.any { it.contains(bab) } }
}
companion object {
fun from(line: String): IP7 {
return IP7(line.split("[", "]"))
}
private fun hasAbba(string: String): Boolean {
return (0..string.lastIndex - 3).firstOrNull() {
string[it] != string[it + 1] &&
string[it] == string[it + 3] &&
string[it + 1] == string[it + 2]
} != null
}
private fun getAbaSequences(supernetSequences: List<String>): List<String> =
supernetSequences.flatMap { seq -> seq.windowed(3, 1).filter { hasAba(it) } }
private fun hasAba(sequence: String): Boolean = sequence[0] == sequence[2] && sequence[0] != sequence[1]
}
}
}
| 3 | Kotlin | 0 | 0 | b2a836bd3f1c5eaec32b89a6ab5fcccc91b665dc | 1,850 | advent-of-code-2016 | Creative Commons Zero v1.0 Universal |
lib/src/main/kotlin/aoc/day09/Day09.kt | Denaun | 636,769,784 | false | null | package aoc.day09
import kotlin.math.abs
fun part1(input: String): Int = simulate(parse(input), 2).size
fun part2(input: String): Int = simulate(parse(input), 10).size
fun simulate(motions: List<Motion>, numKnots: Int): Set<Coordinate> {
require(numKnots >= 1)
var knots = List(numKnots) { Coordinate(0, 0) }
val tailPositions = mutableSetOf(knots.last())
for (motion in motions) {
for (step in 0 until motion.steps) {
knots = knots.drop(1)
.runningFold(knots.first().move(motion.direction))
{ prev, next -> next.follow(prev) }
tailPositions.add(knots.last())
}
}
return tailPositions
}
data class Coordinate(val x: Int, val y: Int) {
fun move(direction: Direction): Coordinate =
when (direction) {
Direction.LEFT -> Coordinate(x - 1, y)
Direction.RIGHT -> Coordinate(x + 1, y)
Direction.UP -> Coordinate(x, y + 1)
Direction.DOWN -> Coordinate(x, y - 1)
}
fun follow(other: Coordinate): Coordinate =
if (other.x == x) {
if (other.y > y + 1) {
move(Direction.UP)
} else if (other.y < y - 1) {
move(Direction.DOWN)
} else {
this
}
} else if (other.y == y) {
if (other.x > x + 1) {
move(Direction.RIGHT)
} else if (other.x < x - 1) {
move(Direction.LEFT)
} else {
this
}
} else if (distance(other) > 2) {
move(
if (other.x > x) {
Direction.RIGHT
} else {
Direction.LEFT
}
).move(
if (other.y > y) {
Direction.UP
} else {
Direction.DOWN
}
)
} else {
this
}
private fun distance(other: Coordinate): Int = abs(x - other.x) + abs(y - other.y)
}
| 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 2,075 | aoc-2022 | Apache License 2.0 |
src/Day10.kt | HylkeB | 573,815,567 | false | {"Kotlin": 83982} | private sealed class Instruction {
object Noop : Instruction()
object StartAddX : Instruction()
class FinishAddX(val amount: Int): Instruction()
}
fun main() {
fun List<String>.toInstructions(): List<Instruction> {
return flatMap {
if (it == "noop") {
listOf(Instruction.Noop)
} else {
val amount = it.split(" ")[1].toInt()
listOf(Instruction.StartAddX, Instruction.FinishAddX(amount))
}
}
}
fun Int.cycleToLineIndex(): Int {
return (this - 1) / 40
}
fun Int.clockCycleToPixelPosition(): Int {
return (this - 1) % 40
}
fun Int.isSpriteVisibleAt(pixelPosition: Int): Boolean {
return pixelPosition in this - 1 .. this + 1
}
fun MutableList<String>.appendAtLine(lineIndex: Int, value: Char) {
if (this.size < (1 + lineIndex)) {
this.add("")
}
this[lineIndex] = this[lineIndex] + value
}
fun part1(input: List<String>): Int {
fun Int.isMultipleOf40OffsetBy20(): Boolean {
return (this - 20) % 40 == 0
}
val sums = mutableListOf<Int>()
var currentClockCycle = 1
var xRegisterValue = 1
input.forEach {
if (it == "noop") {
if (currentClockCycle.isMultipleOf40OffsetBy20()) {
sums += currentClockCycle * xRegisterValue
}
currentClockCycle++
} else {
if (currentClockCycle.isMultipleOf40OffsetBy20()) {
sums += currentClockCycle * xRegisterValue
}
currentClockCycle++
if (currentClockCycle.isMultipleOf40OffsetBy20()) {
sums += currentClockCycle * xRegisterValue
}
currentClockCycle++
xRegisterValue += it.split(" ")[1].toInt()
}
}
return sums.sum()
}
fun part2(input: List<String>): String {
var currentClockCycle = 1
var currentSpritePosition = 1
val lines = mutableListOf<String>()
input.toInstructions()
.forEach { instruction ->
// First draw
val pixelPosition = currentClockCycle.clockCycleToPixelPosition()
val isSpriteVisible = currentSpritePosition.isSpriteVisibleAt(pixelPosition)
val characterToDraw = if (isSpriteVisible) '#' else '.'
lines.appendAtLine(currentClockCycle.cycleToLineIndex(), characterToDraw)
// Then perform instruction
if (instruction is Instruction.FinishAddX) {
currentSpritePosition += instruction.amount
}
currentClockCycle++
}
return lines.joinToString(separator = System.lineSeparator())
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent())
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8649209f4b1264f51b07212ef08fa8ca5c7d465b | 3,558 | advent-of-code-2022-kotlin | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year15/Day07.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year15
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.year15.Wiring.*
import com.grappenmaker.aoc.year15.Operator.*
fun PuzzleSet.day7() = puzzle {
val insns = inputLines.associate { l ->
val (operation, target) = l.split(" -> ")
val parts = operation.split(" ")
target to when {
"NOT" in operation -> Not(parts[1].parseSide())
"AND" in operation -> And(parts[0].parseSide(), parts[2].parseSide())
"LSHIFT" in operation -> LShift(parts[0].parseSide(), parts[2].parseSide())
"OR" in operation -> Or(parts[0].parseSide(), parts[2].parseSide())
"RSHIFT" in operation -> RShift(parts[0].parseSide(), parts[2].parseSide())
else -> Connect(operation.parseSide())
}
}
val wireA = insns.solve("a")
partOne = wireA.s()
partTwo = (insns + ("b" to Connect(Value(wireA)))).solve("a").s()
}
fun Map<String, Operator>.solve(forWire: String) = buildMap {
fun recurse(node: Wiring): Int = when (node) {
is Value -> node.literal
is Wire -> getOrPut(node.id) {
when (val insn = this@solve[node.id] ?: error("Wire has not yet been resolved?")) {
is BinaryOperator -> {
val lhs = recurse(insn.lhs)
val rhs = recurse(insn.rhs)
when (insn) {
is And -> lhs and rhs
is Or -> lhs or rhs
is LShift -> lhs shl rhs
is RShift -> lhs shr rhs
}
}
is Not -> recurse(insn.operand).inv()
is Connect -> recurse(insn.from)
} and 0xFFFF
}
}
recurse(Wire(forWire))
}.getValue(forWire)
fun String.parseSide(): Wiring = toIntOrNull()?.let { Value(it) } ?: Wire(this)
sealed interface Operator {
sealed interface BinaryOperator : Operator {
val lhs: Wiring
val rhs: Wiring
}
data class And(override val lhs: Wiring, override val rhs: Wiring) : BinaryOperator
data class LShift(override val lhs: Wiring, override val rhs: Wiring) : BinaryOperator
data class Not(val operand: Wiring) : Operator
data class Or(override val lhs: Wiring, override val rhs: Wiring) : BinaryOperator
data class RShift(override val lhs: Wiring, override val rhs: Wiring) : BinaryOperator
data class Connect(val from: Wiring) : Operator
}
sealed interface Wiring {
data class Value(val literal: Int) : Wiring
data class Wire(val id: String) : Wiring
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,624 | advent-of-code | The Unlicense |
src/Day11.kt | lmoustak | 573,003,221 | false | {"Kotlin": 25890} | import java.util.*
enum class Operation(val value: String) { ADDITION("+"), MULTIPLICATION("*") }
data class Monkey(
val items: MutableList<Long>,
val operation: Operation,
val value: Int?,
val divisibleBy: Int,
val targetIfTrue: Int,
val targetIfFalse: Int,
var inspections: Long = 0L
)
fun main() {
val startingItemsPattern = Regex("""\s*Starting items: ((\d+(,\s*)?)+)""")
val operationPattern = Regex("""\s*Operation: new = old ([+\-*/]) (\d+|old)""")
val testAndTargetPattern = Regex(""".+ (\d+)""")
fun part1(input: List<String>): Long {
val monkeys = mutableListOf<Monkey>()
val sanitizedInput = input.filter { it.isNotBlank() }
for (i in sanitizedInput.indices step 6) {
val items =
startingItemsPattern.find(sanitizedInput[i + 1])!!.groupValues[1].split(", ").map { it.toLong() }
.toMutableList()
val (_, operationString, valueString) = operationPattern.find(sanitizedInput[i + 2])!!.groupValues
val operation = Operation.values().find { it.value == operationString }!!
val value = if (valueString == "old") {
null
} else {
valueString.toInt()
}
val divisibleBy = testAndTargetPattern.find(sanitizedInput[i + 3])!!.groupValues[1].toInt()
val targetIfTrue = testAndTargetPattern.find(sanitizedInput[i + 4])!!.groupValues[1].toInt()
val targetIfFalse = testAndTargetPattern.find(sanitizedInput[i + 5])!!.groupValues[1].toInt()
monkeys.add(Monkey(items, operation, value, divisibleBy, targetIfTrue, targetIfFalse))
}
for (i in 1..20) {
for (monkey in monkeys) {
for (item in monkey.items) {
val value = monkey.value?.toLong() ?: item
val newItem = when (monkey.operation) {
Operation.ADDITION -> item + value
Operation.MULTIPLICATION -> item * value
} / 3L
val nextMonkey = monkeys[if (newItem % monkey.divisibleBy.toLong() == 0L) {
monkey.targetIfTrue
} else {
monkey.targetIfFalse
}]
nextMonkey.items += newItem
monkey.inspections++
}
monkey.items.clear()
}
}
monkeys.sortByDescending { it.inspections }
return monkeys.take(2).map { it.inspections }.reduce(Long::times)
}
fun part2(input: List<String>): Long {
val monkeys = mutableListOf<Monkey>()
val sanitizedInput = input.filter { it.isNotBlank() }
for (i in sanitizedInput.indices step 6) {
val items =
startingItemsPattern.find(sanitizedInput[i + 1])!!.groupValues[1].split(", ").map { it.toLong() }
.toMutableList()
val (_, operationString, valueString) = operationPattern.find(sanitizedInput[i + 2])!!.groupValues
val operation = Operation.values().find { it.value == operationString }!!
val value = if (valueString == "old") {
null
} else {
valueString.toInt()
}
val divisibleBy = testAndTargetPattern.find(sanitizedInput[i + 3])!!.groupValues[1].toInt()
val targetIfTrue = testAndTargetPattern.find(sanitizedInput[i + 4])!!.groupValues[1].toInt()
val targetIfFalse = testAndTargetPattern.find(sanitizedInput[i + 5])!!.groupValues[1].toInt()
monkeys.add(Monkey(items, operation, value, divisibleBy, targetIfTrue, targetIfFalse))
}
val mod = monkeys.map { it.divisibleBy.toLong() }.reduce(Long::times)
for (i in 1..10_000) {
for (monkey in monkeys) {
for (item in monkey.items) {
val value = monkey.value?.toLong() ?: item
val newItem = when (monkey.operation) {
Operation.ADDITION -> item + value
Operation.MULTIPLICATION -> item * value
} % mod
val nextMonkey = monkeys[if (newItem % monkey.divisibleBy == 0L) {
monkey.targetIfTrue
} else {
monkey.targetIfFalse
}]
nextMonkey.items += newItem
monkey.inspections++
}
monkey.items.clear()
}
}
monkeys.sortByDescending { it.inspections }
return monkeys.take(2).map { it.inspections }.reduce(Long::times)
}
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd259af405b557ab7e6c27e55d3c419c54d9d867 | 4,865 | aoc-2022-kotlin | Apache License 2.0 |
2020/src/main/kotlin/de/skyrising/aoc2020/day9/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2020.day9
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.HashCommon
import it.unimi.dsi.fastutil.longs.LongOpenHashSet
val test = TestInput("""
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
""")
fun longArrayOf(numbers: List<String>): LongArray {
val arr = LongArray(numbers.size)
for (i in arr.indices) {
arr[i] = numbers[i].toLong()
}
return arr
}
fun findInvalid(numbers: List<Long>, preambleLen: Int = 25): Long? {
for (i in preambleLen until numbers.size) {
val n = numbers[i]
val set = LongOpenHashSet(preambleLen)
var valid = false
for (j in i - preambleLen until i) {
val m = numbers[j]
if ((n - m) in set) {
valid = true
break
}
set.add(m)
}
if (!valid) return n
}
return null
}
fun findInvalid2(numbers: LongArray, preambleLen: Int = 25): Long? {
for (i in preambleLen until numbers.size) {
val n = numbers[i]
var bloom = 0L
var valid = false
middle@ for (j in i - preambleLen until i) {
val m = numbers[j]
val diff = n - m
val mixed = HashCommon.mix(diff)
if ((bloom and mixed) == mixed) {
for (k in i - preambleLen until j) {
if (numbers[k] == diff) {
valid = true
break@middle
}
}
}
bloom = bloom or HashCommon.mix(m)
}
if (!valid) return n
}
return null
}
@PuzzleName("Encoding Error")
fun PuzzleInput.part1v0() = findInvalid(lines.map(String::toLong))
@PuzzleName("Encoding Error")
fun PuzzleInput.part1v1() = findInvalid2(longArrayOf(lines))
fun PuzzleInput.part2v0(): Any? {
val numbers = lines.map(String::toLong)
val invalid = findInvalid(numbers) ?: return null
for (i in numbers.indices) {
var sum = 0L
for (j in i until numbers.size) {
sum += numbers[j]
if (sum == invalid) {
val sorted = numbers.subList(i, j + 1).sorted()
return sorted[0] + sorted[sorted.size - 1]
}
if (sum > invalid) break
}
}
return null
}
fun PuzzleInput.part2v1(): Any? {
val numbers = longArrayOf(lines)
val invalid = findInvalid2(numbers) ?: return null
for (i in numbers.lastIndex downTo 0) {
var sum = numbers[i]
var min = sum
var max = sum
for (j in i + 1 until numbers.size) {
val n = numbers[j]
min = minOf(min, n)
max = maxOf(max, n)
sum += n
if (sum == invalid && max != min) return min + max
if (sum > invalid) break
}
}
return null
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,958 | aoc | MIT License |
src/main/kotlin/day12/Code.kt | fcolasuonno | 317,324,330 | false | null | package day12
import isDebug
import java.io.File
import kotlin.math.abs
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
private val lineStructure = """(.)(\d+)""".toRegex()
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val (instruction, amount) = it.toList()
instruction.single() to amount.toInt()
}
}.requireNoNulls()
fun part1(input: List<Pair<Char, Int>>) {
val res = input.fold('E' to (0 to 0)) { (dir, pos), (instr, amount) ->
when (instr) {
'L' -> generateSequence(dir) { it.left() }.elementAt(amount / 90)
'R' -> generateSequence(dir) { it.right() }.elementAt(amount / 90)
else -> dir
} to when (instr) {
'F' -> pos.move(dir, amount)
'L', 'R' -> pos
else -> pos.move(instr, amount)
}
}.let { (_, pos) -> pos.manhattam() }
println("Part 1 = $res")
}
fun part2(input: List<Pair<Char, Int>>) {
val res = input.fold((10 to 1) to (0 to 0)) { (waypoint, pos), (instr, amount) ->
when (instr) {
'F' -> waypoint
'R' -> generateSequence(waypoint) { (x, y) -> y to -x }.elementAt(amount / 90)
'L' -> generateSequence(waypoint) { (x, y) -> -y to x }.elementAt(amount / 90)
else -> waypoint.move(instr, amount)
} to when (instr) {
'F' -> generateSequence(pos) { (x, y) -> (waypoint.first + x) to (waypoint.second + y) }.elementAt(amount)
else -> pos
}
}.let { (_, pos) -> pos.manhattam() }
println("Part 2 = $res")
}
fun Pair<Int, Int>.manhattam() = abs(first) + abs(second)
fun Pair<Int, Int>.move(dir: Char, amount: Int): Pair<Int, Int> = when (dir) {
'N' -> copy(second = second + amount)
'E' -> copy(first = first + amount)
'S' -> copy(second = second - amount)
'W' -> copy(first = first - amount)
else -> throw IllegalArgumentException()
}
fun Char.left() = "NWSE".let { it[(it.indexOf(this) + 1) % 4] }
fun Char.right() = "NESW".let { it[(it.indexOf(this) + 1) % 4] } | 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 2,319 | AOC2020 | MIT License |
src/Day01.kt | remidu | 573,452,090 | false | {"Kotlin": 22113} | fun main() {
fun part1(input: List<String>): Int {
var best = 0
var total = 0
for (line in input) {
if (line.isBlank()) {
if (total > best) best = total
total = 0
} else {
total += line.toInt()
}
}
return best
}
fun part2(input: List<String>): Int {
val best3 = intArrayOf(0, 0, 0)
var total = 0
for (line in input) {
if (line.isBlank()) {
if (total > best3[0]) best3[0] = total
best3.sort()
total = 0
} else {
total += line.toInt()
}
}
return best3.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 | ecda4e162ab8f1d46be1ce4b1b9a75bb901bc106 | 984 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/cloud/dqn/leetcode/TwoSum4Kt.kt | aviuswen | 112,305,062 | false | null | package cloud.dqn.leetcode
/**
* https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/
Given a Binary Search Tree and a target number,
return true if there exist two elements in the BST
such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
*/
class TwoSum4Kt {
class Solution {
fun findButNotSelf(root: TreeNode, src: TreeNode, value: Int): TreeNode? {
var currentNode: TreeNode? = root
while (currentNode != null) {
currentNode = when {
(value < currentNode.`val`) -> currentNode.left
(value > currentNode.`val`) -> currentNode.right
else -> {
return when {
(src !== currentNode) -> currentNode
(currentNode.left?.`val` == src.`val`) -> currentNode.left
(currentNode.right?.`val` == src.`val`) -> currentNode.right
else -> null
}
}
}
}
return null
}
fun iterateInOrder(currentNode: TreeNode?, body: (TreeNode) -> Unit) {
currentNode?.let {
it.left?.let { iterateInOrder(it, body) }
body(it)
it.right?.let { iterateInOrder(it, body) }
}
}
fun findTarget(root: TreeNode?, k: Int): Boolean {
var found = false
root?.let {
iterateInOrder(it, body = { node ->
findButNotSelf(it, node, k - node.`val`)?.let {
found = true
}
})
}
return found
}
fun findTargetFaster(root: TreeNode?, k: Int): Boolean {
var found = false
root?.let {
val targetToNode = HashMap<Int, TreeNode>()
iterateInOrder(it, body = { currentNode ->
targetToNode[k - currentNode.`val`] = currentNode
} )
iterateInOrder(it, body = { currentNode ->
targetToNode[currentNode.`val`]?.let { targetNode ->
if (currentNode !== targetNode) {
found = true
}
}
})
}
return found
}
}
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
} | 0 | Kotlin | 0 | 0 | 23458b98104fa5d32efe811c3d2d4c1578b67f4b | 2,875 | cloud-dqn-leetcode | No Limit Public License |
src/Day09.kt | esteluk | 572,920,449 | false | {"Kotlin": 29185} | import kotlin.math.absoluteValue
fun main() {
fun printPositions(head: Pair<Int, Int>, tail: Array<Pair<Int, Int>>, size: Pair<Int, Int> = Pair(6, 5)) {
for (i in size.second-1 downTo 0) {
val builder = StringBuilder(size.first)
for (j in 0 until size.first) {
if (head.first == j && head.second == i) {
builder.append("H")
} else if (tail.contains(Pair(j, i))) {
val index = tail.indexOf(Pair(j, i))+1
builder.append("$index")
} else {
builder.append(".")
}
}
println(builder.toString())
}
println()
}
fun part1(input: List<String>): Int {
var headPosition = Pair(0,0)
var tailPosition = Pair(0,0)
val tailVisitedPositions = mutableSetOf<Pair<Int, Int>>()
val instructions = input.map { it.split(" ") }.map { Pair(it.first(), it[1].toInt()) }
instructions.forEach {
val direction = it.first
// println(it)
for (i in 0 until it.second) {
// Move the head
when(direction) {
"U" -> headPosition = Pair(headPosition.first, headPosition.second + 1)
"D" -> headPosition = Pair(headPosition.first, headPosition.second - 1)
"L" -> headPosition = Pair(headPosition.first - 1, headPosition.second)
"R" -> headPosition = Pair(headPosition.first + 1, headPosition.second)
}
// println("Head now at ${headPosition}")
// Move the tail
if (tailPosition.first < headPosition.first - 1) {
tailPosition = Pair(tailPosition.first + 1, headPosition.second)
} else if (tailPosition.first > headPosition.first + 1) {
tailPosition = Pair(tailPosition.first - 1, headPosition.second)
}
if (tailPosition.second < headPosition.second - 1) {
tailPosition = Pair(headPosition.first, tailPosition.second + 1)
} else if (tailPosition.second > headPosition.second + 1) {
tailPosition = Pair(headPosition.first, tailPosition.second - 1)
}
// println("Tail now at ${tailPosition}")
tailVisitedPositions.add(tailPosition)
}
}
return tailVisitedPositions.size
}
fun part2(input: List<String>): Int {
var headPosition = Pair(0,0)
val knotPositions = Array(9) { Pair(0, 0) }
val tailVisitedPositions = mutableSetOf<Pair<Int, Int>>()
val instructions = input.map { it.split(" ") }.map { Pair(it.first(), it[1].toInt()) }
instructions.forEach {
val direction = it.first
// println(it)
for (i in 0 until it.second) {
// Move the head
when(direction) {
"U" -> headPosition = Pair(headPosition.first, headPosition.second + 1)
"D" -> headPosition = Pair(headPosition.first, headPosition.second - 1)
"L" -> headPosition = Pair(headPosition.first - 1, headPosition.second)
"R" -> headPosition = Pair(headPosition.first + 1, headPosition.second)
}
// println("Head now at ${headPosition}")
// Move the tail
for (j in 0 until 9) {
val previousPosition = if (j > 0) knotPositions[j-1] else headPosition
val xDiff = knotPositions[j].first - previousPosition.first
val yDiff = knotPositions[j].second - previousPosition.second
val isNotTouching = xDiff.absoluteValue > 1 || yDiff.absoluteValue > 1
val isSameAxis = xDiff == 0 || yDiff == 0
if (isNotTouching && !isSameAxis) {
val newX = if (xDiff < 0) knotPositions[j].first + 1 else knotPositions[j].first - 1
val newY = if (yDiff < 0) knotPositions[j].second + 1 else knotPositions[j].second - 1
knotPositions[j] = Pair(newX, newY)
} else if (isNotTouching) {
val newX = if (xDiff < -1) knotPositions[j].first + 1 else if (xDiff > 1) knotPositions[j].first - 1 else knotPositions[j].first
val newY = if (yDiff < -1) knotPositions[j].second + 1 else if (yDiff > 1) knotPositions[j].second - 1 else knotPositions[j].second
knotPositions[j] = Pair(newX, newY)
}
}
// printPositions(headPosition, knotPositions)
tailVisitedPositions.add(knotPositions[8])
}
// for (j in 0 until 9) {
// println("Knot ${j+1} at ${knotPositions[j]}")
// }
}
return tailVisitedPositions.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
// check(part1(testInput) == 13)
check(part2(testInput) == 1)
val test2Input = readInput("Day09_test2")
check(part2(test2Input) == 36)
val input = readInput("Day09")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73 | 5,421 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimizeDeviationInArray.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Collections
import java.util.PriorityQueue
import kotlin.math.min
/**
* 1675. Minimize Deviation in Array
* @see <a href="https://leetcode.com/problems/minimize-deviation-in-array/">Source</a>
*/
fun interface MinimizeDeviationInArray {
fun minimumDeviation(nums: IntArray): Int
}
class MinimizeDeviationInArrayQueue : MinimizeDeviationInArray {
override fun minimumDeviation(nums: IntArray): Int {
val pq: PriorityQueue<Int> = PriorityQueue(Collections.reverseOrder())
var minVal = Int.MAX_VALUE
for (num in nums) {
var n = num
if (n % 2 == 1) {
n *= 2
}
pq.offer(n)
minVal = min(minVal, n)
}
var minDeviation = Int.MAX_VALUE
while (true) {
var maxVal: Int = pq.poll()
minDeviation = min(minDeviation, maxVal - minVal)
if (maxVal % 2 == 1) break
maxVal /= 2
minVal = min(minVal, maxVal)
pq.offer(maxVal)
}
return minDeviation
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,719 | kotlab | Apache License 2.0 |
src/test/kotlin/Day13.kt | christof-vollrath | 317,635,262 | false | null | import io.kotest.core.spec.style.FunSpec
import io.kotest.data.forAll
import io.kotest.data.headers
import io.kotest.data.row
import io.kotest.data.table
import io.kotest.matchers.shouldBe
/*
--- Day 13: Shuttle Search ---
See https://adventofcode.com/2020/day/13
*/
fun List<Int?>.findNextBus(earliest: Int): Pair<Int, Int> {
val leavingNow = getOrNull(earliest)
if (leavingNow != null) return leavingNow to 0 // Found a bus just leaving now
val departureTimes = mapNotNull { busId ->
if (busId == null) null
else {
val departureTime = (earliest + busId) / busId * busId
busId to departureTime
}
}
return departureTimes.minByOrNull { it.second }!!
}
fun parseTimeTable(timeTableString: String): List<Int?> = timeTableString.split(",").map { it.toIntOrNull()}
class Day13_Part1 : FunSpec({
val busTimeTableString = "7,13,x,x,59,x,31,19"
context("parse time table") {
val timeTable = parseTimeTable(busTimeTableString)
test("should have parsed 8 buses") {
timeTable.size shouldBe 8
}
test("should have parsed the right time table") {
timeTable shouldBe listOf(7, 13, null, null, 59, null, 31, 19)
}
context("find next bus") {
val nextBus = timeTable.findNextBus(939)
test("should have found the right bus") {
nextBus.first shouldBe 59
nextBus.second shouldBe 944
}
test("should have found solution") {
calculateShuttleSolution(939, nextBus) shouldBe 295
}
}
}
})
fun calculateShuttleSolution(earliest: Int, nextBus: Pair<Int, Int>) = (nextBus.second - earliest) * nextBus.first
fun calculateShuttleContest(timeTable: List<Int?>): Long {
fun check(time: Long, timeTable: List<IndexedValue<Int?>>): Boolean {
for(i in timeTable) {
val busTime = i.value
if (busTime != null && (time + i.index) % busTime != 0L) return false
}
return true
}
val timeTableWithIndex = timeTable.withIndex().filter { it.value != null }
val checkBus = timeTableWithIndex.maxByOrNull { it.value!!}!! // Optimization: use highest id for loop
println("checkBus=$checkBus")
//var time = (checkBus.value!! - checkBus.index).toLong()
var time = 539742675714343L // Was interrupted after this value
var i = 0
//TODO sort by bus id descending to start with the biggest
// check only against the last bus
while(true) {
if (check(time, timeTableWithIndex)) return time
time += checkBus.value!!
if (i % 10_000_000 == 0) println("time=$time")
i++
}
}
class Day13_Part1_Exercise: FunSpec({
val input = readResource("day13Input.txt")!!
val inputLines = input.split("\n")
val earliest = inputLines[0].toInt()
val timeTable = parseTimeTable(inputLines[1])
val nextBus = timeTable.findNextBus(earliest)
val solution = calculateShuttleSolution(earliest, nextBus)
test("should have found solution") {
solution shouldBe 171
}
})
class Day13_Part2 : FunSpec({
xcontext("shuttle contest example") {
val busTimeTableString = "7,13,x,x,59,x,31,19"
val timeTable = parseTimeTable(busTimeTableString)
val solution = calculateShuttleContest(timeTable)
test("should have found solution") {
solution shouldBe 1068781
}
}
xcontext("more shuttle contest examples") {
table(
headers("bus ids", "expected"),
row("17,x,13,19", 3417),
row("67,7,59,61", 754018),
row("67,x,7,59,61", 779210),
row("67,7,x,59,61", 1261476),
row("1789,37,47,1889", 1202161486),
).forAll { busTimeTableString, expected ->
val timeTable = parseTimeTable(busTimeTableString)
val solution = calculateShuttleContest(timeTable)
solution shouldBe expected
}
}
})
class Day13_Part2_Exercise: FunSpec({
val input = readResource("day13Input.txt")!!
val inputLines = input.split("\n")
val timeTable = parseTimeTable(inputLines[1])
xcontext("test") {
val solution = calculateShuttleContest(timeTable)
test("should have found solution") {
solution shouldBe 539746751134958L
}
}
})
| 1 | Kotlin | 0 | 0 | 8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8 | 4,392 | advent_of_code_2020 | Apache License 2.0 |
src/main/kotlin/Day02.kt | nmx | 572,850,616 | false | {"Kotlin": 18806} | fun main(args: Array<String>) {
class Shape(
val draw: Char,
val defeats: Char,
val score: Int
)
val shapes = buildMap<Char, Shape> {
put('X', Shape('A', 'C', 1)) // Rock smashes Scissors
put('Y', Shape('B', 'A', 2)) // Paper covers Rock
put('Z', Shape('C', 'B', 3)) // Scissors cuts Paper
}
class OpponentShape(win: Char, lose: Char, draw: Char) {
val win = shapes[win]!!
val lose = shapes[lose]!!
val draw = shapes[draw]!!
}
val opponentShapes = buildMap<Char, OpponentShape> {
put('A', OpponentShape('Y', 'Z', 'X'))
put('B', OpponentShape('Z', 'X', 'Y'))
put('C', OpponentShape('X', 'Y', 'Z'))
}
fun scoreRow(row: String, secondColumIsWLD: Boolean): Int {
if (row.isEmpty())
return 0
val opponent = row[0]
val shape = if (secondColumIsWLD) {
val opponentShape = opponentShapes[opponent]!!
when (row[2]) {
'X' -> opponentShape.lose
'Y' -> opponentShape.draw
'Z' -> opponentShape.win
else -> throw RuntimeException("unhandled input")
}
} else {
shapes[row[2]]!!
}
return shape.score + when (opponent) {
shape.defeats -> 6
shape.draw -> 3
else -> 0
}
}
fun partN(input: String, secondColumIsWLD: Boolean) {
var score = 0
input.split("\n").forEach {
score += scoreRow(it, secondColumIsWLD)
}
println(score)
}
fun part1(input: String) {
partN(input, false)
}
fun part2(input: String) {
partN(input, true)
}
val input = object {}.javaClass.getResource("Day02.txt").readText()
part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | 33da2136649d08c32728fa7583ecb82cb1a39049 | 1,859 | aoc2022 | MIT License |
src/Day05.kt | ExpiredMinotaur | 572,572,449 | false | {"Kotlin": 11216} | fun main() {
var crateDataOriginal: List<List<Char>> =emptyList()
var moveData: List<List<Int>> = emptyList()
fun loadData(input: List<String>){
val data = input.chunkedByBlank()
//Parse Crate Data
val lineLength = data[0].maxOf { it.length }
crateDataOriginal = data[0].dropLast(1)
.map{it.padEnd(lineLength, ' ')
.slice(1 until lineLength step 4)
.toList()
}
.transpose()
.map { it.filter { char -> !char.isWhitespace() } }
//Parse Move Data
val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
moveData = data[1].map{regex.find(it)!!.groupValues.drop(1).map{v-> v.toInt()}}
}
fun part1(): String {
var crateData = crateDataOriginal.map { it.toMutableList() }.toMutableList() //copy list
for((amount, from, to) in moveData)
{
val moving = crateData[from-1].takeLast(amount).reversed()
crateData[to-1].addAll(moving)
crateData[from-1] = crateData[from-1].dropLast(amount).toMutableList()
}
return crateData.map{it.last()}.joinToString ("")
}
fun part2(): String {
var crateData = crateDataOriginal.map { it.toMutableList() }.toMutableList() //copy list
for((amount, from, to) in moveData)
{
val moving = crateData[from-1].takeLast(amount)
crateData[to-1].addAll(moving)
crateData[from-1] = crateData[from-1].dropLast(amount).toMutableList()
}
return crateData.map{it.last()}.joinToString ("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
loadData(testInput)
check(part1() == "CMZ")
check(part2() == "MCD")
val input = readInput("Day05")
loadData(input)
println("Part 1: " + part1())
println("Part 2: " + part2())
} | 0 | Kotlin | 0 | 0 | 7ded818577737b0d6aa93cccf28f07bcf60a9e8f | 1,950 | AOC2022 | Apache License 2.0 |
src/Day24.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | fun main() {
var dR = listOf<Int>(-1, 0, 1, 0, 0)
var dC = listOf<Int>(0, 1, 0, -1, 0)
fun part1(input: List<String>): Int {
var blizzards = arrayListOf<ArrayList<ArrayList<Boolean>>>()
var oldPositions = mutableSetOf<Pair<Pair<Int, Int>, Int>>()
var blizzard = arrayListOf<ArrayList<Boolean>>()
for (i in input.indices) {
blizzard.add(arrayListOf())
for (j in input[i].indices) {
blizzard[i].add(input[i][j] != '.' && input[i][j] != '#')
if (input[i][j] == '.' || input[i][j] == '#') continue
var dir = when (input[i][j]) {
'^' -> 0
'>' -> 1
'v' -> 2
else -> 3
}
oldPositions.add(Pair(Pair(i, j), dir))
}
}
blizzards.add(blizzard)
// generate blizzards for each step
fun genNewBlizzard() {
var blizzard = arrayListOf<ArrayList<Boolean>>()
for (i in input.indices) {
blizzard.add(arrayListOf())
for (j in input[i].indices) {
blizzard[i].add(false)
}
}
var positions = mutableSetOf<Pair<Pair<Int, Int>, Int>>()
for (pos in oldPositions) {
var (r, c) = pos.first
var dir = pos.second
r += dR[dir]
c += dC[dir]
if (input[r][c] == '#') {
when (dir) {
0 -> r = input.size - 2
1 -> c = 1
2 -> r = 1
3 -> c = input[0].length - 2
}
}
blizzard[r][c] = true
positions.add(Pair(Pair(r, c), dir))
}
blizzards.add(blizzard)
oldPositions = positions
}
val dist = mutableSetOf<Pair<Pair<Int, Int>, Int>>() // ((row, col), dist)
val queue = mutableListOf<Pair<Pair<Int, Int>, Int>>()
queue.add(Pair(Pair(0, 1), 0))
dist.add(Pair(Pair(0, 1), 0))
while (queue.isNotEmpty()) {
while (queue[0].second+1 >= blizzards.size) {
genNewBlizzard()
}
val blizzard = blizzards[queue[0].second + 1]
val (r, c) = queue[0].first
val d = queue[0].second
if (r == input.size - 1 && c == input[0].length - 2) {
return d
}
queue.removeAt(0)
for (i in 0 until 5) {
val nr = r + dR[i]
val nc = c + dC[i]
if (nr < 0 || nr >= blizzard.size || nc < 0 || nc >= blizzard[0].size || input[nr][nc] == '#') continue
if (!blizzard[nr][nc] && !dist.contains(Pair(Pair(nr, nc), d + 1))) {
dist.add(Pair(Pair(nr, nc), d + 1))
queue.add(Pair(Pair(nr, nc), d + 1))
}
}
}
return -1
}
fun part2(input: List<String>): Int {
var blizzards = arrayListOf<ArrayList<ArrayList<Boolean>>>()
var oldPositions = mutableSetOf<Pair<Pair<Int, Int>, Int>>()
var blizzard = arrayListOf<ArrayList<Boolean>>()
for (i in input.indices) {
blizzard.add(arrayListOf())
for (j in input[i].indices) {
blizzard[i].add(input[i][j] != '.' && input[i][j] != '#')
if (input[i][j] == '.' || input[i][j] == '#') continue
var dir = when (input[i][j]) {
'^' -> 0
'>' -> 1
'v' -> 2
else -> 3
}
oldPositions.add(Pair(Pair(i, j), dir))
}
}
blizzards.add(blizzard)
// generate blizzards for each step
fun genNewBlizzard() {
var blizzard = arrayListOf<ArrayList<Boolean>>()
for (i in input.indices) {
blizzard.add(arrayListOf())
for (j in input[i].indices) {
blizzard[i].add(false)
}
}
var positions = mutableSetOf<Pair<Pair<Int, Int>, Int>>()
for (pos in oldPositions) {
var (r, c) = pos.first
var dir = pos.second
r += dR[dir]
c += dC[dir]
if (input[r][c] == '#') {
when (dir) {
0 -> r = input.size - 2
1 -> c = 1
2 -> r = 1
3 -> c = input[0].length - 2
}
}
blizzard[r][c] = true
positions.add(Pair(Pair(r, c), dir))
}
blizzards.add(blizzard)
oldPositions = positions
}
val dist = mutableSetOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>() // ((row, col), (dist, currentTarget))
val queue = mutableListOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>()
queue.add(Pair(Pair(0, 1), Pair(0, 0)))
dist.add(Pair(Pair(0, 1), Pair(0, 0)))
var target = listOf<Pair<Int, Int>>(
Pair(input.size-1, input[0].length-2),
Pair(0, 1),
Pair(input.size-1, input[0].length-2)
)
while (queue.isNotEmpty()) {
val d = queue[0].second.first
while (d+1 >= blizzards.size) {
genNewBlizzard()
}
val blizzard = blizzards[d + 1]
val (r, c) = queue[0].first
var curTarget = queue[0].second.second
if (Pair(r, c) == target[curTarget]) curTarget++
if (curTarget == 3) return d
queue.removeAt(0)
for (i in 0 until 5) {
val nr = r + dR[i]
val nc = c + dC[i]
if (nr < 0 || nr >= blizzard.size || nc < 0 || nc >= blizzard[0].size || input[nr][nc] == '#') continue
if (!blizzard[nr][nc] && !dist.contains(Pair(Pair(nr, nc), Pair(d + 1, curTarget)))) {
dist.add(Pair(Pair(nr, nc), Pair(d + 1, curTarget)))
queue.add(Pair(Pair(nr, nc), Pair(d + 1, curTarget)))
}
}
}
return -1
}
val input = readInput("Day24")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 6,456 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxScore.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 1423. Maximum Points You Can Obtain from Cards
* @see <a href="https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/">Source</a>
*/
fun interface MaxScore {
operator fun invoke(cardPoints: IntArray, k: Int): Int
}
/**
* Approach 1: Dynamic Programming
* Time complexity: O(k).
* Space complexity: O(k).
*/
class MaxScoreDP : MaxScore {
override operator fun invoke(cardPoints: IntArray, k: Int): Int {
val n: Int = cardPoints.size
val frontSetOfCards = IntArray(k + 1)
val rearSetOfCards = IntArray(k + 1)
for (i in 0 until k) {
frontSetOfCards[i + 1] = cardPoints[i] + frontSetOfCards[i]
rearSetOfCards[i + 1] = cardPoints[n - i - 1] + rearSetOfCards[i]
}
var maxScore = 0
// Each i represents the number of cards we take from the front.
for (i in 0..k) {
val currentScore = frontSetOfCards[i] + rearSetOfCards[k - i]
maxScore = max(maxScore, currentScore)
}
return maxScore
}
}
/**
* Approach 2: Dynamic Programming - Space Optimized
* Time complexity: O(k).
* Space complexity: O(1).
*/
class MaxScoreDPSpaceOptimized : MaxScore {
override operator fun invoke(cardPoints: IntArray, k: Int): Int {
var frontScore = 0
var rearScore = 0
val n: Int = cardPoints.size
for (i in 0 until k) {
frontScore += cardPoints[i]
}
// take all k cards from the beginning
var maxScore = frontScore
// take i from the beginning and k - i from the end
for (i in k - 1 downTo 0) {
rearScore += cardPoints[n - (k - i)]
frontScore -= cardPoints[i]
val currentScore = rearScore + frontScore
maxScore = max(maxScore, currentScore)
}
return maxScore
}
}
/**
* Approach 3: Sliding Window
* Time complexity: O(n).
* Space complexity: O(1).
*/
class MaxScoreSlidingWindow : MaxScore {
override operator fun invoke(cardPoints: IntArray, k: Int): Int {
var startingIndex = 0
var presentSubarrayScore = 0
val n: Int = cardPoints.size
val requiredSubarrayLength = n - k
var minSubarrayScore: Int
var totalScore = 0
// Total score obtained on selecting all the cards.
for (i in cardPoints) {
totalScore += i
}
minSubarrayScore = totalScore
if (k == n) {
return totalScore
}
for (i in 0 until n) {
presentSubarrayScore += cardPoints[i]
val presentSubarrayLength = i - startingIndex + 1
// If a valid sub array (having size cardsPoints.length - k) is possible.
if (presentSubarrayLength == requiredSubarrayLength) {
minSubarrayScore = min(minSubarrayScore, presentSubarrayScore)
presentSubarrayScore -= cardPoints[startingIndex++]
}
}
return totalScore - minSubarrayScore
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,727 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/OptimalDivision.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
class Division {
var maxVal: Float = 0f
var minVal: Float = 0f
var minStr: String = ""
var maxStr: String = ""
}
fun interface OptimalDivisionStrategy {
operator fun invoke(nums: IntArray): String
}
class OptimalDivisionBruteForce : OptimalDivisionStrategy {
override operator fun invoke(nums: IntArray): String {
val t = optimal(nums, 0, nums.size - 1)
return t.maxStr
}
private fun optimal(nums: IntArray, start: Int, end: Int): Division {
val division = Division()
if (start == end) {
division.maxVal = nums[start].toFloat()
division.minVal = nums[start].toFloat()
division.minStr = "" + nums[start]
division.maxStr = "" + nums[start]
return division
}
division.minVal = Float.MAX_VALUE
division.maxVal = Float.MIN_VALUE
division.maxStr = ""
division.minStr = division.maxStr
for (i in start until end) {
val left = optimal(nums, start, i)
val right = optimal(nums, i + 1, end)
if (division.minVal > left.minVal / right.maxVal) {
division.minVal = left.minVal / right.maxVal
division.minStr =
left.minStr + "/" + (if (i + 1 != end) "(" else "") + right.minStr + if (i + 1 != end) ")" else ""
}
if (division.maxVal < left.maxVal / right.minVal) {
division.maxVal = left.maxVal / right.minVal
division.maxStr =
left.maxStr + "/" + (if (i + 1 != end) "(" else "") + right.minStr + if (i + 1 != end) ")" else ""
}
}
return division
}
}
class OptimalDivisionMemorization : OptimalDivisionStrategy {
override operator fun invoke(nums: IntArray): String {
val memo: Array<Array<Division>> = Array(nums.size) { Array<Division>(nums.size) { Division() } }
val division: Division = optimal(nums, 0, nums.size - 1, memo)
return division.maxStr
}
private fun optimal(nums: IntArray, start: Int, end: Int, memo: Array<Array<Division>>): Division {
val division = Division()
if (start == end) {
division.maxVal = nums[start].toFloat()
division.minVal = nums[start].toFloat()
division.minStr = "" + nums[start]
division.maxStr = "" + nums[start]
memo[start][end] = division
return division
}
division.minVal = Float.MAX_VALUE
division.maxVal = Float.MIN_VALUE
division.maxStr = ""
division.minStr = division.maxStr
for (i in start until end) {
val left: Division = optimal(nums, start, i, memo)
val right: Division = optimal(nums, i + 1, end, memo)
if (division.minVal > left.minVal / right.maxVal) {
division.minVal = left.minVal / right.maxVal
division.minStr =
left.minStr + "/" + (if (i + 1 != end) "(" else "") + right.maxStr + if (i + 1 != end) ")" else ""
}
if (division.maxVal < left.maxVal / right.minVal) {
division.maxVal = left.maxVal / right.minVal
division.maxStr =
left.maxStr + "/" + (if (i + 1 != end) "(" else "") + right.minStr + if (i + 1 != end) ")" else ""
}
}
try {
memo[start][end] = division
} catch (ignore: ArrayIndexOutOfBoundsException) {
return division
}
return division
}
}
class MathOptimalDivision : OptimalDivisionStrategy {
override operator fun invoke(nums: IntArray): String {
if (nums.isEmpty()) return ""
if (nums.size == 1) return nums.first().toString() + ""
if (nums.size == 2) return nums.first().toString() + "/" + nums[1]
val res = StringBuilder(nums.first().toString() + "/(" + nums[1])
for (i in 2 until nums.size) {
res.append("/" + nums[i])
}
res.append(")")
return res.toString()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,741 | kotlab | Apache License 2.0 |
src/aoc2022/Day05.kt | Playacem | 573,606,418 | false | {"Kotlin": 44779} | package aoc2022
import utils.readInput
object Day05 {
override fun toString(): String {
return this.javaClass.simpleName
}
data class Instruction(val numOfItems: Int, val fromRaw: Int, val toRaw: Int) {
val fromIndex: Int get() = fromRaw - 1
val toIndex: Int get() = toRaw - 1
}
fun String.toInstruction(): Instruction {
val parts = this.split(' ', limit = 6)
return Instruction(
numOfItems = parts[1].toInt(radix = 10),
fromRaw = parts[3].toInt(radix = 10),
toRaw = parts[5].toInt(radix = 10)
)
}
class StorageStack(val is9001: Boolean = false) {
private val lines = ArrayDeque<String>()
private val stacks: MutableList<ArrayDeque<String>> = mutableListOf()
private var layoutDone = false
fun loadData(lines: List<String>): StorageStack {
lines.forEach(::readInputLine)
return this
}
private fun readInputLine(line: String) {
if (line.isBlank() && !layoutDone) {
val numberOfElements = lines.removeLast().split(' ').last { it.isNotBlank() }.toInt()
repeat(numberOfElements) {
stacks.add(ArrayDeque())
}
lines.reversed().forEach {
it.chunked(4) { chars ->
chars.trim().removePrefix("[").removeSuffix("]")
}.forEachIndexed { index, charSequence ->
if (charSequence.isNotBlank()) {
stacks[index].addFirst(charSequence.toString())
}
}
}
layoutDone = true
return
}
if (!layoutDone) {
lines.add(line)
return
}
line.toInstruction().apply {
if (is9001) {
applyInstruction9001(this)
} else {
applyInstruction9000(this)
}
}
}
private fun applyInstruction9000(instruction: Instruction) {
repeat(instruction.numOfItems) {
val tmp = stacks[instruction.fromIndex].removeFirst()
stacks[instruction.toIndex].addFirst(tmp)
}
}
private fun applyInstruction9001(instruction: Instruction) {
val tmp: ArrayDeque<String> = ArrayDeque()
repeat(instruction.numOfItems) {
stacks[instruction.fromIndex].removeFirst().apply { tmp.addLast(this) }
}
stacks[instruction.toIndex].addAll(0, tmp)
}
fun displayStacks(): StorageStack {
println("-".repeat(15))
stacks.forEachIndexed { index, strings ->
println("${index + 1}: $strings")
}
println("-".repeat(15))
return this
}
fun calculateMessage(): String {
return stacks.joinToString(prefix = "", postfix = "", separator = "") { it.first() }
}
}
}
fun main() {
fun part1(input: List<String>): String {
return Day05.StorageStack().loadData(input).displayStacks().calculateMessage()
}
fun part2(input: List<String>): String {
return Day05.StorageStack(is9001 = true).loadData(input).displayStacks().calculateMessage()
}
val testInput = readInput(2022, "${Day05}_test")
val input = readInput(2022, Day05.toString())
// test if implementation meets criteria from the description, like:
check(part1(testInput) == "CMZ")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4ec3831b3d4f576e905076ff80aca035307ed522 | 3,743 | advent-of-code-2022 | Apache License 2.0 |
src/day16/Day16.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day16
import Runner
fun main() {
Day16Runner().solve()
}
class Day16Runner : Runner<Int>(
day = 16,
expectedPartOneTestAnswer = 1651,
expectedPartTwoTestAnswer = 1707
) {
override fun partOne(input: List<String>, test: Boolean): Int {
val valveInput = valves(input)
return recurseValves(
initialValve = valveInput
.first { valve -> valve.label == "AA" }
.let { valve -> Valve(label = valve.label, flowRate = valve.flowRate) },
paths = getPaths(valveInput),
maxTime = 30
)
}
override fun partTwo(input: List<String>, test: Boolean): Int {
val valveInput = valves(input)
return recurseValves(
initialValve = valveInput
.first { valve -> valve.label == "AA" }
.let { valve -> Valve(label = valve.label, flowRate = valve.flowRate) },
paths = getPaths(valveInput),
maxTime = 26,
helper = true
)
}
private fun recurseValves(
initialValve: Valve,
paths: Map<Valve, Map<Valve, Int>>,
maxTime: Int,
helper: Boolean = false
) : Int {
fun openValves(
valve: Valve,
paths: Map<Valve, Map<Valve, Int>>,
visited: Set<Valve> = setOf(),
scores: MutableList<Int> = mutableListOf(),
currentTime: Int = 0,
maxTime: Int,
currentScore: Int = 0,
helper: Boolean = false
) : List<Int> {
scores.add(currentScore)
paths[valve]!!.forEach { (pathNode, travelTime) ->
val canVisit = canVisitNode(
valve = pathNode,
visited = visited,
travelTime = travelTime,
currentTime = currentTime,
maxTime = maxTime
)
if (canVisit) {
val updatedScore = calculateScore(
valve = pathNode,
currentScore = currentScore,
travelTime = travelTime,
currentTime = currentTime,
maxTime = maxTime,
)
openValves(
valve = pathNode,
paths = paths,
visited = visited.toMutableSet().apply { add(pathNode) },
scores = scores,
currentTime = currentTime + travelTime + 1,
maxTime = maxTime,
currentScore = updatedScore,
helper = helper
)
}
}
if (helper) {
openValves(
currentScore = currentScore,
valve = initialValve,
paths = paths,
visited = visited,
scores = scores,
maxTime = maxTime
)
}
return scores
}
return openValves(
valve = initialValve,
paths = paths,
maxTime = maxTime,
helper = helper
).max()
}
private fun canVisitNode(
valve: Valve,
visited: Set<Valve>,
travelTime: Int,
currentTime: Int,
maxTime: Int
) : Boolean {
return !visited.contains(valve) && currentTime + travelTime + 1 < maxTime
}
private fun calculateScore(
valve: Valve,
currentScore: Int,
travelTime: Int,
currentTime: Int,
maxTime: Int
) : Int {
return currentScore + (maxTime - currentTime - travelTime - 1) * valve.flowRate
}
// https://www.programiz.com/dsa/floyd-warshall-algorithm
fun getPaths(valves: List<ValveInput>): Map<Valve, MutableMap<Valve, Int>> {
val paths = buildMap {
valves.forEach { valve ->
put(Valve(valve.label, valve.flowRate), buildMap {
valve.leadsTo.forEach { leadTo ->
put(Valve(leadTo, valves.first { valve -> valve.label == leadTo }.flowRate), 1)
}
}.toMutableMap())
}
}
paths.keys.forEach { i ->
paths.keys.forEach { j ->
paths.keys.forEach { k ->
val ji = paths.get(j)?.get(i) ?: 9999
val ik = paths.get(i)?.get(k) ?: 9999
val jk = paths.get(j)?.get(k) ?: 9999
if (ji + ik < jk) {
paths.get(j)?.set(k, ji + ik)
}
}
}
}
paths.forEach { (_, path) ->
val keep = path.filterKeys { key -> valves.first { valve -> valve.label == key.label }.flowRate > 0 }
path.clear()
path.putAll(keep)
}
return paths
}
private fun valves(input: List<String>) : List<ValveInput> {
return input.map { line ->
val (valve, tunnels) = line.split(";")
val label = valve.substring(6, 8)
val flowRate = valve.substring(valve.indexOf('=') + 1).toInt()
val leadsTo = tunnels.filter { c -> c.isUpperCase() || c == ',' }.split(",")
ValveInput(
label = label,
flowRate = flowRate,
leadsTo = leadsTo
)
}
}
}
data class ValveInput(
val label: String,
val leadsTo: List<String>,
val flowRate: Int
)
data class Valve(
val label: String,
val flowRate: Int
) {
override fun toString(): String {
return label
}
}
| 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 5,790 | advent-of-code | Apache License 2.0 |
src/main/kotlin/solutions/day15/Day15.kt | Dr-Horv | 112,381,975 | false | null | package solutions.day15
import solutions.Solver
import utils.splitAtWhitespace
class Generator(private var value: Long, private val factor: Int, private val divisableBy: Int) {
fun next(): Long {
while(true) {
value = (value * factor) % 2147483647
if(value % divisableBy == 0L) {
return value
}
}
}
}
fun Long.toBinaryString(): String {
val s = java.lang.Long.toBinaryString(this)
return if(s.length < 16) {
s.padStart(16, '0')
} else {
s
}
}
class Day15: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val generators = input
.map(String::splitAtWhitespace)
.mapIndexed {index, list ->
when(index) {
0 -> when(partTwo) {
true -> Generator(list.last().toLong(), 16807, 4)
false -> Generator(list.last().toLong(), 16807, 1)
}
1 -> when(partTwo) {
true -> Generator(list.last().toLong(), 48271, 8)
false -> Generator(list.last().toLong(), 48271, 1)
}
else -> throw RuntimeException("Invalid index")
}
}
var count = 0
val iterations = if(partTwo) {
5_000_000
} else {
40_000_000
}
for (i in 1..iterations) {
val (a, b) = generators
.map(Generator::next)
val aStr = a.toBinaryString()
val bStr = b.toBinaryString()
val first = aStr.substring(aStr.length - 16)
val second = bStr.substring(bStr.length - 16)
if(first == second) {
count++
}
}
return count.toString()
}
} | 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 1,952 | Advent-of-Code-2017 | MIT License |
2021/src/main/kotlin/com/trikzon/aoc2021/Day2.kt | Trikzon | 317,622,840 | false | {"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397} | package com.trikzon.aoc2021
fun main() {
val input = getInputStringFromFile("/day2.txt")
benchmark(Part.One, ::dayTwoPartOne, input, 2039912, 50000)
benchmark(Part.Two, ::dayTwoPartTwo, input, 1942068080, 50000)
}
fun dayTwoPartOne(input: String): Int {
val commands = input.lines().map { line ->
val words = line.split(' ')
Pair(words[0], words[1].toInt())
}
var horizontalPosition = 0
var depth = 0
commands.forEach { command ->
when (command.first) {
"forward" -> horizontalPosition += command.second
"down" -> depth += command.second
"up" -> depth -= command.second
}
}
return horizontalPosition * depth
}
fun dayTwoPartTwo(input: String): Int {
val commands = input.lines().map { line ->
val words = line.split(' ')
Pair(words[0], words[1].toInt())
}
var horizontalPosition = 0
var depth = 0
var aim = 0
commands.forEach { command ->
when (command.first) {
"down" -> aim += command.second
"up" -> aim -= command.second
"forward" -> {
horizontalPosition += command.second
depth += command.second * aim
}
}
}
return horizontalPosition * depth
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 1,315 | advent-of-code | MIT License |
src/main/kotlin/CitiesAndDistances.kt | thomasnield | 136,809,665 | false | {"Kotlin": 25034} | import java.util.concurrent.ThreadLocalRandom
data class CityPair(val city1: Int, val city2: Int)
class City(val id: Int, val name: String, val x: Double, val y: Double) {
override fun toString() = name
fun distanceTo(other: City) =CitiesAndDistances.distances[CityPair(id, other.id)]?:0.0
}
object CitiesAndDistances {
val citiesById = CitiesAndDistances::class.java.getResource("cities.csv").readText().lines()
.asSequence()
.map { it.split(",") }
.map { City(it[0].toInt(), it[1], it[2].toDouble(), it[3].toDouble()) }
.map { it.id to it }
.toMap()
val citiesByString = citiesById.entries.asSequence()
.map { it.value.name to it.value }
.toMap()
val cities = citiesById.values.toList()
val distances = CitiesAndDistances::class.java.getResource("distances.csv").readText().lines()
.asSequence()
.map { it.split(",") }
.map { CityPair(it[0].toInt(), it[1].toInt()) to it[2].toDouble() }
.toMap()
val distancesByStartCityId = distances.entries.asSequence()
.map { it.key.city1 to (cities[it.key.city2] to it.value) }
.groupBy({it.first},{it.second})
val randomCity get() = ThreadLocalRandom.current().nextInt(0,CitiesAndDistances.cities.count()).let { CitiesAndDistances.cities[it] }
}
operator fun Map<CityPair,String>.get(city1: Int, city2: Int) = get(CityPair(city1,city2))
operator fun Map<CityPair,String>.get(city1: City, city2: City) = get(CityPair(city1.id,city2.id))
| 2 | Kotlin | 25 | 60 | f6d20984b311f59fe3221f170bc55cfc9eb3097e | 1,575 | traveling_salesman_demo | Apache License 2.0 |
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/ds/BTree.kt | nalinchhajer1 | 534,780,196 | false | {"Kotlin": 86359, "Ruby": 1605} | package com.nalin.datastructurealgorithm.ds
import kotlin.math.abs
import kotlin.math.max
interface BTree<out T> {
fun root(): BTreeNode<T>?
}
interface BTreeNode<out T> {
fun value(): T
fun leftNode(): BTreeNode<T>?
fun rightNode(): BTreeNode<T>?
}
interface BSTTree<T : Comparable<T>> : BTree<T> {
fun insert(value: T)
}
fun <T : Comparable<T>> BTree<T>.search(value: T): Boolean {
return find(value) != null
}
fun <T : Comparable<T>> BTree<T>.find(value: T): BTreeNode<T>? {
var traverseNode: BTreeNode<T>? = root()
while (traverseNode != null) {
if (value == traverseNode.value()) {
return traverseNode;
}
traverseNode = if (value < traverseNode.value()) {
traverseNode.leftNode()
} else {
traverseNode.rightNode()
}
}
return null
}
/**
* Check if given tree hold BST property and it is balanced
*/
fun <T : Comparable<T>> BTree<T>.isBST(): Boolean {
return root()?.isBST() ?: true
}
fun <T : Comparable<T>> BTree<T>.height(): Int {
return root()?.height() ?: 0
}
fun <T> BTree<T>.isBalanced(): Boolean {
return root()?.isBalanced() ?: true
}
fun <T : Comparable<T>> BTree<T>.isBalancedBST(): Boolean {
return isBST() && isBalanced()
}
/**
* return array of distinct node value
*/
fun <T> BTreeNode<T>.treeTraversalLTR(): List<T> {
val array = mutableListOf<T>()
fun _traversal(node: BTreeNode<T>?) {
if (node?.value() == null) return
_traversal(node.leftNode())
array.add(node.value()!!)
_traversal(node.rightNode())
}
_traversal(this)
return array
}
/**
* return min of node, or null
*/
fun <T> BTreeNode<T>.min(): T? {
var traverseNode: BTreeNode<T>? = this;
while (traverseNode?.leftNode() != null) {
traverseNode = traverseNode.leftNode()
}
return traverseNode?.value()
}
/**
* return min of node, or null
*/
fun <T> BTreeNode<T>.max(): T? {
var traverseNode: BTreeNode<T>? = this;
while (traverseNode?.rightNode() != null) {
traverseNode = traverseNode.rightNode()
}
return traverseNode?.value()
}
/**
* Depth of tree
*/
fun <T> BTreeNode<T>.height(): Int {
return max((leftNode()?.height() ?: 0), (rightNode()?.height() ?: 0)) + 1
}
/**
* Check if inorder traversal is in sorted order
*/
fun <T : Comparable<T>> BTreeNode<T>.isBST(): Boolean {
var lastVisit: T? = null
fun _traversal(node: BTreeNode<T>?): Boolean {
if (node == null) return true
if (!_traversal(node.leftNode())) {
return false
}
if (lastVisit != null && lastVisit!! > node.value()) {
return false
}
lastVisit = node.value()
return _traversal(node.rightNode())
}
return _traversal(this)
}
/**
* Check if given tree is balanced
*/
fun <T> BTreeNode<T>.isBalanced(): Boolean {
return checkBalance() >= 0
}
/**
* use height logic to check balance, if balance failed, avoid computation and return -1, else return height
*/
private fun <T> BTreeNode<T>.checkBalance(): Int {
val lh: Int = leftNode()?.checkBalance() ?: 0
if (lh == -1) {
return -1
}
val rh: Int = rightNode()?.checkBalance() ?: 0
if (rh == -1) {
return -1
}
if (abs(lh - rh) > 1) {
return -1;
}
return max(lh, rh) + 1
}
class ArrayTree<T>(array: Array<T?>) : BTree<T> {
var root: ArrayTreeNode<T>? = null
var size: Int = 0
init {
fun _createTreeNode(rootNode: BTreeNode<T>?, index: Int): ArrayTreeNode<T>? {
if (index < array.size && array[index] != null) {
val node = ArrayTreeNode<T>(array[index]!!)
size++
node.leftNode = _createTreeNode(rootNode, ArrayTreeNode.leftChildIndex(index))
node.rightNode = _createTreeNode(rootNode, ArrayTreeNode.leftChildIndex(index) + 1)
return node
}
return null
}
root = _createTreeNode(null, 0)
}
override fun root(): ArrayTreeNode<T>? {
return root
}
fun size(): Int {
return size
}
}
class ArrayTreeNode<T>(
value: T,
var leftNode: ArrayTreeNode<T>? = null,
var rightNode: ArrayTreeNode<T>? = null
) : BTreeNode<T> by TreeNodeImpl(value) {
companion object {
fun leftChildIndex(index: Int): Int {
return (index shl 1) or 1
}
}
override fun leftNode(): ArrayTreeNode<T>? {
return leftNode
}
override fun rightNode(): ArrayTreeNode<T>? {
return rightNode
}
}
class TreeNodeImpl<T>(
var value: T,
var leftNode: TreeNodeImpl<T>? = null,
var rightNode: TreeNodeImpl<T>? = null
) : BTreeNode<T> {
override fun value(): T {
return value
}
override fun leftNode(): TreeNodeImpl<T>? {
return leftNode
}
override fun rightNode(): TreeNodeImpl<T>? {
return rightNode
}
}
| 0 | Kotlin | 0 | 0 | eca60301dab981d0139788f61149d091c2c557fd | 5,016 | kotlin-ds-algo | MIT License |
04 - Kotlin/4.kt | Ciremun | 318,207,178 | false | {"C": 9212, "C++": 7831, "Crystal": 5319, "Python": 4909, "Kotlin": 3585, "Ruby": 3297, "TypeScript": 2631, "Rust": 2560, "Nim": 2134, "Scala": 1408, "C#": 980, "Haskell": 596} | import java.io.File
fun is_valid_hex_char(c: String): Boolean {
val c_int: Int? = c.toIntOrNull()
if (c_int is Int)
return 0 <= c_int && c_int <= 9
return listOf("a", "b", "c", "d", "e", "f").contains(c)
}
fun is_valid_field_hair(pd_value: String): Boolean {
val pd_hash: String = pd_value.substring(0, 1)
val pd_values: String = pd_value.substring(1, 7)
if (pd_hash == "#" && pd_values.length == 6 && pd_values.all{ is_valid_hex_char(it.toString()) })
return true
return false
}
fun is_valid_field_height(pd_value: String): Boolean {
if (pd_value.endsWith("cm") && is_valid_field_range(pd_value.substring(0, 3), 150, 193))
return true
if (pd_value.endsWith("in") && is_valid_field_range(pd_value.substring(0, 2), 59, 76))
return true
return false
}
fun is_valid_field_range(pd_value: String, x: Int, y: Int): Boolean {
val pd_int: Int? = pd_value.toIntOrNull()
return pd_int is Int && (x <= pd_int && pd_int <= y)
}
fun is_valid_passport(pd: MutableMap<String, String>, puzzle_part: Int): Boolean {
if (puzzle_part == 1) return pd.all{ (k, v) -> k == "cid" || listOf("byr","iyr","eyr","hgt","hcl","ecl","pid").contains(k) && !v.isEmpty() }
for (i in pd.keys) {
if (i == "cid") continue
val pd_value: String? = pd.get(i)
if (pd_value is String && !pd_value.isEmpty()) {
when (i) {
"byr" -> if (pd_value.length != 4 || !is_valid_field_range(pd_value, 1920, 2002)) return false
"iyr" -> if (pd_value.length != 4 || !is_valid_field_range(pd_value, 2010, 2020)) return false
"eyr" -> if (pd_value.length != 4 || !is_valid_field_range(pd_value, 2020, 2030)) return false
"hgt" -> if (pd_value.length <= 3 || !is_valid_field_height(pd_value)) return false
"hcl" -> if (pd_value.length != 7 || !is_valid_field_hair(pd_value)) return false
"ecl" -> if (pd_value.length != 3 || !listOf("amb","blu","brn","gry","grn","hzl","oth").contains(pd_value)) return false
"pid" -> if (pd_value.length != 9 || !pd_value.all{ it.toString().toIntOrNull() is Int }) return false
}
}
else return false
}
return true
}
fun main() {
val inp: String = File("input.txt").readText() + "\n"
val lines: List<String> = inp.split("\n").map{ it.trim() }
val passports: MutableList<String> = mutableListOf()
var passport_str: String = ""
var valid_passports_p1: Int = 0
var valid_passports_p2: Int = 0
for (line in lines) {
if (line.isEmpty()) {
passports.add(passport_str)
passport_str = ""
continue
}
if (passport_str.isEmpty()) passport_str = line
else passport_str = "$passport_str $line"
}
for (passport in passports) {
val pd: MutableMap<String, String> = mutableMapOf(
"byr" to "", "iyr" to "", "eyr" to "",
"hgt" to "", "hcl" to "", "ecl" to "",
"pid" to "", "cid" to "")
val field_pairs: List<String> = passport.split(" ")
for (pair in field_pairs) {
val pair_split: List<String> = pair.split(":")
val field_key: String = pair_split[0]
val field_val: String = pair_split[1]
pd.put(field_key, field_val)
}
if (is_valid_passport(pd, 1)) valid_passports_p1++
if (is_valid_passport(pd, 2)) valid_passports_p2++
}
println("pt.1: $valid_passports_p1")
println("pt.2: $valid_passports_p2")
}
| 0 | C | 0 | 1 | 05789c51a3c05040b93e5d943c5eb68c9b3d989b | 3,585 | AOC-2020 | MIT License |
src/exercises/Day07.kt | Njko | 572,917,534 | false | {"Kotlin": 53729} | // ktlint-disable filename
package exercises
import readInput
// https://www.kodeco.com/books/data-structures-algorithms-in-kotlin/v1.0/chapters/6-trees
sealed class Node {
data class Folder(val name: String, val children: MutableList<Node> = mutableListOf()) : Node()
data class File(val name: String, val size: Int) : Node()
}
fun Node.Folder.add(child: Node) = this.children.add(child)
// https://www.youtube.com/watch?v=Q819VW8yxFo&t=2090s
fun main() {
fun part1(input: List<String>): Int {
/*var startRecording = false
var currentDirectory = ""
var root = Node.Folder("/")
input.forEach { line ->
if (line.startsWith("$ cd ")) {
startRecording = false
currentDirectory = line.last().toString()
// read directory move
return@forEach
}
if (line.startsWith("ls")) {
startRecording = true
return@forEach
}
if (startRecording) {
}
}*/
val root = Node.Folder("/").apply {
add(
Node.Folder("a").apply {
add(
Node.Folder("e").apply {
add(Node.File("i", 584))
}
)
add(Node.File("f", 29116))
add(Node.File("g", 2557))
add(Node.File("h.lst", 62596))
}
)
add(Node.File("b.txt", 14848514))
add(Node.File("c.dat", 8504156))
add(
Node.Folder("d").apply {
add(Node.File("j", 4060174))
add(Node.File("d.log", 8033020))
add(Node.File("d.ext", 5626152))
add(Node.File("k", 7214296))
}
)
}
val folders = root.children.filterIsInstance<Node.Folder>().toList()
println("$root")
println("$folders")
return input.size
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
println("Test results:")
println(part1(testInput))
check(part1(testInput) == 23)
println(part2(testInput))
check(part2(testInput) == 23)
val input = readInput("Day07")
println("Final results:")
println(part1(input))
check(part1(input) == 1046)
println(part2(input))
check(part2(input) == 1046)
}
| 0 | Kotlin | 0 | 2 | 68d0c8d0bcfb81c183786dfd7e02e6745024e396 | 2,606 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day15.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
import com.akikanellis.adventofcode.year2022.utils.Point
import kotlin.math.abs
object Day15 {
private val SENSORS_TO_BEACONS_REGEX =
"Sensor at x=(.+), y=(.+): closest beacon is at x=(.+), y=(.+)".toRegex()
private const val DISTRESS_BEACON_MIN_COORDINATE = 0
private const val TUNING_FREQUENCY_MULTIPLIER = 4_000_000
fun numberOfPositionsWithoutBeacon(input: String, targetRow: Int): Int {
val sensorsToClosestBeacons = sensorsToClosestBeacons(input)
val pointsWithoutABeaconInRow = mutableSetOf<Point>()
val beaconsInRow = mutableSetOf<Point>()
for ((sensor, closestBeacon) in sensorsToClosestBeacons) {
if (closestBeacon.y == targetRow) beaconsInRow += closestBeacon
val sensorToBeaconDistance = sensor.manhattanDistance(closestBeacon)
val xOffset = sensorToBeaconDistance - abs(sensor.y - targetRow)
(sensor.x - xOffset..sensor.x + xOffset).forEach { x ->
pointsWithoutABeaconInRow += Point(x, targetRow)
}
}
return pointsWithoutABeaconInRow.size - beaconsInRow.size
}
fun tuningFrequencyOfDistressBeacon(input: String, distressBeaconMaxCoordinate: Int): Long {
val sensorsToClosestBeacons = sensorsToClosestBeacons(input)
for (y in DISTRESS_BEACON_MIN_COORDINATE..distressBeaconMaxCoordinate) {
var x = DISTRESS_BEACON_MIN_COORDINATE
while (x <= distressBeaconMaxCoordinate) {
val candidateDistressBeacon = Point(x, y)
val xAfterSkippingPointsWithoutBeacon = xAfterSkippingPointsWithoutBeacon(
sensorsToClosestBeacons,
candidateDistressBeacon
)
if (xAfterSkippingPointsWithoutBeacon != null) {
x = xAfterSkippingPointsWithoutBeacon
} else {
return (candidateDistressBeacon.x.toLong() * TUNING_FREQUENCY_MULTIPLIER) +
candidateDistressBeacon.y
}
}
}
error("Could not find distress beacon")
}
private fun sensorsToClosestBeacons(input: String) = input.lines()
.filter { it.isNotBlank() }
.map { line ->
val coordinates = SENSORS_TO_BEACONS_REGEX.matchEntire(line)!!.groupValues
Pair(
Point(coordinates[1].toInt(), coordinates[2].toInt()),
Point(coordinates[3].toInt(), coordinates[4].toInt())
)
}
private fun xAfterSkippingPointsWithoutBeacon(
sensorsToClosestBeacons: List<Pair<Point, Point>>,
candidateDistressBeacon: Point
): Int? = sensorsToClosestBeacons
.firstOrNull { (sensor, closestBeacon) ->
sensor.manhattanDistance(closestBeacon) >=
sensor.manhattanDistance(candidateDistressBeacon)
}?.let { (sensor, closestBeacon) ->
sensor.x +
sensor.manhattanDistance(closestBeacon) -
abs(sensor.y - candidateDistressBeacon.y) +
1
}
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 3,160 | advent-of-code | MIT License |
src/aoc2022/Day06.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import println
import readInput
fun main() {
fun part1(input: List<String>): Int {
val seq = input[0]
val occur = mutableMapOf<Char, Int>()
for (i in 0 until seq.length) {
if (i > 3) {
val char = seq.get(i - 4)
val count = occur.getValue(char)
if (count == 1) occur.remove(char)
else occur.put(char, count - 1)
}
occur.compute(seq.get(i)) { k, v -> (v?:0) + 1 };
if (occur.size == 4)
return i + 1
}
return 0
}
fun part2(input: List<String>): Int {
val seq = input[0]
val occur = mutableMapOf<Char, Int>()
for (i in 0 until seq.length) {
if (i > 13) {
val char = seq.get(i - 14)
val count = occur.getValue(char)
if (count == 1) occur.remove(char)
else occur.put(char, count - 1)
}
occur.compute(seq.get(i)) { k, v -> (v?:0) + 1 };
if (occur.size == 14)
return i + 1
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 10)
check(part2(testInput) == 29)
val input = readInput("Day06")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 1,428 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NearestExit.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 1926. Nearest Exit from Entrance in Maze
* @see <a href="https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/">Source</a>
*/
fun interface NearestExit {
operator fun invoke(maze: Array<CharArray>, entrance: IntArray): Int
}
/**
* Approach 1: Breadth First Search (BFS)
*/
class NearestExitBFS : NearestExit {
override operator fun invoke(maze: Array<CharArray>, entrance: IntArray): Int {
val rows: Int = maze.size
val cols: Int = maze[0].size
val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1))
// Mark the entrance as visited since it's not an exit.
val startRow = entrance[0]
val startCol = entrance[1]
maze[startRow][startCol] = '+'
// Start BFS from the entrance, and use a queue `queue` to store all
// the cells to be visited.
val queue: Queue<IntArray> = LinkedList()
queue.offer(intArrayOf(startRow, startCol, 0))
while (queue.isNotEmpty()) {
val currState: IntArray = queue.poll()
val currRow = currState[0]
val currCol = currState[1]
val currDistance = currState[2]
// For the current cell, check its four neighbor cells.
for (dir in dirs) {
val nextRow = currRow + dir[0]
val nextCol = currCol + dir[1]
// If there exists an unvisited empty neighbor:
if (nextRow in 0 until rows && 0 <= nextCol && nextCol < cols && maze[nextRow][nextCol] == '.') {
// If this empty cell is an exit, return distance + 1.
if (nextRow == 0 || nextRow == rows - 1 || nextCol == 0 || nextCol == cols - 1) {
return currDistance + 1
}
// Otherwise, add this cell to 'queue' and mark it as visited.
maze[nextRow][nextCol] = '+'
queue.offer(intArrayOf(nextRow, nextCol, currDistance + 1))
}
}
}
// If we finish iterating without finding an exit, return -1.
return -1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,865 | kotlab | Apache License 2.0 |
src/Day01.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | fun main() {
fun part1(input: List<Int>): Int {
return input.max()
}
fun part2(input: List<Int>): Int {
return input.sortedDescending().subList(0, 3).sum()
}
fun computeCaloriesForElves(input: List<String>): List<Int> {
var curVal = 0
val output = mutableListOf<Int>()
for (row in input) {
val rowAsInt = row.toIntOrNull()
if (rowAsInt != null) {
curVal += rowAsInt
} else {
output.add(curVal)
curVal = 0
}
}
output.add(curVal)
return output
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
val testCalories = computeCaloriesForElves(testInput)
check(part1(testCalories) == 6000)
check(part2(testCalories) == 10000)
val input = readInput("Day01_input")
val inputCalories = computeCaloriesForElves(input)
println(part1(inputCalories))
println(part2(inputCalories))
}
| 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 1,052 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem2391/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2391
/**
* LeetCode page: [2391. Minimum Amount of Time to Collect Garbage](https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/);
*/
class Solution {
/* Complexity:
* Time O(L) and Space O(1) where L id the flattened length of garbage;
*/
fun garbageCollection(garbage: Array<String>, travel: IntArray): Int {
val pickUpTime = garbage.sumOf { it.length }
val truckTypes = charArrayOf('M', 'P', 'G')
val finalPositions = truckTypes.map { type ->
garbage
.indexOfLast { assortment -> assortment.contains(type) }
.coerceAtLeast(0)
}
return pickUpTime + travelTime(finalPositions, travel)
}
private fun travelTime(finalPositions: List<Int>, travel: IntArray): Int {
val sortedPositions = finalPositions.sorted()
var result = 0
for (index in sortedPositions.indices) {
val routeStart = sortedPositions.getOrElse(index - 1) { 0 }
val routeEnd = sortedPositions[index]
val routeTravelTime = (routeStart..<routeEnd).sumOf { travel[it] }
val travellingTrucks = sortedPositions.size - index
result += routeTravelTime * travellingTrucks
}
return result
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,322 | hj-leetcode-kotlin | Apache License 2.0 |
src/commonMain/kotlin/io/github/alexandrepiveteau/graphs/algorithms/ParentsMap.kt | alexandrepiveteau | 630,931,403 | false | {"Kotlin": 132267} | package io.github.alexandrepiveteau.graphs.algorithms
import io.github.alexandrepiveteau.graphs.*
import io.github.alexandrepiveteau.graphs.builder.buildDirectedNetwork
import io.github.alexandrepiveteau.graphs.internal.collections.IntDequeue
/**
* Returns the [VertexArray] containing all the vertices traversed to go from the [from] vertex to
* the [to] vertex, using the given [parents] map.
*
* @param parents the map containing the parents of each vertex.
* @param from the starting vertex.
* @param to the ending vertex.
* @return the [VertexArray] containing all the vertices traversed to go from the [from] vertex to
* the [to] vertex.
* @receiver the [Graph] on which the traversal was performed.
*/
internal fun <G> G.computePath(
parents: VertexMap,
from: Vertex,
to: Vertex,
): VertexArray? where G : VertexSet {
if (from == Vertex.Invalid) throw IllegalArgumentException()
if (to == Vertex.Invalid) throw IllegalArgumentException()
val path = IntDequeue()
var current = to
while (current != from) {
if (current == Vertex.Invalid) return null
path.addFirst(index(current))
current = parents[current]
}
path.addFirst(index(from))
return VertexArray(path.toIntArray())
}
/**
* Returns the [DirectedNetwork] for the subgraph of this [Network] defined by the [parents] map.
*
* @param parents the [VertexMap] that maps each vertex to its parent in the shortest path tree.
* @return the [DirectedNetwork] for the subgraph of this [Network] defined by the [parents] map.
* @receiver the [Network] to transform.
*/
internal fun <N> N.computeNetwork(
parents: VertexMap,
): DirectedNetwork where N : SuccessorsWeight {
return buildDirectedNetwork {
forEachVertex { addVertex() }
parents.forEach { vertex, parent ->
if (parent != Vertex.Invalid) {
addArc(parent arcTo vertex, successorWeight(parent, vertex))
}
}
}
}
| 9 | Kotlin | 0 | 6 | a4fd159f094aed5b6b8920d0ceaa6a9c5fc7679f | 1,921 | kotlin-graphs | MIT License |
src/main/kotlin/com/groundsfam/advent/y2015/d03/Day03.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2015.d03
import com.groundsfam.advent.DATAPATH
import kotlin.io.path.div
import kotlin.io.path.useLines
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
}
fun partOne(directions: List<Direction>): Int {
var position = 0 to 0
val visited = mutableSetOf(position)
directions.forEach { direction ->
position = when (direction) {
Direction.UP -> position.copy(first = position.first + 1)
Direction.DOWN -> position.copy(first = position.first - 1)
Direction.LEFT -> position.copy(second = position.second - 1)
Direction.RIGHT -> position.copy(second = position.second + 1)
}
visited.add(position)
}
return visited.size
}
fun partTwo(directions: List<Direction>): Int {
val positions = Array(2) { 0 to 0 }
val visited = mutableSetOf(positions[0])
directions.forEachIndexed { index, direction ->
val i = index % 2
positions[i] = positions[i].let {
when (direction) {
Direction.UP -> it.copy(first = it.first + 1)
Direction.DOWN -> it.copy(first = it.first - 1)
Direction.LEFT -> it.copy(second = it.second - 1)
Direction.RIGHT -> it.copy(second = it.second + 1)
}
}
visited.add(positions[i])
}
return visited.size
}
fun main() {
val directions = (DATAPATH / "2015/day03.txt").useLines { lines ->
lines.first().map { c ->
when (c) {
'^' -> Direction.DOWN
'v' -> Direction.UP
'<' -> Direction.LEFT
'>' -> Direction.RIGHT
else -> throw RuntimeException("Invalid character: $c")
}
}
}
println("Part one: ${partOne(directions)}")
println("Part two: ${partTwo(directions)}")
} | 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,883 | advent-of-code | MIT License |
src/main/kotlin/com/jaspervanmerle/aoc2020/day/Day12.kt | jmerle | 317,518,472 | false | null | package com.jaspervanmerle.aoc2020.day
import kotlin.math.abs
class Day12 : Day("1589", "23960") {
private data class Instruction(val action: Char, val value: Int)
private enum class Direction(val xModifier: Int, val yModifier: Int) {
NORTH(0, 1),
EAST(1, 0),
SOUTH(0, -1),
WEST(-1, 0);
}
private abstract class Ship(var x: Int, var y: Int) {
abstract fun applyInstruction(instruction: Instruction)
fun getManhattanDistance(): Int {
return abs(x) + abs(y)
}
}
private class SimpleShip(x: Int, y: Int, var direction: Direction) : Ship(x, y) {
override fun applyInstruction(instruction: Instruction) {
when (instruction.action) {
'N' -> y += instruction.value
'S' -> y -= instruction.value
'E' -> x += instruction.value
'W' -> x -= instruction.value
'L' -> rotate(-1 * (instruction.value / 90))
'R' -> rotate(instruction.value / 90)
'F' -> {
x += direction.xModifier * instruction.value
y += direction.yModifier * instruction.value
}
}
}
private fun rotate(steps: Int) {
val directions = Direction.values()
direction = directions[Math.floorMod(direction.ordinal + steps, directions.size)]
}
override fun toString(): String {
return "SimpleShip(x=$x, y=$y, direction=$direction)"
}
}
private class AdvancedShip(x: Int, y: Int, var waypointX: Int, var waypointY: Int) : Ship(x, y) {
override fun applyInstruction(instruction: Instruction) {
when (instruction.action) {
'N' -> waypointY += instruction.value
'S' -> waypointY -= instruction.value
'E' -> waypointX += instruction.value
'W' -> waypointX -= instruction.value
'L' -> rotate(-instruction.value)
'R' -> rotate(instruction.value)
'F' -> {
x += waypointX * instruction.value
y += waypointY * instruction.value
}
}
}
fun rotate(degrees: Int) {
val rotations = mapOf(
0 to (waypointX to waypointY),
90 to (waypointY to -waypointX),
180 to (-waypointX to -waypointY),
270 to (-waypointY to waypointX)
)
val newWaypoint = rotations[(degrees + 360) % 360]!!
waypointX = newWaypoint.first
waypointY = newWaypoint.second
}
override fun toString(): String {
return "AdvancedShip(x=$x, y=$y, waypointX=$waypointX, waypointY=$waypointY)"
}
}
private val instructions = getInput()
.lines()
.map { Instruction(it[0], it.substring(1).toInt()) }
override fun solvePartOne(): Any {
val ship = SimpleShip(0, 0, Direction.EAST)
for (instruction in instructions) {
ship.applyInstruction(instruction)
}
return ship.getManhattanDistance()
}
override fun solvePartTwo(): Any {
val ship = AdvancedShip(0, 0, 10, 1)
for (instruction in instructions) {
ship.applyInstruction(instruction)
}
return ship.getManhattanDistance()
}
}
| 0 | Kotlin | 0 | 0 | 81765a46df89533842162f3bfc90f25511b4913e | 3,457 | advent-of-code-2020 | MIT License |
src/main/kotlin/week5/TicTacToe.kt | doertscho | 305,730,136 | false | null | package week5
import week5.players.ValidMovePlayer
fun winner(state: State): Symbol? {
val field = state.field
val triples = listOf(
// rows
listOf(field[0][0], field[0][1], field[0][2]),
listOf(field[1][0], field[1][1], field[1][2]),
listOf(field[2][0], field[2][1], field[2][2]),
// columns
listOf(field[0][0], field[1][0], field[2][0]),
listOf(field[0][1], field[1][1], field[2][1]),
listOf(field[0][2], field[1][2], field[2][2]),
// diagonals
listOf(field[0][0], field[1][1], field[2][2]),
listOf(field[0][2], field[1][1], field[2][0])
)
for (triple in triples) {
if (
(triple[0] != null) &&
(triple[0] == triple[1]) &&
(triple[0] == triple[2])
) {
return triple[0]
}
}
return null
}
fun isValidMove(state: State, move: Move): Boolean =
state.field[move.row][move.column] == null
fun validMoveIsPossible(state: State): Boolean {
for (row in 0 .. 2) {
for (column in 0 ..2) {
if (state.field[row][column] == null) {
return true
}
}
}
return false
}
fun runGame(state: State, players: Map<Symbol, Player>) {
while (winner(state) == null && validMoveIsPossible(state)) {
val playerSymbol = state.nextPlayerSymbol
val player = players[playerSymbol] ?: error("player $playerSymbol not available")
val nextMove = player.nextMove(state)
if (!isValidMove(state, nextMove)) {
error("invalid move from $playerSymbol: $nextMove")
}
state.field[nextMove.row][nextMove.column] = playerSymbol
state.nextPlayerSymbol = state.nextPlayerSymbol.other()
}
val winner = winner(state)
println("$winner wins the game!")
}
fun main() {
val state = State()
val players: Map<Symbol, Player> = mapOf<Symbol, Player>(
Symbol.X to ValidMovePlayer(),
Symbol.O to ValidMovePlayer(),
)
runGame(state, players)
}
| 0 | Kotlin | 0 | 0 | c84e8b0341fae1b5384fce52fcedf660e54b11f5 | 2,137 | software-ag-kks | MIT License |
src/Day03.kt | cerberus97 | 579,910,396 | false | {"Kotlin": 11722} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { items ->
val sz = items.length
val firstHalf = items.substring(0, sz / 2).toSet()
val secondHalf = items.substring(sz / 2, sz).toSet()
val common = firstHalf.intersect(secondHalf).single()
if (common.isLowerCase()) (common - 'a' + 1) else (common - 'A' + 27)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { itemGroup ->
val itemSets = itemGroup.map { items -> items.toSet() }
val common = itemSets[0].intersect(itemSets[1]).intersect(itemSets[2]).single()
if (common.isLowerCase()) (common - 'a' + 1) else (common - 'A' + 27)
}
}
val input = readInput("in")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | ed7b5bd7ad90bfa85e868fa2a2cdefead087d710 | 783 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/boj_2206/Kotlin.kt | devetude | 70,114,524 | false | {"Java": 564034, "Kotlin": 80457} | package boj_2206
import java.util.LinkedList
import java.util.StringTokenizer
val DIRECTIONS = arrayOf(arrayOf(0, 1), arrayOf(0, -1), arrayOf(1, 0), arrayOf(-1, 0))
fun main() {
val st = StringTokenizer(readln())
val n = st.nextToken().toInt()
val m = st.nextToken().toInt()
val map = Array(size = n + 1) { CharArray(size = m + 1) }
for (row in 1..n) {
val input = readln()
for (col in 1..m) {
map[row][col] = input[col - 1]
}
}
val startPoint = Point(row = 1, col = 1, depth = 1, hasBreakChance = true)
val queue = LinkedList<Point>()
queue.offer(startPoint)
val isVisited = Array(size = n + 1) { Array(size = m + 1) { BooleanArray(size = 2) } }
isVisited[1][1][0] = true
while (queue.isNotEmpty()) {
val point = queue.poll()
if (point.row == n && point.col == m) return println(point.depth)
val nextPoints = DIRECTIONS.asSequence()
.map { (rowDiff, colDiff) ->
val nextRow = point.row + rowDiff
val nextCol = point.col + colDiff
val nextDepth = point.depth + 1
Point(nextRow, nextCol, nextDepth, point.hasBreakChance)
}
.filter { it.row in 1..n && it.col in 1..m }
.toList()
nextPoints.forEach { nextPoint ->
if (map[nextPoint.row][nextPoint.col] == '0') {
if (nextPoint.hasBreakChance && !isVisited[nextPoint.row][nextPoint.col][0]) {
isVisited[nextPoint.row][nextPoint.col][0] = true
queue.offer(nextPoint)
} else if (!isVisited[nextPoint.row][nextPoint.col][1]) {
isVisited[nextPoint.row][nextPoint.col][1] = true
queue.offer(nextPoint)
}
} else {
if (nextPoint.hasBreakChance) {
isVisited[nextPoint.row][nextPoint.col][1] = true
queue.offer(nextPoint.copy(hasBreakChance = false))
}
}
}
}
println(-1)
}
data class Point(
val row: Int,
val col: Int,
val depth: Int,
val hasBreakChance: Boolean
)
| 0 | Java | 7 | 20 | 4c6acff4654c49d15827ef87c8e41f972ff47222 | 2,205 | BOJ-PSJ | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2022/Day05.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2022
import net.voldrich.BaseDay
import java.util.*
import kotlin.collections.ArrayList
// https://adventofcode.com/2022/day/5
fun main() {
Day05().run()
}
class Day05 : BaseDay() {
val instructionRegex = Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)")
override fun task1() : String {
val separator = input.getEmptyLineIndex()
val queues = parseQueues(separator)
for (i in separator + 1 until input.lines().size) {
val (count, from, to) = parseInstruction(i)
for (j in 0 until count) {
queues[to-1].addFirst(queues[from - 1].pop())
}
}
return queues.map { it.first }.joinToString("")
}
private fun parseQueues(separator: Int): ArrayList<LinkedList<Char>> {
val indexes = input.lines()[separator - 1].mapIndexedNotNull { index, c ->
if (c != ' ') {
index
} else {
null
}
}
val queues = ArrayList<LinkedList<Char>>(indexes.size)
for (i in indexes.indices) {
queues.add(LinkedList())
}
for (i in 0 until separator - 1) {
val line = input.lines()[i]
for (q in indexes.indices) {
val j = indexes[q]
if (j < line.length && line[j] != ' ') {
queues[q].add(line[j])
}
}
}
return queues
}
override fun task2() : String {
val separator = input.getEmptyLineIndex()
val queues = parseQueues(separator)
for (i in separator + 1 until input.lines().size) {
val (count, from, to) = parseInstruction(i)
val holder = LinkedList<Char>()
for (j in 0 until count) {
holder.addFirst(queues[from - 1].pop())
}
for (j in 0 until count) {
queues[to-1].addFirst(holder.pop())
}
}
return queues.map { it.first }.joinToString("")
}
private fun parseInstruction(i: Int): Triple<Int, Int, Int> {
val line = input.lines()[i]
val matches = instructionRegex.find(line)!!
val count = matches.groupValues[1].toInt()
val from = matches.groupValues[2].toInt()
val to = matches.groupValues[3].toInt()
return Triple(count, from, to)
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 2,414 | advent-of-code | Apache License 2.0 |
src/day2/Code.kt | fcolasuonno | 162,470,286 | false | null | package day2
import java.io.File
fun main(args: Array<String>) {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2(parsed)}")
}
data class Box(val l: Int, val w: Int, val h: Int) {
private val area = 2 * l * w + 2 * w * h + 2 * h * l
private val volume = h * l * w
private val smallestDim = listOf(l, w, h).sorted().take(2)
private val slack = smallestDim.reduce { a, b -> a * b }
val wrappingArea = area + slack
val ribbonLength = volume + smallestDim.sum() * 2
}
private val lineStructure = """(\d+)x(\d+)x(\d+)""".toRegex()
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val (l, w, h) = it.toList().map { it.toInt() }
Box(l, w, h)
}
}.requireNoNulls()
fun part1(input: List<Box>): Any? = input.sumBy { it.wrappingArea }
fun part2(input: List<Box>): Any? = input.sumBy { it.ribbonLength }
| 0 | Kotlin | 0 | 0 | 24f54bf7be4b5d2a91a82a6998f633f353b2afb6 | 1,099 | AOC2015 | MIT License |
src/main/kotlin/y2023/Day03.kt | jforatier | 432,712,749 | false | {"Kotlin": 44692} | package y2023
import common.Resources.splitOnEmpty
class Day03(private val data: List<String>) {
fun part1(): Int {
val digits = "\\d+".toRegex()
val partNumbers = mutableListOf<Int>()
data.forEachIndexed { row, s ->
val numbers = digits.findAll(s)
.map { it.range to it.value.toInt() }
.filter { (range, _) ->
val adjacentCells = (range.first - 1..range.last + 1).flatMap {
listOf(row - 1 to it, row to it, row + 1 to it)
}
adjacentCells.forEach { (x, y) ->
runCatching {
if (!data[x][y].isDigit() && data[x][y] != '.') return@filter true
}
}
false
}
partNumbers += numbers.map { it.second }
}
return partNumbers.sum()
}
fun part2(): Int {
val digits = "\\d+".toRegex()
val numbersWithCoordinates = data.flatMapIndexed { row, s ->
digits.findAll(s).map { (row to it.range) to it.value.toInt() }
}.toMap()
val gearRatios = mutableListOf<Int>()
data.forEachIndexed { row, s ->
val asteriskIndexes = s.mapIndexedNotNull { index: Int, c: Char -> if (c == '*') index else null }
asteriskIndexes.forEach { index ->
val adjacentNumbers = numbersWithCoordinates.filterKeys { (x, range) ->
x in row - 1..row + 1 && range.any { it in index - 1..index + 1 }
}
if (adjacentNumbers.values.size == 2) {
gearRatios += adjacentNumbers.values.fold(1) { acc, i -> i * acc }
}
}
}
return gearRatios.sum()
}
}
| 0 | Kotlin | 0 | 0 | 2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae | 1,841 | advent-of-code-kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ThreeEqualParts.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* 927. Three Equal Parts
* @see <a href="https://leetcode.com/problems/three-equal-parts/">Source</a>
*/
fun interface ThreeEqualParts {
operator fun invoke(arr: IntArray): IntArray
}
class EqualOnes : ThreeEqualParts {
private val impossible = intArrayOf(-1, -1)
override operator fun invoke(arr: IntArray): IntArray {
val n = arr.size
// Count how many 1s are in arr.
var totalOnes = 0
for (bit in arr) {
totalOnes += bit
}
// If total number of ones is not evenly divisible by 3, then no solution exists.
if (totalOnes % 3 != 0) {
return impossible
}
// Otherwise, each part should contain an equal amount of 1s.
val targetOnes = totalOnes / 3
if (targetOnes == 0) {
return intArrayOf(0, n - 1)
}
// i1, j1 marks the index of the first and last one in the first block of 1s, etc.
var i1 = -1
var j1 = -1
var i2 = -1
var j2 = -1
var i3 = -1
var j3 = -1
// Find the index of the first and last 1 in each block of ones.
var oneCount = 0
for (i in 0 until n) {
if (arr[i] == 1) {
oneCount += 1
if (oneCount == 1) i1 = i
if (oneCount == targetOnes) j1 = i
if (oneCount == targetOnes + 1) i2 = i
if (oneCount == 2 * targetOnes) j2 = i
if (oneCount == 2 * targetOnes + 1) i3 = i
if (oneCount == 3 * targetOnes) j3 = i
}
}
// The array is in the form W [i1, j1] X [i2, j2] Y [i3, j3] Z
// where each [i, j] is a block of 1s and W, X, Y, and Z represent blocks of 0s.
val part1: IntArray = arr.copyOfRange(i1, j1 + 1)
val part2: IntArray = arr.copyOfRange(i2, j2 + 1)
val part3: IntArray = arr.copyOfRange(i3, j3 + 1)
if (!part1.contentEquals(part2) || !part1.contentEquals(part3)) {
return impossible
}
// The number of zeros after the left, middle, and right parts
val trailingZerosLeft = i2 - j1 - 1
val trailingZerosMid = i3 - j2 - 1
val trailingZeros = n - j3 - 1
return if (trailingZeros > min(trailingZerosLeft, trailingZerosMid)) {
impossible
} else {
intArrayOf(j1 + trailingZeros, j2 + trailingZeros + 1)
}
}
}
class ThreeEqualPartsSimple : ThreeEqualParts {
override operator fun invoke(arr: IntArray): IntArray {
var numOne = 0
for (i in arr) {
if (i == 1) numOne++
}
val res = intArrayOf(-1, -1)
if (numOne == 0) return intArrayOf(0, 2) // special case
if (numOne % 3 != 0) return res
var thirdPartStartingIndex = 0
var count = 0
for (i in arr.indices.reversed()) {
if (arr[i] == 1 && ++count == numOne / 3) {
thirdPartStartingIndex = i
break
}
}
val firstPartEndIndex = findNextEndIndexAndCompare(arr, 0, thirdPartStartingIndex)
if (firstPartEndIndex < 0) return res
val secondPartEndIndex = findNextEndIndexAndCompare(arr, firstPartEndIndex + 1, thirdPartStartingIndex)
return if (secondPartEndIndex < 0) res else intArrayOf(firstPartEndIndex, secondPartEndIndex + 1)
}
/** the implementation idea is similar to find last k node in a list
* in the sense that pacer is a pacer
* when the pacer reaches the end, the end for the current part has been anchored
* Note: we also do the comparing for the two parts of interest
*
* @param a
* @param start
* @param pacer
* @return
*/
private fun findNextEndIndexAndCompare(a: IntArray, start: Int, pacer: Int): Int {
var start0 = start
var pacer0 = pacer
while (a[start0] == 0) {
start0++
}
while (pacer0 < a.size) {
if (a[start0] != a[pacer0]) return -1
start0++
pacer0++
}
return start0 - 1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,802 | kotlab | Apache License 2.0 |
leetcode/src/tree/Q101.kt | zhangweizhe | 387,808,774 | false | null | package tree
import linkedlist.TreeNode
import java.util.*
fun main() {
// 101. 对称二叉树
// https://leetcode-cn.com/problems/symmetric-tree/
val root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left?.left = TreeNode(3)
// root.left?.right = TreeNode(3)
// root.right?.left = TreeNode(4)
root.right?.right = TreeNode(3)
println(isSymmetric(root))
}
/**
* 递归
*/
private fun isSymmetric(root: TreeNode?): Boolean {
return help(root, root)
}
private fun help(left: TreeNode?, right: TreeNode?):Boolean {
if (left == null && right == null) {
return true
}
if (left == null || right == null) {
return false
}
if (left.`val` != right.`val`) {
return false
}
return help(left.left, right.right) && help(left.right, right.left)
}
/**
* 迭代
*/
private fun isSymmetric1(root: TreeNode?): Boolean {
if (root == null) {
return true
}
val queue = LinkedList<TreeNode?>()
queue.add(root)
while (queue.isNotEmpty()) {
val size = queue.size
for (i in 0 until size) {
if (queue[i] == null && queue[size - i - 1] == null) {
continue
}
if (queue[i]?.`val` != queue[size - i - 1]?.`val`) {
return false
}
// 遍历每一层时,只peek
val peek = queue[i]
queue.add(peek?.left)
queue.add(peek?.right)
}
// 一层遍历完了,再统一poll
for (i in 0 until size) {
queue.poll()
}
}
return true
}
| 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,645 | kotlin-study | MIT License |
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day02/Day02.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.day02
import com.pietromaggi.aoc2021.readInput
enum class Command {
FORWARD,
DOWN,
UP
}
data class Instruction(val command: Command, val value: Int)
fun String.toCommand() : Command {
val command = when(this) {
"forward" -> Command.FORWARD
"down" -> Command.DOWN
"up" -> Command.UP
else -> throw IllegalArgumentException("Invalid command")
}
return command
}
fun List<String>.toInstructions() : List<Instruction> {
return this.map { line ->
val (command, value) = line.split(" ")
Instruction(command.toCommand(), value.toInt())
}
}
fun part1(input: List<String>) : Int {
val instructions = input.toInstructions()
var position = 0
var depth = 0
for ((command, value) in instructions) {
when (command) {
Command.FORWARD -> position += value
Command.DOWN -> depth += value
Command.UP -> depth -= value
}
}
return depth * position
}
fun part2(input: List<String>) : Int {
val instructions = input.toInstructions()
var position = 0
var aim = 0
var depth = 0
for ((command, value) in instructions) {
when (command) {
Command.FORWARD -> {
position += value
depth += value * aim
}
Command.DOWN -> aim += value
Command.UP -> aim -= value
}
}
return depth * position
}
fun main() {
val input = readInput("Day02")
println("What do you get if you multiply your final horizontal position by your final depth?")
println("My puzzle answer is: ${part1(input)}")
println("What do you get if you multiply your final horizontal position by your final depth?")
println("My puzzle answer is: ${part2(input)}")}
| 0 | Kotlin | 0 | 0 | 7c4946b6a161fb08a02e10e99055a7168a3a795e | 2,430 | AdventOfCode | Apache License 2.0 |
src/Lesson2Arrays/OddOccurrencesInArray.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} |
import java.util.Arrays
/**
* 100/100
* @param A
* @return
*/
fun solution(A: IntArray): Int {
Arrays.sort(A)
var i = 0
while (i < A.size - 1) {
if (A[i] != A[i + 1]) {
return A[i]
}
i += 2
}
return A[A.size - 1]
}
/**
* A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
*
* For example, in array A such that:
*
* A[0] = 9 A[1] = 3 A[2] = 9
* A[3] = 3 A[4] = 9 A[5] = 7
* A[6] = 9
* the elements at indexes 0 and 2 have value 9,
* the elements at indexes 1 and 3 have value 3,
* the elements at indexes 4 and 6 have value 9,
* the element at index 5 has value 7 and is unpaired.
* Write a function:
*
* class Solution { public int solution(int[] A); }
*
* that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
*
* For example, given array A such that:
*
* A[0] = 9 A[1] = 3 A[2] = 9
* A[3] = 3 A[4] = 9 A[5] = 7
* A[6] = 9
* the function should return 7, as explained in the example above.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an odd integer within the range [1..1,000,000];
* each element of array A is an integer within the range [1..1,000,000,000];
* all but one of the values in A occur an even number of times.
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 1,525 | Codility-Kotlin | Apache License 2.0 |
src/org/aoc2021/Day23.kt | jsgroth | 439,763,933 | false | {"Kotlin": 86732} | package org.aoc2021
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
object Day23 {
private const val hallwayLength = 11
private val amphipodChars = setOf('A', 'B', 'C', 'D')
private val roomIndices = setOf(2, 4, 6, 8)
private val secondRow = listOf(Amphipod.DESERT, Amphipod.COPPER, Amphipod.BRONZE, Amphipod.AMBER)
private val thirdRow = listOf(Amphipod.DESERT, Amphipod.BRONZE, Amphipod.AMBER, Amphipod.COPPER)
enum class Amphipod(val energyPerStep: Int) {
AMBER(1),
BRONZE(10),
COPPER(100),
DESERT(1000),
}
private val winState = Amphipod.values().toList()
sealed interface HallwayPosition
data class Space(val occupant: Amphipod?) : HallwayPosition
data class Room(val occupants: List<Amphipod?>) : HallwayPosition {
fun withNewOccupant(occupant: Amphipod): Room {
if (occupants.all { it == null }) {
return Room(occupants.drop(1).plus(occupant))
}
val firstNullIndex = firstOpenIndex()
return Room(
occupants.take(firstNullIndex).plus(occupant).plus(occupants.drop(firstNullIndex + 1))
)
}
fun withoutTopOccupant(): Room {
val firstNonNullIndex = firstOccupiedIndex()
return Room(
occupants.take(firstNonNullIndex).plus(null).plus(occupants.drop(firstNonNullIndex + 1))
)
}
fun firstOpenIndex(): Int {
return occupants.indexOfLast { it == null }
}
fun firstOccupiedIndex(): Int {
return occupants.indexOfFirst { it != null }
}
}
data class State(val distance: Int, val hallway: List<HallwayPosition>)
private fun solve(lines: List<String>, expandMiddle: Boolean): Int {
val hallway = parseInput(lines, expandMiddle)
val pq = PriorityQueue<State> { a, b ->
a.distance.compareTo(b.distance)
}
pq.add(State(0, hallway))
val stateToMinDistance = mutableMapOf<List<HallwayPosition>, Int>()
while (!pq.isEmpty()) {
val state = pq.remove()
if (state.distance >= (stateToMinDistance[state.hallway] ?: Integer.MAX_VALUE)) {
continue
}
stateToMinDistance[state.hallway] = state.distance
if (isWinningState(state.hallway)) {
return state.distance
}
generatePossibleMoves(state.hallway).forEach { (moveDistance, moveState) ->
val newDistance = state.distance + moveDistance
if (newDistance < (stateToMinDistance[moveState] ?: Integer.MAX_VALUE)) {
pq.add(State(newDistance, moveState))
}
}
}
throw IllegalArgumentException("no winning solution found")
}
private fun isWinningState(state: List<HallwayPosition>): Boolean {
return state.filterIsInstance<Room>().zip(winState).all { (room, targetAmphipod) ->
room.occupants.all { it == targetAmphipod }
}
}
private fun generatePossibleMoves(hallway: List<HallwayPosition>): List<Pair<Int, List<HallwayPosition>>> {
val moves = mutableListOf<Pair<Int, List<HallwayPosition>>>()
hallway.forEachIndexed { i, position ->
when (position) {
is Space -> moves.addAll(generateSpaceMoves(hallway, i, position))
is Room -> moves.addAll(generateRoomMoves(hallway, i, position))
}
}
return moves.toList()
}
private fun generateSpaceMoves(
hallway: List<HallwayPosition>,
i: Int,
space: Space,
): List<Pair<Int, List<HallwayPosition>>> {
if (space.occupant == null) {
return listOf()
}
val targetIndex = 2 * winState.indexOf(space.occupant) + 2
val targetRoom = hallway[targetIndex] as Room
if (canMoveToRoom(hallway, i, targetIndex)) {
val distance = space.occupant.energyPerStep * (abs(i - targetIndex) + 1 + targetRoom.firstOpenIndex())
val newState = hallway.map { position ->
if (position === space) {
Space(null)
} else if (position === targetRoom) {
targetRoom.withNewOccupant(space.occupant)
} else {
position
}
}
return listOf(distance to newState)
}
return listOf()
}
private fun generateRoomMoves(
hallway: List<HallwayPosition>,
i: Int,
room: Room,
): List<Pair<Int, List<HallwayPosition>>> {
val targetAmphipod = winState[(i - 2) / 2]
if (room.occupants.all { it == null || it == targetAmphipod }) {
return listOf()
}
val firstOccupiedIndex = room.firstOccupiedIndex()
val first = room.occupants[firstOccupiedIndex]!!
if (first != targetAmphipod) {
val firstTargetIndex = 2 * winState.indexOf(first) + 2
val firstTargetRoom = hallway[firstTargetIndex] as Room
if (canMoveToRoom(hallway, i, firstTargetIndex)) {
val steps = abs(i - firstTargetIndex) + 2 + firstOccupiedIndex + firstTargetRoom.firstOpenIndex()
val distance = first.energyPerStep * steps
val newState = hallway.map { position ->
if (position === room) {
room.withoutTopOccupant()
} else if (position === firstTargetRoom) {
firstTargetRoom.withNewOccupant(first)
} else {
position
}
}
return listOf(distance to newState)
}
}
val moves = mutableListOf<Pair<Int, List<HallwayPosition>>>()
for (j in hallway.indices) {
val space = hallway[j]
if (space !is Space) {
continue
}
if (canMoveToSpace(hallway, i, j)) {
val distance = first.energyPerStep * (abs(i - j) + 1 + room.firstOccupiedIndex())
val newState = hallway.map { position ->
if (position === room) {
room.withoutTopOccupant()
} else if (position === space) {
Space(first)
} else {
position
}
}
moves.add(distance to newState)
}
}
return moves.toList()
}
private fun canMoveToSpace(
hallway: List<HallwayPosition>,
i: Int,
targetIndex: Int,
): Boolean {
val space = hallway[targetIndex] as Space
if (space.occupant != null) {
return false
}
return canMoveToPosition(hallway, i, targetIndex)
}
private fun canMoveToRoom(
hallway: List<HallwayPosition>,
i: Int,
targetIndex: Int,
): Boolean {
val targetAmphipod = winState[(targetIndex - 2) / 2]
val targetRoom = hallway[targetIndex] as Room
if (!targetRoom.occupants.all { it == null || it == targetAmphipod }) {
return false
}
return canMoveToPosition(hallway, i, targetIndex)
}
private fun canMoveToPosition(
hallway: List<HallwayPosition>,
i: Int,
targetIndex: Int,
): Boolean {
val start = min(i, targetIndex)
val end = max(i, targetIndex)
return ((start + 1) until end).all { j ->
val position = hallway[j]
position !is Space || position.occupant == null
}
}
private fun parseInput(lines: List<String>, expandMiddle: Boolean): List<HallwayPosition> {
val frontOccupants = lines[2].filter(amphipodChars::contains).toCharArray()
val backOccupants = lines[3].filter(amphipodChars::contains).toCharArray()
val roomOccupants = frontOccupants.zip(backOccupants)
var occupantsIndex = 0
val result = mutableListOf<HallwayPosition>()
for (i in 0 until hallwayLength) {
if (roomIndices.contains(i)) {
val (frontOccupant, backOccupant) = roomOccupants[occupantsIndex]
val room = if (expandMiddle) {
Room(listOf(
charToAmphipod(frontOccupant),
secondRow[(i - 2) / 2],
thirdRow[(i - 2) / 2],
charToAmphipod(backOccupant),
))
} else {
Room(listOf(charToAmphipod(frontOccupant), charToAmphipod(backOccupant)))
}
result.add(room)
occupantsIndex++
} else {
result.add(Space(occupant = null))
}
}
return result.toList()
}
private fun charToAmphipod(c: Char): Amphipod = when (c) {
'A' -> Amphipod.AMBER
'B' -> Amphipod.BRONZE
'C' -> Amphipod.COPPER
'D' -> Amphipod.DESERT
else -> throw IllegalArgumentException("$c")
}
@JvmStatic
fun main(args: Array<String>) {
val lines = Files.readAllLines(Path.of("input23.txt"), Charsets.UTF_8)
val solution1 = solve(lines, false)
println(solution1)
val solution2 = solve(lines, true)
println(solution2)
}
} | 0 | Kotlin | 0 | 0 | ba81fadf2a8106fae3e16ed825cc25bbb7a95409 | 9,627 | advent-of-code-2021 | The Unlicense |
src/y2022/Day02.kt | a3nv | 574,208,224 | false | {"Kotlin": 34115, "Java": 1914} | package y2022
import utils.readInput
fun main() {
fun getGame(choice: String): Choice {
return when (choice) {
"A", "X" -> Rock(choice)
"B", "Y" -> Paper(choice)
"C", "Z" -> Scissors(choice)
else -> throw IllegalArgumentException()
}
}
fun game(round: String): Int {
val split = round.split(" ", limit = 2)
val game = getGame(split[1])
return game.play(getGame(split[0])) + game.points
}
fun part1(rounds: List<String>): Int {
var sum = 0
rounds.forEach {
sum += game(it)
}
return sum
}
fun yield(round: String): Int {
val split = round.split(" ", limit = 2)
val game = getGame(split[0])
val choose = game.choose(split[1])
return choose.play(game) + choose.points
}
fun part2(rounds: List<String>): Int {
var sum = 0
rounds.forEach {
sum += yield(it)
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("y2022", "Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
println(part2(testInput))
check(part2(testInput) == 12)
val input = readInput("y2022", "Day02")
println(part1(input))
check(part1(input) == 15337)
println(part2(input))
check(part2(input) == 11696)
}
abstract class Choice(val choice: String, var label: String, var points: Int) {
abstract fun play(opp: Choice): Int
abstract fun choose(outcome: String): Choice
}
class Rock(choice: String, label: String = "A", points: Int = 1) : Choice(choice, label, points) {
override fun play(opp: Choice): Int {
return when (opp) {
is Rock -> 3
is Paper -> 0
is Scissors -> 6
else -> 0
}
}
override fun choose(outcome: String): Choice {
return when (outcome) {
"X" -> Scissors(outcome) // lose to Rock
"Y" -> Rock(outcome) // draw with Rock
"Z" -> Paper(outcome) // win Rock
else -> throw IllegalArgumentException()
}
}
override fun toString(): String {
return choice + label
}
}
class Paper(choice: String, label: String = "B", points: Int = 2) : Choice(choice, label, points) {
override fun play(opp: Choice): Int {
return when (opp) {
is Rock -> 6
is Paper -> 3
is Scissors -> 0
else -> 0
}
}
override fun choose(outcome: String): Choice {
return when (outcome) {
"X" -> Rock(outcome) // lose to Paper
"Y" -> Paper(outcome) // draw with Paper
"Z" -> Scissors(outcome) // win Paper
else -> throw IllegalArgumentException()
}
}
override fun toString(): String {
return choice + label
}
}
class Scissors(choice: String, label: String = "C", points: Int = 3) : Choice(choice, label, points) {
override fun play(opp: Choice): Int {
return when (opp) {
is Rock -> 0
is Paper -> 6
is Scissors -> 3
else -> 0
}
}
override fun choose(outcome: String): Choice {
return when (outcome) {
"X" -> Paper(outcome) // lose to Scissors
"Y" -> Scissors(outcome) // draw with Scissors
"Z" -> Rock(outcome) // win Scissors
else -> throw IllegalArgumentException()
}
}
override fun toString(): String {
return choice + label
}
} | 0 | Kotlin | 0 | 0 | ab2206ab5030ace967e08c7051becb4ae44aea39 | 3,638 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2016/Day01.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2016
import AoCDay
import aoc2016.Day01.Dir.*
import util.Vec2
import util.illegalInput
import util.plus
import util.times
import kotlin.math.abs
// https://adventofcode.com/2016/day/1
object Day01 : AoCDay<Int>(
title = "No Time for a Taxicab",
part1ExampleAnswer = 8,
part1Answer = 252,
part2ExampleAnswer = 4,
part2Answer = 143,
) {
private fun Vec2.manhattanDistanceFromStart() = abs(x) + abs(y)
private enum class Dir(val vec: Vec2) {
NORTH(Vec2(1, 0)),
EAST(Vec2(0, 1)),
SOUTH(Vec2(-1, 0)),
WEST(Vec2(0, -1)),
}
private fun Dir.turn(dir: Char) = when (dir) {
'L' -> when (this) {
NORTH -> WEST
EAST -> NORTH
SOUTH -> EAST
WEST -> SOUTH
}
'R' -> when (this) {
NORTH -> EAST
EAST -> SOUTH
SOUTH -> WEST
WEST -> NORTH
}
else -> illegalInput(dir)
}
override fun part1(input: String) = input
.splitToSequence(", ")
.fold(
initial = Pair(Vec2(0, 0), NORTH),
) { (pos, facing), ins ->
val newFacing = facing.turn(ins.first())
val step = ins.drop(1).toInt()
val newPos = pos + (newFacing.vec * step)
Pair(newPos, newFacing)
}
.first
.manhattanDistanceFromStart()
override fun part2(input: String): Int {
var pos = Vec2(0, 0)
var facing = NORTH
val visited = hashSetOf(pos)
outer@ for (ins in input.splitToSequence(", ")) {
facing = facing.turn(ins.first())
val step = ins.drop(1).toInt()
for (i in 0..<step) {
pos += facing.vec
if (!visited.add(pos)) break@outer
}
}
return pos.manhattanDistanceFromStart()
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 1,882 | advent-of-code-kotlin | MIT License |
kotlin/src/main/kotlin/adventofcode/y2018/Day6.kt | 3ygun | 115,948,057 | false | null | package adventofcode.y2018
import adventofcode.DataLoader
import adventofcode.Day
import kotlin.math.abs
object Day6 : Day {
val STAR1_DATA = DataLoader.readLinesFromFor("/y2018/Day6Star1.txt")
val STAR2_DATA = STAR1_DATA
const val STAR2_MAX_DISTANCE = 10_000
override val day: Int = 6
override fun star1Run(): String {
val result = star1Calc(STAR1_DATA)
return "largest non infinite area is $result"
}
override fun star2Run(): String {
val result = star2Calc(STAR2_DATA, STAR2_MAX_DISTANCE)
return "area of region with max 1000 distance to all coordinates is $result"
}
fun star1Calc(input: List<String>): Int {
if (input.isEmpty()) return 0
val points = parsePoints(input)
val grid = Grid(points)
grid.populate()
if (debug) grid.print()
return grid.largestArea()
}
fun star2Calc(input: List<String>, maxDistance: Int): Int {
if (input.isEmpty()) return 0
val points = parsePoints(input)
val grid = Grid(points)
grid.populateAllPointsWithinDistance(maxDistance)
if (debug) grid.print()
if (debug) grid.printDistance()
return grid.flagged()
}
private fun parsePoints(input: List<String>): List<Point> {
val nextName = (1 .. input.size).iterator()
return input.map { rawPoint ->
val points = rawPoint.split(",", limit = 2)
Point(
x = points[0].trim().toInt(),
y = points[1].trim().toInt(),
name = nextName.nextInt()
)
}
}
}
private typealias GridArray = Array<Array<GridPoint?>>
private data class Point(val x: Int, val y: Int, val name: Int) {
fun distanceTo(x: Int, y: Int): Int = abs(this.x - x) + abs(this.y - y)
}
private data class GridPoint(val name: Int, val distance: Int) {
fun isContended() = name == NAME_FLAG
fun distanceCompareTo(distance: Int): Int {
return this.distance.compareTo(distance)
}
companion object {
const val NAME_FLAG = -1
fun Flag(distance: Int): GridPoint = GridPoint(NAME_FLAG, distance)
}
}
private data class Grid(
val points: List<Point>
) {
val width: Int = points.maxBy { it.x }!!.x + 1 // + 1 to account for the 0 start
val height: Int = points.maxBy { it.y }!!.y + 1 // + 1 to account for the 0 start
// Height, Width because the top left corner is 0, 0
private val grid: GridArray = Array(height) { Array<GridPoint?>(width) { null } }
fun at(x: Int, y: Int): GridPoint? = grid[y][x]
fun claim(x: Int, y: Int, name: Int, distance: Int): Boolean {
val existing = at(x, y)
?: return claimLocation(x, y, GridPoint(name, distance))
// we don't have to care about the distance in our algorithm
if (existing.name == name) return true
return when(existing.distanceCompareTo(distance)) {
1 -> claimLocation(x, y, GridPoint(name, distance))
0 -> claimLocation(x, y, GridPoint.Flag(distance))
else -> false
}
}
private fun claimLocation(x: Int, y: Int, gridPoint: GridPoint): Boolean {
grid[y][x] = gridPoint
return true // Claimed
}
inline fun forEachPoint(run: (GridPoint?) -> Unit) {
for (y in 0 until height) {
for (x in 0 until width) {
run(at(x, y))
}
}
}
fun print() = forEachPrinting { it?.name ?: 0 }
fun printDistance() = forEachPrinting { it?.distance ?: 0 }
private inline fun forEachPrinting(run: (GridPoint?) -> Int) {
for (y in 0 until height) {
for (x in 0 until width) {
print("%3d".format(run(at(x, y))))
}
println()
}
println()
}
}
//<editor-fold desc="Star 1">
private fun Grid.populate() {
for (point in points) {
// println("${point.name} with ${point.x}, ${point.y}")
// print()
// println()
//
// printDistance()
// println()
// Initial Point
claim(point.x, point.y, point.name, distance = 0)
// Top Left Corner
claimAllFor(
point = point,
xRange = point.x downTo 0,
yRange = point.y downTo 0
)
// Top Right Corner
claimAllFor(
point = point,
xRange = point.x until width,
yRange = point.y downTo 0
)
// Bottom Left Corner
claimAllFor(
point = point,
xRange = point.x downTo 0,
yRange = point.y until height
)
// Bottom Right Corner
claimAllFor(
point = point,
xRange = point.x until width,
yRange = point.y until height
)
}
}
private fun Grid.claimAllFor(
point: Point,
xRange: IntProgression,
yRange: IntProgression
) {
for (x in xRange) {
for (y in yRange) {
if (x == point.x && y == point.y) continue
val madeClaim = claim(x, y, point.name, distance = point.distanceTo(x, y))
if (madeClaim) continue
if (y == point.y) return
break // otherwise we hit the a overflow on y
}
}
}
private fun Grid.largestArea(): Int {
// This array is one larger than the original points because I'm saving 0 as "untouched"
val counts = IntArray(points.size + 1)
forEachPoint { point ->
if (point != null && !point.isContended()) {
counts[point.name] = counts[point.name] + 1
}
}
val infinite = HashSet<Int>()
(0 until width).forEach { x ->
at(x, 0)?.run { infinite.add(this.name) }
at(x, height-1)?.run { infinite.add(this.name) }
}
(0 until height).forEach { y ->
at(0, y)?.run { infinite.add(this.name) }
at(width-1, y)?.run { infinite.add(this.name) }
}
return counts
.mapIndexed { index, count -> Pair(index, count) }
.filter { !infinite.contains(it.first) }
.maxBy { it.second }!!
.second
}
//</editor-fold>
//<editor-fold desc="Star 2">
private fun Grid.populateAllPointsWithinDistance(maxDistance: Int) {
for (x in 0 until width) {
y@for (y in 0 until height) {
var distance = 0
for (point in points) {
distance += point.distanceTo(x, y)
if (distance >= maxDistance) continue@y // point too far
}
claim(x, y, GridPoint.NAME_FLAG, distance)
}
}
}
private fun Grid.flagged(): Int {
var flagged = 0
forEachPoint { point ->
if (point != null && point.isContended()) flagged ++
}
return flagged
}
//</editor-fold>
| 0 | Kotlin | 0 | 0 | 69f95bca3d22032fba6ee7d9d6ec307d4d2163cf | 6,827 | adventofcode | MIT License |
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day16/Valve.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2022.day16
import eu.janvdb.aocutil.kotlin.ShortestPathMove
import eu.janvdb.aocutil.kotlin.findShortestPath
const val START_VALVE = "AA"
val PATTERN = Regex("Valve ([A-Z]+) has flow rate=(\\d+); tunnels? leads? to valves? ([A-Z, ]+)")
val SPLIT = Regex(", ")
data class Valve(val name: String, val flowRate: Int, val leadsTo: List<String>)
fun String.toValve(): Valve {
val match = PATTERN.matchEntire(this) ?: throw IllegalArgumentException(this)
val name = match.groupValues[1]
val flowRate = match.groupValues[2].toInt()
val leadsTo = match.groupValues[3].split(SPLIT).toList()
return Valve(name, flowRate, leadsTo)
}
data class Valves(val valvesMap: Map<String, Valve>, val distances: Map<String, Map<String, Int>>) {
fun stepLength(from: String, to: String): Int {
return distances[from]!![to]!!
}
fun flowRate(it: String): Int {
return valvesMap[it]!!.flowRate
}
val names = distances.keys
companion object {
fun create(valves: List<Valve>): Valves {
val valvesMap = valves.associateBy { it.name }
val valvesToConsider = valves.filter { it.flowRate != 0 } + valvesMap[START_VALVE]!!
fun subMap(valve1: Valve): Pair<String, Map<String, Int>> {
val subMap = valvesToConsider.asSequence()
.filter { it != valve1 }
.map { valve2 ->
val shortestPath = findShortestPath(valve1, valve2) { valve ->
valve.leadsTo.asSequence().map { ShortestPathMove(valvesMap[it]!!, 1) }
}?.cost
Pair(valve2.name, shortestPath!!)
}
.toMap()
return Pair(valve1.name, subMap)
}
val distances = valvesToConsider.asSequence()
.map { subMap(it) }
.toMap()
return Valves(valvesMap, distances)
}
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 1,708 | advent-of-code | Apache License 2.0 |
kotlin/dp/MatrixChainMultiply.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package dp
object MatrixChainMultiply {
fun solveIterative(s: IntArray): Int {
val n = s.size - 1
val p = Array(n) { IntArray(n) }
val m = Array(n) { IntArray(n) }
for (len in 2..n) {
var a = 0
while (a + len <= n) {
val b = a + len - 1
m[a][b] = Integer.MAX_VALUE
for (c in a until b) {
val v = m[a][c] + m[c + 1][b] + s[a] * s[c + 1] * s[b + 1]
if (m[a][b] > v) {
m[a][b] = v
p[a][b] = c
}
}
a++
}
}
return m[0][n - 1]
}
fun solveRecursive(s: IntArray): Int {
val n = s.size - 1
val cache = Array(n) { IntArray(n) }
for (x in cache) Arrays.fill(x, INF)
val p = Array(n) { IntArray(n) }
return rec(0, n - 1, s, p, cache)
}
val INF: Int = Integer.MAX_VALUE / 3
fun rec(i: Int, j: Int, s: IntArray, p: Array<IntArray>, cache: Array<IntArray>): Int {
if (i == j) return 0
var res = cache[i][j]
if (res != INF) return res
for (k in i until j) {
val v = rec(i, k, s, p, cache) + rec(k + 1, j, s, p, cache) + s[i] * s[k + 1] * s[j + 1]
if (res > v) {
res = v
p[i][j] = k
}
}
return res.also { cache[i][j] = it }
}
// test
fun main(args: Array<String?>?) {
val rnd = Random(1)
for (step in 0..999) {
val n: Int = rnd.nextInt(6) + 2
val s: IntArray = rnd.ints(n, 1, 11).toArray()
val res1 = solveIterative(s)
val res2 = solveRecursive(s)
if (res1 != res2) {
System.out.println("$res1 $res2")
System.out.println(Arrays.toString(s))
}
}
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,932 | codelibrary | The Unlicense |
src/aoc2023/Day3.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2023
import utils.Vertex
import utils.alsoPrintln
import utils.checkEquals
import utils.readInput
import kotlin.collections.List
import kotlin.collections.contains
import kotlin.collections.filter
import kotlin.collections.flatten
import kotlin.collections.getOrNull
import kotlin.collections.listOf
import kotlin.collections.listOfNotNull
import kotlin.collections.mutableMapOf
import kotlin.collections.plus
import kotlin.collections.set
import kotlin.collections.sumOf
import kotlin.collections.withIndex
fun main(): Unit = with(Day3) {
part1(testInput).checkEquals(4361)
part1(input)
.checkEquals(546312)
// .sendAnswer(part = 1, day = "3", year = 2023)
part2(testInput).checkEquals(467835)
part2(input)
.alsoPrintln()
.checkEquals(87449461)
// .sendAnswer(part = 2, day = "3", year = 2023)
}
object Day3 {
private val numRegex = "\\d+".toRegex()
fun part1(input: List<String>): Int {
fun Char.isSymbol() = !isDigit() && this != '.'
var sum = 0
for ((i, line) in input.withIndex()) {
val nums: Sequence<MatchResult> = numRegex.findAll(line)
match@ for (numMatchResult in nums) {
val horizontalAdjacentRange = IntRange(
(numMatchResult.range.first - 1).coerceAtLeast(0),
(numMatchResult.range.last + 1).coerceAtMost(input[0].lastIndex)
)
val top = input.getOrNull(i - 1)?.substring(horizontalAdjacentRange)
val down = input.getOrNull(i + 1)?.substring(horizontalAdjacentRange)
val left = line.getOrNull(horizontalAdjacentRange.first)
val right = line.getOrNull(horizontalAdjacentRange.last)
val around: List<Char> =
listOfNotNull(top?.toList(), down?.toList()).flatten() + listOfNotNull(left, right)
for (c in around)
if (c.isSymbol()) {
sum += numMatchResult.value.toInt()
continue@match
}
}
}
return sum
}
fun part2(input: List<String>): Long {
val gearAdjacentNumbers = mutableMapOf<Vertex, List<Int>>()
fun Vertex.addToGearMap(num: Int) {
if (this !in gearAdjacentNumbers)
gearAdjacentNumbers[this] = listOf(num)
else
gearAdjacentNumbers[this] = gearAdjacentNumbers[this]!! + listOf(num)
}
for ((i, line) in input.withIndex()) {
val nums = numRegex.findAll(line)
for (numMatchResult in nums) {
val horizontalAdjacentRange = IntRange(
(numMatchResult.range.first - 1).coerceAtLeast(0),
(numMatchResult.range.last + 1).coerceAtMost(input[0].lastIndex)
)
// left
if (line.getOrNull(horizontalAdjacentRange.first) == '*') {
val gearVertex = Vertex(y = i, x = horizontalAdjacentRange.first)
gearVertex.addToGearMap(numMatchResult.value.toInt())
}
//right
if (line.getOrNull(horizontalAdjacentRange.last) == '*')
Vertex(y = i, x = horizontalAdjacentRange.last).addToGearMap(numMatchResult.value.toInt())
// top
input.getOrNull(i - 1)
?.substring(horizontalAdjacentRange)
?.forEachIndexed { cIndex, c ->
if (c == '*')
Vertex(y = i - 1, x = horizontalAdjacentRange.first + cIndex).addToGearMap(numMatchResult.value.toInt())
}
// down
input.getOrNull(i + 1)
?.substring(horizontalAdjacentRange)
?.forEachIndexed { cIndex, c ->
if (c == '*')
Vertex(y = i + 1, x = horizontalAdjacentRange.first + cIndex).addToGearMap(numMatchResult.value.toInt())
}
}
}
return gearAdjacentNumbers.values.filter { it.size == 2 }.sumOf { it[0].toLong() * it[1] }
}
val input
get() = readInput("Day3", "aoc2023")
val testInput
get() = readInput("Day3_test", "aoc2023")
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 4,378 | Kotlin-AOC-2023 | Apache License 2.0 |
leetcode-75-kotlin/src/main/kotlin/MergeStringsAlternately.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* You are given two strings word1 and word2.
* Merge the strings by adding letters in alternating order, starting with word1.
* If a string is longer than the other, append the additional letters onto the end of the merged string.
*
* Return the merged string.
*
*
*
* Example 1:
*
* Input: word1 = "abc", word2 = "pqr"
* Output: "apbqcr"
* Explanation: The merged string will be merged as so:
* word1: a b c
* word2: p q r
* merged: a p b q c r
* Example 2:
*
* Input: word1 = "ab", word2 = "pqrs"
* Output: "apbqrs"
* Explanation: Notice that as word2 is longer, "rs" is appended to the end.
* word1: a b
* word2: p q r s
* merged: a p b q r s
* Example 3:
*
* Input: word1 = "abcd", word2 = "pq"
* Output: "apbqcd"
* Explanation: Notice that as word1 is longer, "cd" is appended to the end.
* word1: a b c d
* word2: p q
* merged: a p b q c d
*
*
* Constraints:
*
* 1 <= word1.length, word2.length <= 100
* word1 and word2 consist of lowercase English letters.
* @see <a href="https://leetcode.com/problems/merge-strings-alternately/">LeetCode</a>
*/
fun mergeAlternately(word1: String, word2: String): String {
var word1Index = 0
var word2Index = 0
return buildString {
for (index in 0 until word1.length + word2.length) {
if (word1Index < word1.length && (index.rem(2) == 0 || word2Index >= word2.length)) {
append(word1[word1Index])
word1Index++
} else {
append(word2[word2Index])
word2Index++
}
}
}
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,626 | leetcode-75 | Apache License 2.0 |
src/Day04.kt | ostersc | 572,991,552 | false | {"Kotlin": 46059} | fun main() {
class Assignment() {
var range1 = IntRange(0, 0)
var range2 = IntRange(0, 0)
constructor(line: String) : this() {
val (a, b, c, d) = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex().find(line)!!.destructured.toList()
.map { it.toInt() }
range1 = IntRange(a, b)
range2 = IntRange(c, d)
}
fun containsStrictOverlap(): Boolean {
return range1.intersect(range2).size == range2.count { true } ||
range2.intersect(range1).size == range1.count { true }
}
fun containsAnyOverlap(): Boolean {
return range1.intersect(range2).isNotEmpty()
}
}
fun part1(input: List<String>): Int {
return input.count { line -> Assignment(line).containsStrictOverlap() }
}
fun part2(input: List<String>): Int {
return input.count { line -> Assignment(line).containsAnyOverlap() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9 | 1,236 | advent-of-code-2022 | Apache License 2.0 |
src/Day16.kt | wgolyakov | 572,463,468 | false | null | import kotlin.random.Random
fun main() {
fun parse(input: List<String>): Pair<List<List<Int>>, IntArray> {
val valves = mutableMapOf("AA" to 0)
val adj = MutableList(input.size) { emptyList<Int>() }
val rates = IntArray(input.size)
var count = 1
for (line in input) {
val (valve, rate, exits) =
Regex("Valve ([A-Z]{2}) has flow rate=(\\d+); tunnels? leads? to valves? (.*)")
.matchEntire(line)!!.groupValues.takeLast(3)
val valveNum = valves.getOrPut(valve) { count++ }
rates[valveNum] = rate.toInt()
adj[valveNum] = exits.split(", ").map { valves.getOrPut(it) { count++ } }
}
return adj to rates
}
fun part1(input: List<String>): Int {
val (adj, rate) = parse(input)
val countWithRate = rate.count { it > 0 }
val maxRate = rate.max()
fun isOpen(rate: Int) = maxRate - rate <= Random.nextInt(maxRate * 2)
var maxPressure = 0
for (i in 0 until 10000) {
val visited = BooleanArray(adj.size)
val opened = BooleanArray(adj.size)
var openedWithRate = 0
var time = 30
var pressure = 0
var valve = 0
var prevValve = 0
while (openedWithRate < countWithRate && time > 0) {
if (!visited[valve])
visited[valve] = true
if (rate[valve] > 0 && !opened[valve] && isOpen(rate[valve])) {
opened[valve] = true
openedWithRate++
time--
if (time > 0) pressure += time * rate[valve]
}
val v = valve
val ways = adj[valve]
val unvisited = ways.filter { !visited[it] }
valve = if (unvisited.isNotEmpty()) unvisited.random() else {
if (ways.size == 1) ways.first() else ways.filter { it != prevValve }.random()
}
time--
prevValve = v
}
if (pressure > maxPressure) maxPressure = pressure
}
return maxPressure
}
fun part2(input: List<String>): Int {
val (adj, rate) = parse(input)
val countWithRate = rate.count { it > 0 }
val maxRate = rate.max()
fun isOpen(rate: Int) = maxRate - rate <= Random.nextInt(maxRate * 2)
var maxPressure = 0
for (i in 0 until 1000000) {
val visited = BooleanArray(adj.size)
val opened = BooleanArray(adj.size)
var openedWithRate = 0
var pressure = 0
var me = 0
var mePrev = 0
var meTime = 26
var elephant = 0
var elephantPrev = 0
var elephantTime = 26
visited[0] = true
while (openedWithRate < countWithRate && (meTime > 0 || elephantTime > 0)) {
if (meTime > 0 && rate[me] > 0 && !opened[me] && isOpen(rate[me])) {
opened[me] = true
openedWithRate++
meTime--
if (meTime > 0) pressure += meTime * rate[me]
}
if (elephantTime > 0 && rate[elephant] > 0 && !opened[elephant] && isOpen(rate[elephant])) {
opened[elephant] = true
openedWithRate++
elephantTime--
if (elephantTime > 0) pressure += elephantTime * rate[elephant]
}
if (meTime > 0) {
val v = me
val ways = adj[me]
val unvisited = ways.filter { !visited[it] }
me = if (unvisited.isNotEmpty()) unvisited.random() else {
if (ways.size == 1) ways.first() else ways.filter { it != mePrev }.random()
}
meTime--
mePrev = v
if (!visited[me]) visited[me] = true
}
if (elephantTime > 0) {
val v = elephant
val ways = adj[elephant]
val unvisited = ways.filter { !visited[it] }
elephant = if (unvisited.isNotEmpty()) unvisited.random() else {
if (ways.size == 1) ways.first() else ways.filter { it != elephantPrev }.random()
}
elephantTime--
elephantPrev = v
if (!visited[elephant]) visited[elephant] = true
}
}
if (pressure > maxPressure) maxPressure = pressure
}
return maxPressure
}
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 3,803 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code2015/src/main/kotlin/day7/Advent7.kt | REDNBLACK | 128,669,137 | false | null | package day7
import parseInput
import splitToLines
/**
--- Day 7: Some Assembly Required ---
This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is a little under the recommended age range, and he needs help assembling the circuit.
Each wire has an identifier (some lowercase letters) and can carry a 16-bit signal (a number from 0 to 65535). A signal is provided to each wire by a gate, another wire, or some specific value. Each wire can only get a signal from one source, but can provide its signal to multiple destinations. A gate provides no signal until all of its inputs have a signal.
The included instructions booklet describes how to connect the parts together: x AND y -> z means to connect wires x and y to an AND gate, and then connect its output to wire z.
For example:
123 -> x means that the signal 123 is provided to wire x.
x AND y -> z means that the bitwise AND of wire x and wire y is provided to wire z.
p LSHIFT 2 -> q means that the value from wire p is left-shifted by 2 and then provided to wire q.
NOT e -> f means that the bitwise complement of the value from wire e is provided to wire f.
Other possible gates include OR (bitwise OR) and RSHIFT (right-shift). If, for some reason, you'd like to emulate the circuit instead, almost all programming languages (for example, C, JavaScript, or Python) provide operators for these gates.
For example, here is a simple circuit:
123 -> x
456 -> y
x AND y -> d
x OR y -> e
x LSHIFT 2 -> f
y RSHIFT 2 -> g
NOT x -> h
NOT y -> i
After it is run, these are the signals on the wires:
d: 72
e: 507
f: 492
g: 114
h: 65412
i: 65079
x: 123
y: 456
In little Bobby's kit's instructions booklet (provided as your puzzle input), what signal is ultimately provided to wire a?
--- Part Two ---
Now, take the signal you got on wire a, override wire b to that signal, and reset the other wires (including wire a). What new signal is ultimately provided to wire a?
*/
fun main(args: Array<String>) {
val test = """
|123 -> x
|456 -> y
|x AND y -> d
|x OR y -> e
|x LSHIFT 2 -> f
|y RSHIFT 2 -> g
|NOT x -> h
|NOT y -> i
""".trimMargin()
println(generateClasses(test))
println(generateClasses(parseInput("day7-input.txt")))
// println(Generated().a)
// println(Generated2().a)
}
fun generateClasses(input: String): String {
val first = parseOperations(input)
.plus("fun getMembers() = Generated::class.declaredMemberProperties.map { it.name to it.get(this) }")
.map { " ".repeat(4) + it }
.joinToString(
separator = System.lineSeparator(),
prefix = "open class Generated {${System.lineSeparator()}",
postfix = "${System.lineSeparator()}}"
)
val second = "class Generated2 : Generated() { override val b: Int by lazy { Generated().a } }"
return listOf(first, second).joinToString(System.lineSeparator().repeat(2))
}
private fun parseOperations(input: String) = input.splitToLines()
.map {
val args = Regex("""[\da-z]+""")
.findAll(it)
.map { it.groupValues[0] }
.map { if (it in listOf("as", "is", "in", "if", "do")) "reserved_" + it else it }
.toList()
val template = "open val %s: Int by lazy { %s }"
when {
it.matches(Regex("""^[\d\w]+ -> \w+$""")) -> {
val (value, to) = args
template.format(to, value)
}
"AND" in it -> {
val (from1, from2, to) = args
template.format(to, "$from1 and $from2")
}
"OR" in it -> {
val (from1, from2, to) = args
template.format(to, "$from1 or $from2")
}
"NOT" in it -> {
val (from, to) = args
template.format(to, "1.shl(16) - 1 - $from")
}
"LSHIFT" in it -> {
val (from, times, to) = args
template.format(to, "$from shl $times")
}
"RSHIFT" in it -> {
val (from, times, to) = args
template.format(to, "$from shr $times")
}
else -> throw IllegalArgumentException(it)
}
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 4,607 | courses | MIT License |
src/Day05.kt | samframpton | 572,917,565 | false | {"Kotlin": 6980} | import java.io.File
fun main() {
fun part1(): String {
val stacks = getStacks()
val instructions = getInstructions()
for (instruction in instructions) {
for (i in 0 until instruction.first) {
val crate = stacks[instruction.second - 1].removeLast()
stacks[instruction.third - 1].addLast(crate)
}
}
return String(stacks.map { it.last() }.toCharArray())
}
fun part2(): String {
val stacks = getStacks()
val instructions = getInstructions()
for (instruction in instructions) {
val tempStack: ArrayDeque<Char> = ArrayDeque()
for (i in 0 until instruction.first) {
tempStack.addLast(stacks[instruction.second - 1].removeLast())
}
for (i in 0 until instruction.first) {
stacks[instruction.third - 1].addLast(tempStack.removeLast())
}
}
return String(stacks.map { it.last() }.toCharArray())
}
println(part1())
println(part2())
}
private fun getStacks(): List<ArrayDeque<Char>> {
val input = File("src", "Day05.txt").readText().split("\n\n").first().lines().reversed()
val stacks: MutableList<ArrayDeque<Char>> = mutableListOf()
for ((index, character) in input.first().withIndex()) {
if (character.isDigit()) {
val stack: ArrayDeque<Char> = ArrayDeque()
for (i in 1 until input.size) {
if (input[i][index].isLetter()) {
stack.add(input[i][index])
}
}
stacks.add(stack)
}
}
return stacks
}
private fun getInstructions(): List<Triple<Int, Int, Int>> {
val input = File("src", "Day05.txt").readText().split("\n\n").last().lines()
return input.map {
val nums = it.replace("move ", "")
.replace("from ", "")
.replace("to ", "")
.split(" ")
Triple(nums[0].toInt(), nums[1].toInt(), nums[2].toInt())
}
}
| 0 | Kotlin | 0 | 0 | e7f5220b6bd6f3c5a54396fa95f199ff3a8a24be | 2,046 | advent-of-code-2022 | Apache License 2.0 |
src/Day2/Day2.kt | mhlavac | 574,023,170 | false | {"Kotlin": 11179, "Makefile": 612} | package Day2
import java.io.File
fun main() {
val lines = File("src", "Day2/input.txt").readLines()
var totalScore = 0
lines.forEach {
val (theirs, mine) = it.split(" ")
val score = score(map(theirs), map(mine))
totalScore += score
println("$theirs $mine: $score")
}
println("Total Score: $totalScore")
}
fun score(theirs: String, mine:String): Int {
var score = 0
when (mine) {
"Rock" -> score += 1 // Rock is 1 point
"Paper" -> score += 2 // Paper is 2 points
"Scissors" -> score += 3 // Scissors are 3 points
}
if (theirs == mine) {
return score + 3 // Draw is 3 points
}
if (
(theirs == "Rock" && mine == "Paper") || // A Rock is wrapped in a Y Paper
(theirs == "Paper" && mine == "Scissors") || // B Paper is cut by Z scissors
(theirs == "Scissors" && mine == "Rock") // C Scissors is blunted by X Rock
) {
return score + 6; // Win is 6 points
}
return score
}
fun map(move: String): String {
when (move) {
"A", "X" -> return "Rock"
"B", "Y" -> return "Paper"
"C", "Z" -> return "Scissors"
}
return ""
}
| 0 | Kotlin | 0 | 0 | 240dbd396c0a9d72959a0b0ed31f77c356c0c0bd | 1,210 | advent-of-code-2022 | Apache License 2.0 |
2016/main/day_01/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_01_2016
import java.io.File
import kotlin.math.abs
enum class Facing {
NORTH, EAST, SOUTH, WEST
}
fun part1(input: List<String>) {
var horizontalPos =0
var verticalPos = 0
var facing = Facing.NORTH
for ((direction, distance) in input.map { Pair(it[0], it.substring(1).toInt()) }) {
when (direction) {
'R' -> facing = when (facing) {
Facing.NORTH -> Facing.EAST
Facing.EAST -> Facing.SOUTH
Facing.SOUTH -> Facing.WEST
Facing.WEST -> Facing.NORTH
}
'L' -> facing = when (facing) {
Facing.NORTH -> Facing.WEST
Facing.WEST -> Facing.SOUTH
Facing.SOUTH -> Facing.EAST
Facing.EAST -> Facing.NORTH
}
}
when (facing) {
Facing.NORTH -> verticalPos += distance
Facing.SOUTH -> verticalPos -= distance
Facing.EAST -> horizontalPos += distance
Facing.WEST -> horizontalPos -= distance
}
}
print("Distance: ${Math.abs(horizontalPos) + Math.abs(verticalPos)}")
}
fun part2(input: List<String>) {
var horizontalPos = 0
var verticalPos = 0
var facing = Facing.NORTH
val visited = mutableMapOf<Pair<Int,Int>, Byte>()
for ((direction, distance) in input.map { Pair(it[0], it.substring(1).toInt()) }) {
when (direction) {
'R' -> facing = when (facing) {
Facing.NORTH -> Facing.EAST
Facing.EAST -> Facing.SOUTH
Facing.SOUTH -> Facing.WEST
Facing.WEST -> Facing.NORTH
}
'L' -> facing = when (facing) {
Facing.NORTH -> Facing.WEST
Facing.WEST -> Facing.SOUTH
Facing.SOUTH -> Facing.EAST
Facing.EAST -> Facing.NORTH
}
}
when (facing) {
Facing.NORTH -> {
for (j in 1..distance) {
verticalPos++
if (visited.containsKey(Pair(horizontalPos, verticalPos))) {
print("Distance: ${abs(horizontalPos) + abs(verticalPos)}")
return
}
visited[Pair(horizontalPos, verticalPos)] = 1
}
}
Facing.SOUTH -> {
for (j in 1..distance) {
verticalPos--
if (visited.containsKey(Pair(horizontalPos, verticalPos))) {
print("Distance: ${abs(horizontalPos) + abs(verticalPos)}")
return
}
visited[Pair(horizontalPos, verticalPos)] = 1
}
}
Facing.EAST -> {
for (j in 1..distance) {
horizontalPos++
if (visited.containsKey(Pair(horizontalPos, verticalPos))) {
print("Distance: ${abs(horizontalPos) + abs(verticalPos)}")
return
}
visited[Pair(horizontalPos, verticalPos)] = 1
}
}
Facing.WEST -> {
for (j in 1..distance) {
horizontalPos--
if (visited.containsKey(Pair(horizontalPos, verticalPos))) {
print("Distance: ${abs(horizontalPos) + abs(verticalPos)}")
return
}
visited[Pair(horizontalPos, verticalPos)] = 1
}
}
}
}
}
fun main(){
val inputFile = File("2016/inputs/Day_01.txt")
print("\n----- Part 1 -----\n")
part1(inputFile.readLines()[0].split(", "))
print("\n----- Part 2 -----\n")
part2(inputFile.readLines()[0].split(", "))
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 3,871 | AdventofCode | MIT License |
MaximumSubArray.kt | akshaybhongale | 481,316,050 | false | {"Kotlin": 1611} | /**
* Array Data Structure Problem
* Largest Sum Contiguous Sub-array
* Kotlin solution :
* 1- Simple approach = time complexity O(n*n) where n is size of array
* 2- kadane approach = time complexity O(n) where n is size of array
*/
class MaximumSubArray {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val array = arrayOf(1, 3, 8, -2, 6, -8, 5)
val simpleApproach = simpleApproach(array)
val kadaneSolution = kadaneSolution(array)
print("Maximum Sub array : simpleSolution $simpleApproach kadaneSolution $kadaneSolution")
}
private fun simpleApproach(array: Array<Int>): Int {
var maximumSubArray = Int.MIN_VALUE
for (i in array.indices) {
var curSum = 0
for (j in i until array.size) {
curSum += array[j]
if (curSum > maximumSubArray) {
maximumSubArray = curSum
}
}// end of j
}// end of i
return maximumSubArray
}
private fun kadaneSolution(array: Array<Int>): Int {
var maximumSubArray = Int.MIN_VALUE
var currentSum = 0
for (i in array.indices) {
currentSum += array[i]
if (currentSum > maximumSubArray) {
maximumSubArray = currentSum
}
if (currentSum < 0) {
currentSum = 0
}
}
return maximumSubArray
}
}
}
| 0 | Kotlin | 0 | 0 | e2de2c99096dcf0345979492e40f21a0a16b6d55 | 1,611 | Largest-Sum-Contiguous-Subarray-Kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DivideTwoIntegers.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
private const val BITS = 31
/**
* 29. Divide Two Integers
* @see <a href="https://leetcode.com/problems/divide-two-integers/">Source</a>
*/
fun interface DivideTwoIntegers {
fun divide(dividend: Int, divisor: Int): Int
}
/**
* This solution has O(logN^2) time complexity.
*/
@Suppress("INTEGER_OVERFLOW")
class DivideIntegersBitShifting : DivideTwoIntegers {
override fun divide(dividend: Int, divisor: Int): Int {
if (dividend == 1 shl BITS && divisor == -1) return 1.shl(BITS).minus(1)
var a: Int = abs(dividend)
val b: Int = abs(divisor)
var res = 0
var x: Int
while (a - b >= 0) {
x = 0
while (a - (b shl x shl 1) >= 0) {
x++
}
res += 1 shl x
a -= b shl x
}
return if (dividend > 0 == divisor > 0) res else -res
}
}
/**
* Solution 2
* Another solution is also O(32)
*/
@Suppress("INTEGER_OVERFLOW")
class DivideIntegersBitShifting2 : DivideTwoIntegers {
override fun divide(dividend: Int, divisor: Int): Int {
if (dividend == 1 shl BITS && divisor == -1) return (1 shl BITS) - 1
var a: Int = abs(dividend)
val b: Int = abs(divisor)
var res = 0
for (x in BITS downTo 0) if ((a ushr x) - b >= 0) {
res += 1 shl x
a -= b shl x
}
return if (dividend > 0 == divisor > 0) res else -res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,105 | kotlab | Apache License 2.0 |
advent-of-code2016/src/main/kotlin/day06/Advent6.kt | REDNBLACK | 128,669,137 | false | null | package day06
import array2d
import parseInput
import splitToLines
/**
--- Day 6: Signals and Noise ---
Something is jamming your communications with Santa. Fortunately, your signal is only partially jammed, and protocol in situations like this is to switch to a simple repetition code to get the message through.
In this model, the same message is sent repeatedly. You've recorded the repeating message signal (your puzzle input), but the data seems quite corrupted - almost too badly to recover. Almost.
All you need to do is figure out which character is most frequent for each position. For example, suppose you had recorded the following messages:
eedadn
drvtee
eandsr
raavrd
atevrs
tsrnev
sdttsa
rasrtv
nssdts
ntnada
svetve
tesnvt
vntsnd
vrdear
dvrsen
enarar
The most common character in the first column is e; in the second, a; in the third, s, and so on. Combining these characters returns the error-corrected message, easter.
Given the recording in your puzzle input, what is the error-corrected version of the message being sent?
--- Part Two ---
Of course, that would be the message - if you hadn't agreed to use a modified repetition code instead.
In this modified code, the sender instead transmits what looks like random data, but for each character, the character they actually want to send is slightly less likely than the others. Even after signal-jamming noise, you can look at the letter distributions in each column and choose the least common letter to reconstruct the original message.
In the above example, the least common character in the first column is a; in the second, d, and so on. Repeating this process for the remaining characters produces the original message, advent.
Given the recording in your puzzle input and this new decoding methodology, what is the original message that Santa is trying to send?
*/
fun main(args: Array<String>) {
val test = """eedadn
|drvtee
|eandsr
|raavrd
|atevrs
|tsrnev
|sdttsa
|rasrtv
|nssdts
|ntnada
|svetve
|tesnvt
|vntsnd
|vrdear
|dvrsen
|enarar""".trimMargin()
val input = parseInput("day6-input.txt")
println(findMostFrequentChars(test) == "easter")
println(findMostFrequentChars(input))
println(findLeastFrequentChars(input))
}
data class Message(val payload: String) {
fun mostFrequentChar() = payload.charByFunc { it.maxBy { it.value } }
fun leastFrequentChar() = payload.charByFunc { it.minBy { it.value } }
private fun String.charByFunc(func: (Map<Char, Int>) -> Map.Entry<Char, Int>?) = toCharArray()
.groupBy { it }
.mapValues { it.value.count() }
.let(func)
?.key
}
fun findMostFrequentChars(input: String) = parseMessages(input).map(Message::mostFrequentChar).joinToString("")
fun findLeastFrequentChars(input: String) = parseMessages(input).map(Message::leastFrequentChar).joinToString("")
private fun parseMessages(input: String): List<Message> {
val lines = input.splitToLines().map(String::toList)
fun List<List<Char>>.rotate(): Array<Array<Char>> {
val result = array2d(first().size, lines.size) { '0' }
for ((x, line) in withIndex()) {
for ((y, char) in line.withIndex()) {
result[y][x] = char
}
}
return result
}
return lines.rotate().map { it.joinToString("") }.map(::Message)
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 3,597 | courses | MIT License |
src/day21/Day21.kt | easchner | 572,762,654 | false | {"Kotlin": 104604} | package day21
import readInputString
import java.lang.Exception
import java.lang.Long.max
import kotlin.system.measureNanoTime
data class Monkey(val name: String, val monkey1: String, val monkey2: String, val operation: Char, var output: Long = Long.MIN_VALUE)
fun main() {
fun recurseMonkeys(monkeys: MutableList<Monkey>, current: String, target: Long): Long {
if (current == "humn") {
return target
}
val monkey = monkeys.find { it.name == current }!!
val monkey1 = monkeys.find{ it.name == monkey.monkey1 }!!
val monkey2 = monkeys.find{ it.name == monkey.monkey2 }!!
if (monkey1.output == Long.MIN_VALUE) {
val newTarget = when (monkey.operation) {
'+' -> target - monkey2.output
'-' -> target + monkey2.output
'*' -> target / monkey2.output
'/' -> target * monkey2.output
'=' -> monkey2.output
else -> throw Exception()
}
monkey1.output = newTarget
return recurseMonkeys(monkeys, monkey1.name, newTarget)
} else {
val newTarget = when (monkey.operation) {
'+' -> target - monkey1.output
'-' -> monkey1.output - target
'*' -> target / monkey1.output
'/' -> monkey1.output / target
'=' -> monkey1.output
else -> throw Exception()
}
monkey2.output = newTarget
return recurseMonkeys(monkeys, monkey2.name, newTarget)
}
}
fun part1(input: List<String>): Long {
val monkeys = mutableListOf<Monkey>()
for (line in input) {
// root: pppw + sjmn
val name = line.substring(0, 4)
var output = Long.MIN_VALUE
var monkey1 = ""
var monkey2 = ""
var operation = ' '
if (line.length < 15) {
output = line.substringAfter(" ").toLong()
} else {
monkey1 = line.substring(6, 10)
monkey2 = line.substring(13, 17)
operation = line[11]
}
monkeys.add(Monkey(name, monkey1, monkey2, operation, output))
}
while (monkeys.find { it.name == "root"}!!.output == Long.MIN_VALUE) {
for (monkey in monkeys) {
if (monkey.output == Long.MIN_VALUE) {
val monkey1 = monkeys.find{ it.name == monkey.monkey1 }!!.output
val monkey2 = monkeys.find{ it.name == monkey.monkey2 }!!.output
if (monkey1 != Long.MIN_VALUE && monkey2 != Long.MIN_VALUE) {
monkey.output = when (monkey.operation) {
'+' -> monkey1 + monkey2
'-' -> monkey1 - monkey2
'*' -> monkey1 * monkey2
'/' -> monkey1 / monkey2
else -> throw Exception()
}
if (monkey.output < 0 && monkey1 > 0 && monkey2 > 0) {
println("Woo")
}
}
}
}
}
return monkeys.find { it.name == "root"}!!.output
}
fun part2(input: List<String>): Long {
val monkeys = mutableListOf<Monkey>()
for (line in input) {
// root: pppw + sjmn
val name = line.substring(0, 4)
var output = Long.MIN_VALUE
var monkey1 = ""
var monkey2 = ""
var operation = ' '
if (line.length < 15) {
output = line.substringAfter(" ").toLong()
} else {
monkey1 = line.substring(6, 10)
monkey2 = line.substring(13, 17)
operation = line[11]
}
// Change human's output to impossible
if (name == "humn") {
output = Long.MIN_VALUE
monkey1 = "humn"
monkey2 = "humn"
}
// Change root's operation
if (name == "root") {
operation = '='
}
monkeys.add(Monkey(name, monkey1, monkey2, operation, output))
}
var changed = true
while (changed) {
changed = false
for (monkey in monkeys) {
if (monkey.output == Long.MIN_VALUE) {
val monkey1 = monkeys.find{ it.name == monkey.monkey1 }!!.output
val monkey2 = monkeys.find{ it.name == monkey.monkey2 }!!.output
if (monkey1 != Long.MIN_VALUE && monkey2 != Long.MIN_VALUE) {
monkey.output = when (monkey.operation) {
'+' -> monkey1 + monkey2
'-' -> monkey1 - monkey2
'*' -> monkey1 * monkey2
'/' -> monkey1 / monkey2
else -> throw Exception()
}
changed = true
}
}
}
}
val root = monkeys.find { it.name == "root"}!!
val root1 = monkeys.find{ it.name == root.monkey1 }!!.output
val root2 = monkeys.find{ it.name == root.monkey2 }!!.output
root.output = max(root1, root2)
return recurseMonkeys(monkeys, "root", root.output)
}
val testInput = readInputString("day21/test")
val input = readInputString("day21/input")
check(part1(testInput) == 152L)
val time1 = measureNanoTime { println(part1(input)) }
println("Time for part 1 was ${"%,d".format(time1)} ns")
check(part2(testInput) == 301L)
val time2 = measureNanoTime { println(part2(input)) }
println("Time for part 2 was ${"%,d".format(time2)} ns")
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 5,940 | Advent-Of-Code-2022 | Apache License 2.0 |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day18/Day18.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day18
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 18](https://adventofcode.com/2020/day/18)
*/
object Day18 : DayOf2020(18) {
override fun first(): Any? {
return solve {
when (it) {
'*' -> 1
'+' -> 1
else -> -1
}
}
}
override fun second(): Any? {
return solve {
when (it) {
'*' -> 1
'+' -> 2
else -> -1
}
}
}
private fun solve(precedence: (Char) -> Int): Long {
val values = lines.map { entry ->
val numQueue = ArrayDeque<Char>()
val opQueue = ArrayDeque<Char>()
entry.reversed().forEach { char ->
when (char) {
in '0'..'9' -> numQueue += char
')' -> opQueue += char
'+', '*' -> {
val cp = precedence(char)
while (opQueue.isNotEmpty() && precedence(opQueue.last()) > cp) {
numQueue += opQueue.removeLast()
}
opQueue += char
}
'(' -> {
while (opQueue.last() != ')') {
numQueue += opQueue.removeLast()
}
opQueue.removeLast()
}
}
}
while (opQueue.isNotEmpty()) {
numQueue += opQueue.removeLast()
}
val valStack = ArrayDeque<Long>()
numQueue.forEach { op ->
when (op) {
in '0'..'9' -> valStack += op.digitToInt().toLong()
'+' -> valStack += (valStack.removeLast() + valStack.removeLast())
'*' -> valStack += (valStack.removeLast() * valStack.removeLast())
}
}
return@map valStack.first()
}
return values.sum()
}
}
fun main() = SomeDay.mainify(Day18)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,762 | adventofcode | MIT License |
src/main/kotlin/biodivine/algebra/params/SemiAlgTree.kt | daemontus | 160,796,526 | false | null | package biodivine.algebra.params
import biodivine.algebra.MPoly
import biodivine.algebra.NumQ
import biodivine.algebra.ia.Interval
import biodivine.algebra.ia.div
import biodivine.algebra.ia.minus
import biodivine.algebra.ia.plus
import biodivine.algebra.rootisolation.AdaptiveRootIsolation
import biodivine.algebra.rootisolation.Root
import biodivine.algebra.synth.Box
import cc.redberry.rings.Rings
import cc.redberry.rings.Rings.Q
import java.util.concurrent.atomic.AtomicReference
import kotlin.math.max
typealias LevelList = List<Set<MPoly>>
/*
/**
* Merge levels takes a set of bound polynomials, two level lists and a set of new polynomials
* and merges them at dimension d.
*
* This consists of:
* 1) polynomials with smaller level are transferred from add to the appropriate level
* 2) All projections and intersections with bounds in f and g are already computed
* (if they were removed, they were unnecessary), so we don't do any projections there.
* 3) However, by merging f and g, new intersections can be created - we compute these.
* 4) Finally, the newly added polynomials need to be projected and intersected with the
* rest of f and g.
* We recursively continue, adding into the lower level new polynomials which were created in
* these projections and returning as the current level the merger of f,g, and new polynomials.
*/
fun mergeLevels(
boundPolynomials: List<Pair<MPoly, MPoly>>,
f: LevelList, g: LevelList, add: Set<MPoly>, d: Int
): LevelList {
if (d == 0) return listOf(f[0] + g[0] + add)
// set of polynomials which should be transferred to a lower level
val transfer = add.filter { it.level < d }
// set of polynomials which should be added to this level
val new = add - transfer
// differences between the two levels
val extraF = f[d] - g[d]
val extraG = g[d] - f[d]
val projection = HashSet<MPoly>(transfer)
// combinations of polynomials from F and G
for (p in extraF) {
for (q in g[d]) {
projection.addAll(Projection.resultant(p, q, d))
}
}
for (p in extraG) {
for (q in f[d]) {
projection.addAll(Projection.resultant(p, q, d))
}
}
val old = f[d] + g[d]
// projection of new polynomials
new.forEach { projection.addAll(Projection.discriminant(it, d)) }
// combination of new polynomials with old and bounds
val (low, high) = boundPolynomials[d]
for (p in new) {
for (q in old) {
projection.addAll(Projection.resultant(p, q, d))
}
projection.addAll(Projection.resultant(p, low, d))
projection.addAll(Projection.resultant(p, high, d))
}
// remove elements which are already there
projection.removeAll(f[d-1])
projection.removeAll(g[d-1])
return mergeLevels(boundPolynomials, f, g, projection, d-1) + listOf(f[d] + g[d] + new)
}
/**
* Compute root pairs for this map of partially evaluated polynomials
*/
fun Map<MPoly, MPoly>.roots(bounds: Interval): List<Pair<Root, MPoly>> {
return this.flatMap { (eval, original) ->
AdaptiveRootIsolation.isolateRootsInBounds(listOf(eval.asUnivariate()), bounds)
.map { it to original }
}.sortedBy { it.first }
}
/**
* Given a list of root pairs, compute the sample points defined by the system bounds and the given roots.
*/
fun List<Pair<Root, MPoly>>.samplePoints(bounds: Interval): List<NumQ> {
val result = ArrayList<NumQ>(this.size + 1)
val (l, h) = bounds
if (this.isEmpty()) {
result.add(l + (h - l)/2)
} else {
result.add(this.first().first.middleValue(l))
for (i in 0 until (size - 1)) {
result.add(this[i].first.middleValue(this[i+1].first))
}
result.add(this.last().first.middleValue(h))
}
return result
}
sealed class SemiAlgTree {
companion object {
fun positiveSet(poly: MPoly, bounds: Box, boundPoly: List<Pair<MPoly, MPoly>>): SemiAlgTree {
val dimensions = bounds.data.size
val levels = mergeLevels(
boundPoly,
(0..dimensions).map { emptySet<MPoly>() },
(0..dimensions).map { emptySet<MPoly>() },
setOf(poly),
dimensions - 1
)
return makeTree(levels.map { level ->
level.associateBy({it}, {it})
}, bounds, emptyList(), 0, poly)
}
private fun makeTree(levels: List<Map<MPoly, MPoly>>, bounds: Box, point: List<NumQ>, d: Int, poly: MPoly): SemiAlgTree {
if (levels.isEmpty()) return Leaf(d, poly.evaluate(*point.toTypedArray()) > Q.zero)
val roots = levels.first().roots(bounds.data[d])
val cells = roots.samplePoints(bounds.data[d]).map { sample ->
makeTree(
levels.drop(1).map { level -> level.mapKeys { it.key.evaluate(d, sample) } },
bounds, point + sample, d + 1, poly
)
}
return Cylinder(d, roots, cells)
}
}
data class Leaf(override val level: Int, val member: Boolean) : SemiAlgTree() {
override val projection: Set<MPoly>
get() = emptySet()
override val roots: List<Pair<Root, MPoly>>
get() = emptyList()
override fun similar(other: SemiAlgTree): Boolean = this == other
override fun prune(): SemiAlgTree = this
override fun levelPolynomials(remaining: Int): LevelList {
return emptyLevelList (remaining)
}
override fun lookup(point: NumQ): SemiAlgTree = this
}
data class Cylinder(
override val level: Int,
override val roots: List<Pair<Root, MPoly>>,
val cells: List<SemiAlgTree>
) : SemiAlgTree() {
private var projectionCache = AtomicReference<Set<MPoly>?>()
override val projection: Set<MPoly>
get() {
return projectionCache.get() ?: run {
val transfer = cells.flatMapTo(HashSet()) { cell ->
cell.projection.filter { it.level < this.level }
}
val myPolynomials = roots.mapTo(HashSet()) { it.second }.toList()
val discriminants = myPolynomials.flatMapTo(HashSet()) { poly ->
Projection.discriminant(poly, level)
}
val resultants = HashSet<MPoly>()
for (i in myPolynomials.indices) {
for (j in (i+1) until myPolynomials.size) {
Projection.resultant(myPolynomials[i], myPolynomials[j], level).forEach {
resultants.add(it)
}
}
}
val result = transfer + discriminants + resultants
projectionCache.set(result)
result
}
}
override fun similar(other: SemiAlgTree): Boolean {
if (other !is Cylinder) return false
if (this.cells.size != other.cells.size) return false
return this.cells.asSequence().zip(other.cells.asSequence()).all { (a, b) -> a == b }
}
override fun prune(): SemiAlgTree {
val pruned = cells.map { it.prune() }
if (pruned.all { it is Leaf && it.member }) return Leaf(level, true)
if (pruned.all { it is Leaf && !it.member }) return Leaf(level, false)
val prunedRoots = ArrayList<Pair<Root, MPoly>>(roots.size)
val prunedCells = ArrayList<SemiAlgTree>(cells.size)
for (i in roots.indices) {
val r = roots[i]
val a = pruned[i]; val b = pruned[i+1]
if (r.second in a.projection || r.second in b.projection || !a.similar(b)) {
prunedRoots.add(r); prunedCells.add(a)
}
}
val last = pruned.last()
if (prunedCells.isEmpty() && last is Leaf) return Leaf(level, last.member)
return Cylinder(level, prunedRoots, prunedCells + last)
}
override fun levelPolynomials(remaining: Int): LevelList {
val parentLevels: LevelList = cells.map { it.levelPolynomials(remaining - 1) }
.fold(emptyLevelList(remaining - 1)) { a, b -> a.zip(b) }
return listOf<Set<MPoly>>(this.roots.mapTo(HashSet()) { it.second }) + parentLevels
}
override fun lookup(point: NumQ): SemiAlgTree {
val searchResult = roots.binarySearch { (root, _) -> root.compareTo(point) }
if (searchResult >= 0) {
error("The point $point is also a root in $roots. This should not happen!")
} else {
return cells[(-searchResult - 1)]
}
}
}
abstract val projection: Set<MPoly>
abstract val level: Int
abstract val roots: List<Pair<Root, MPoly>>
abstract fun levelPolynomials(remaining: Int): LevelList
abstract fun prune(): SemiAlgTree
abstract fun similar(other: SemiAlgTree): Boolean
abstract fun lookup(point: NumQ): SemiAlgTree
}
fun emptyLevelList(size: Int): LevelList = (1..size).map { emptySet<MPoly>() }
*/
fun LevelList.zip(other: LevelList): LevelList {
if (this.size < other.size) return other.zip(this)
// this is larger
val result = ArrayList(this)
for (i in other.indices) {
result[i] = result[i] + other[i]
}
return result
} | 0 | Kotlin | 0 | 0 | ed4fd35015b73ea3ac36aecb1c5a568f6be7f14c | 9,569 | biodivine-algebraic-toolkit | MIT License |
src/adventofcode/Day08.kt | Timo-Noordzee | 573,147,284 | false | {"Kotlin": 80936} | package adventofcode
import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
import kotlin.math.absoluteValue
/**
* @param si the starting value for i
* @param sj the starting value for j
* @param di the delta value for i
* @param dj the delta value for j
*/
fun Array<IntArray>.vd(si: Int, sj: Int, di: Int, dj: Int): Int {
val height = this[si][sj]
var i = si + di
var j = sj + dj
while (i in indices && j in 0 until this[0].size) {
if (this[i][j] >= height) return (i - si).absoluteValue + (j - sj).absoluteValue
i += di
j += dj
}
return (i - si - di).absoluteValue + (j - sj - dj).absoluteValue
}
@State(Scope.Benchmark)
@Fork(1)
@Warmup(iterations = 0)
@Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS)
class Day08 {
var input: List<String> = emptyList()
@Setup
fun setup() {
input = readInput("Day08")
}
private fun parseTrees() = input.map { line -> line.map { char -> char - '0' }.toIntArray() }.toTypedArray()
@Benchmark
fun part1(): Int {
val grid = parseTrees()
val visible = Array(grid.size) { Array(grid[0].size) { false } }
var maxHeight: Int
// Left to right
for (i in grid.indices) {
maxHeight = -1
for (j in 0 until grid.first().lastIndex) {
val height = grid[i][j]
if (height > maxHeight) {
maxHeight = height
visible[i][j] = true
}
}
}
// Right to left
for (i in grid.indices) {
maxHeight = -1
for (j in grid.first().lastIndex downTo 1) {
val height = grid[i][j]
if (height > maxHeight) {
maxHeight = height
visible[i][j] = true
}
}
}
// Top to bottom
for (j in grid[0].indices) {
maxHeight = -1
for (i in 0 until grid.lastIndex) {
val height = grid[i][j]
if (height > maxHeight) {
maxHeight = height
visible[i][j] = true
}
}
}
// Bottom to top
for (j in grid[0].indices) {
maxHeight = -1
for (i in grid.lastIndex downTo 1) {
val height = grid[i][j]
if (height > maxHeight) {
maxHeight = height
visible[i][j] = true
}
}
}
return visible.sumOf { row -> row.count { it } }
}
@Benchmark
fun part2(): Int = with(parseTrees()) {
(1 until lastIndex).maxOf { i ->
(1 until this[i].lastIndex).maxOf { j ->
vd(i, j, 1, 0) * vd(i, j, -1, 0) * vd(i, j, 0, 1) * vd(i, j, 0, -1)
}
}
}
}
fun main() {
val day08 = Day08()
// test if implementation meets criteria from the description, like:
day08.input = readInput("Day08_test")
check(day08.part1() == 21)
check(day08.part2() == 8)
day08.input = readInput("Day08")
println(day08.part1())
println(day08.part2())
} | 0 | Kotlin | 0 | 2 | 10c3ab966f9520a2c453a2160b143e50c4c4581f | 3,237 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day01.kt | szymon-kaczorowski | 572,839,642 | false | {"Kotlin": 45324} | fun main() {
fun part1(input: List<String>): Int {
var max = 0;
var current = 0;
for (line in input) {
if (line.isEmpty()) current = 0 else
current += line.toInt()
if (current > max) max = current
}
return max
}
fun part2(input: List<String>): Int {
val maxSet = mutableSetOf(0)
var current = 0;
for (line in input) {
if (line.isEmpty()) {
if (maxSet.any { it<current }){
maxSet+=current
if (maxSet.size>3){
maxSet.remove(maxSet.min())
}
}
current = 0
} else
current += line.toInt()
}
return maxSet.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1d7ab334f38a9e260c72725d3f583228acb6aa0e | 1,061 | advent-2022 | Apache License 2.0 |
src/main/kotlin/g0701_0800/s0773_sliding_puzzle/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0701_0800.s0773_sliding_puzzle
// #Hard #Array #Breadth_First_Search #Matrix
// #2023_03_10_Time_166_ms_(100.00%)_Space_35_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
private class Node(var board: String, var depth: Int, var y: Int, var x: Int)
fun slidingPuzzle(board: Array<IntArray>): Int {
val targetStr = "123450"
val sb = StringBuilder()
var y = 0
var x = 0
for (i in board.indices) {
for (j in board[0].indices) {
if (board[i][j] == 0) {
y = i
x = j
}
sb.append(board[i][j])
}
}
val seen: MutableSet<String> = HashSet()
val q: Queue<Node> = LinkedList()
q.add(Node(sb.toString(), 0, y, x))
val dir = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1))
while (q.isNotEmpty()) {
val next = q.poll()
val s = next.board
if (!seen.contains(s)) {
if (s == targetStr) {
return next.depth
}
val nextDepth = next.depth + 1
y = next.y
x = next.x
for (vector in dir) {
val nextY = y + vector[0]
val nextX = x + vector[1]
if (0 <= nextY && nextY < board.size && 0 <= nextX && nextX < board[0].size) {
val newBoard = swap(s, y, x, nextY, nextX)
q.add(Node(newBoard, nextDepth, nextY, nextX))
}
}
seen.add(s)
}
}
return -1
}
private fun swap(board: String, y1: Int, x1: Int, y2: Int, x2: Int): String {
val arr = board.toCharArray()
val t = board[y1 * 3 + x1]
arr[y1 * 3 + x1] = board[y2 * 3 + x2]
arr[y2 * 3 + x2] = t
return String(arr)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,015 | LeetCode-in-Kotlin | MIT License |
src/y2016/Day15.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.readInput
object Day15 {
private fun parse(input: List<String>): List<Pair<Int, Int>> {
return input.map {
val els = it.split(' ')
els[3].toInt() to els.last().dropLast(1).toInt()
}
}
fun part1(input: List<String>): Int {
val initialState = parse(input)
val (divisors, remainders) = initialState.mapIndexed { idx, (divisor, rest) ->
divisor to (divisor - rest - idx - 1).mod(divisor)
}.unzip()
var result = 0
while (true) {
if (divisors.map { result % it } == remainders) {
return result
}
result++
}
}
fun part2(input: List<String>): Int {
val initialState = parse(input) + listOf(11 to 0)
val (divisors, remainders) = initialState.mapIndexed { idx, (divisor, rest) ->
divisor to (divisor - rest - idx - 1).mod(divisor)
}.unzip()
var result = 0
while (true) {
if (divisors.map { result % it } == remainders) {
return result
}
result++
}
}
}
fun main() {
val testInput = """
Disc #1 has 5 positions; at time=0, it is at position 4.
Disc #2 has 2 positions; at time=0, it is at position 1.
""".trimIndent().split("\n")
println("------Tests------")
println(Day15.part1(testInput))
println(Day15.part2(testInput))
println("------Real------")
val input = readInput("resources/2016/day15")
println(Day15.part1(input))
println(Day15.part2(input))
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,614 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/jaspervanmerle/aoc2020/day/Day14.kt | jmerle | 317,518,472 | false | null | package com.jaspervanmerle.aoc2020.day
class Day14 : Day("17765746710228", "4401465949086") {
private abstract class Program {
protected val memory = mutableMapOf<Long, Long>()
protected var mask = ""
protected abstract fun writeValue(address: Long, value: Long)
fun processInstruction(instruction: String) {
val (operation, argument) = instruction.split(" = ")
if (operation == "mask") {
mask = argument
} else {
writeValue(operation.split("[")[1].split("]")[0].toLong(), argument.toLong())
}
}
fun getResult(): Long {
return memory.values.sum()
}
}
private class ProgramV1 : Program() {
override fun writeValue(address: Long, value: Long) {
val binaryValue = value
.toString(2)
.padStart(mask.length, '0')
memory[address] = mask.indices
.map { if (mask[it] != 'X') mask[it] else binaryValue[it] }
.joinToString("")
.toLong(2)
}
}
private class ProgramV2 : Program() {
override fun writeValue(address: Long, value: Long) {
val binaryAddress = address
.toString(2)
.padStart(mask.length, '0')
val resolvedAddress = mask.indices
.map { if (mask[it] != '0') mask[it] else binaryAddress[it] }
.joinToString("")
if (!resolvedAddress.contains("X")) {
memory[resolvedAddress.toLong(2)] = value
return
}
forEachCombination(resolvedAddress.count { it == 'X' }) { combination ->
var nextIndex = 0
val actualAddress = mask.indices
.map {
if (resolvedAddress[it] == 'X') {
val combinationValue = combination[nextIndex].toString()
nextIndex++
combinationValue
} else {
resolvedAddress[it]
}
}
.joinToString("")
.toLong(2)
memory[actualAddress] = value
}
}
private fun forEachCombination(
size: Int,
current: IntArray = IntArray(size),
nextIndex: Int = 0,
action: (IntArray) -> Unit
) {
if (nextIndex == size) {
action(current)
} else {
for (i in 0..1) {
current[nextIndex] = i
forEachCombination(size, current, nextIndex + 1, action)
}
}
}
}
private val instructions = getInput().lines()
override fun solvePartOne(): Any {
val program = ProgramV1()
for (instruction in instructions) {
program.processInstruction(instruction)
}
return program.getResult()
}
override fun solvePartTwo(): Any {
val program = ProgramV2()
for (instruction in instructions) {
program.processInstruction(instruction)
}
return program.getResult()
}
}
| 0 | Kotlin | 0 | 0 | 81765a46df89533842162f3bfc90f25511b4913e | 3,327 | advent-of-code-2020 | MIT License |
src/main/kotlin/kt/kotlinalgs/app/graph/ConnectedComponents.ws.kts | sjaindl | 384,471,324 | false | null | package kt.kotlinalgs.app.graph
println("Test")
Solution().test()
data class Vertice<T>(
val value: T
)
class UndirectedGraphWithAdjList<T>(val vertices: List<Vertice<T>> = emptyList()) {
private val adjList: MutableMap<Vertice<T>, MutableList<Vertice<T>>> = mutableMapOf()
fun addEdge(from: Vertice<T>, to: Vertice<T>) {
val neighbours = adjList[from] ?: mutableListOf()
neighbours.add(to)
adjList[from] = neighbours
val neighbours2 = adjList[to] ?: mutableListOf()
neighbours2.add(from)
adjList[to] = neighbours2
}
fun neighbours(of: Vertice<T>): List<Vertice<T>> {
return adjList[of] ?: emptyList()
}
}
class ConnectedComponentChecker<T> {
fun numOfConnectedComponents(graph: UndirectedGraphWithAdjList<T>): Int {
val visited: MutableSet<Vertice<T>> = mutableSetOf()
var componentsCount = 0
graph.vertices.forEach {
if (!visited.contains(it)) {
componentsCount++
dfs(graph, it, visited)
}
}
return componentsCount
}
private fun dfs(
graph: UndirectedGraphWithAdjList<T>,
vertice: Vertice<T>,
visited: MutableSet<Vertice<T>>
) {
visited.add(vertice)
graph.neighbours(vertice).forEach {
if (!visited.contains(it)) {
dfs(graph, it, visited)
}
}
}
}
class Solution {
fun test() {
val vertice1 = Vertice(1)
val vertice2 = Vertice(2)
val vertice3 = Vertice(3)
val vertice4 = Vertice(4)
val vertice5 = Vertice(5)
val vertice6 = Vertice(6)
val graph = UndirectedGraphWithAdjList<Int>(
vertices = listOf(
vertice1, vertice2, vertice3, vertice4, vertice5, vertice6
)
)
graph.addEdge(vertice1, vertice2)
graph.addEdge(vertice3, vertice4)
graph.addEdge(vertice5, vertice6)
graph.addEdge(vertice6, vertice1)
// 1 -> 2 .. 3 -> 4 .. 5 -> 6 -> 1
val connectedComponentChecker = ConnectedComponentChecker<Int>()
println(connectedComponentChecker.numOfConnectedComponents(graph))
}
}
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 2,238 | KotlinAlgs | MIT License |
src/Day03.kt | NatoNathan | 572,672,396 | false | {"Kotlin": 6460} | fun Char.getPriority(): Int = when {
this.isLowerCase() -> this.code -96
this.isUpperCase() -> this.code - 38
else -> throw Exception("Not a Letter")
}
fun getHalfs(items: String): List<String> = items.chunked(items.length/2)
fun getErrorItem(items: List<String>): Char {
val (one, two) = items
return one.find { two.contains(it) }!!
}
fun getBadge(items: List<String>): Char {
val (one, two, three) = items
return one.find { two.contains(it) && three.contains(it) }!!
}
fun main() {
val day = "Day03"
val testOutputPart1 = 157
fun part1(input: List<String>): Int = input.sumOf { getErrorItem(getHalfs(it)).getPriority() }
val testOutputPart2 = 70
fun part2(input: List<String>): Int = input.chunked(3).sumOf { getBadge(it).getPriority() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
check(part1(testInput) == testOutputPart1)
check(part2(testInput) == testOutputPart2)
val input = readInput(day)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c0c9e2a2d0ca2503afe33684a3fbba1f9eefb2b0 | 1,109 | advent-of-code-kt | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2020/Day14.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2020
import com.s13g.aoc.*
/**
* --- Day 14: Docking Data ---
* https://adventofcode.com/2020/day/14
*/
val memRegex = """mem\[(\d+)\] = (\d+)$""".toRegex()
class Day14 : Solver {
override fun solve(lines: List<String>): Result {
val input = parseInput(lines)
// Part A: Use Mask to change the value. Leave address unchanged.
val memA = mutableMapOf<Int, Long>()
for (assignment in input) {
val newValue = String(decTo36Bin(assignment.value).mapIndexed { idx, it ->
when (assignment.mask[idx]) {
'0' -> '0'
'1' -> '1'
else -> it
}
}.toCharArray()).toLong(2)
memA[assignment.addr] = newValue
}
// Part B: Use mask to generate more addresses. Leave value unchanged.
val memB = mutableMapOf<Long, Long>()
for (assignment in input) {
val newAddrStr = String(decTo36Bin(assignment.addr).mapIndexed { idx, it ->
when (assignment.mask[idx]) {
'0' -> it
'1' -> '1'
else -> 'X'
}
}.toCharArray())
val addresses = mutableListOf<Long>()
genAllFloatingAddresses(newAddrStr.toCharArray(), addresses)
addresses.forEach { memB[it] = assignment.value.toLong() }
}
return Result("${memA.values.sum()}", "${memB.values.sum()}")
}
private fun genAllFloatingAddresses(str: CharArray, result: MutableList<Long>) {
if (str.count { it == 'X' } == 0) result.add(String(str).toLong(2))
for (s in str.indices) {
if (str[s] == 'X') {
// Generate two versions with the first X replaced with 0 and 1. Apply recursively.
genAllFloatingAddresses(str.mapIndexed { i, c -> if (i == s) '0' else c }.toCharArray(), result)
genAllFloatingAddresses(str.mapIndexed { i, c -> if (i == s) '1' else c }.toCharArray(), result)
break;
}
}
}
/** Take an integer and produce a (if needed padded) 36 long binary representation of it. */
private fun decTo36Bin(v: Int) = Integer.toBinaryString(v).padStart(36, '0')
/** Parse input into list of MemAction which holds all the info needed. */
private fun parseInput(lines: List<String>): List<MemAction> {
val result = mutableListOf<MemAction>()
var mask = ""
for (line in lines) {
// Lines are either a new mask or memory assignments.
if (line.startsWith("mask")) {
mask = line.substring(7)
} else {
val (addr, value) = memRegex.find(line)!!.destructured
result.add(MemAction(mask, addr.toInt(), value.toInt()))
}
}
return result
}
private class MemAction(val mask: String, val addr: Int, val value: Int)
}
| 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,671 | euler | Apache License 2.0 |
src/Day05.kt | arturradiuk | 571,954,377 | false | {"Kotlin": 6340} | import java.util.stream.Collectors.*
fun main() {
fun method(input: List<String>, stackFlow: Boolean): String {
val chunkedStacks = input.takeWhile { it != "" }.map { it.chunked(4) }
val indexToElement = chunkedStacks.dropLast(1).flatMap {
it.mapIndexedNotNull { index, string ->
if (string.isBlank()) null else index to string
}
}
val indexToStack = indexToElement.stream()
.collect(groupingBy({ it.first }, mapping(Pair<Int, String>::second, toList())))
val numberRegex = Regex("\\d+")
input.dropWhile { it.isNotEmpty() }.drop(1).map { numberRegex.findAll(it).toList().map(MatchResult::value) }
.forEach {
val (first, second, third) = it
val let = indexToStack.getOrError(second.toInt() - 1).popFirst(first.toInt(), reversed = stackFlow)
indexToStack.getOrError(third.toInt() - 1).addAll(0, let)
}
val bracketsRegex = Regex("(\\[|\\])")
return indexToStack.map { it.value.first().trim() }.joinToString("").replace(bracketsRegex, "")
}
fun partOne(input: List<String>): String = method(input, stackFlow = true)
fun partTwo(input: List<String>): String = method(input, stackFlow = false)
val input = readInput("Day05_test")
println(partOne(input))
println(partTwo(input))
}
fun MutableList<String>.popFirst(n: Int = 1, reversed: Boolean): List<String> =
(0 until n).fold<Int, MutableList<String>>(mutableListOf()) { total,
_ ->
total.add(this.removeFirst())
total
}.apply {
if (reversed) return this.reversed()
}
fun <K, V> Map<K, MutableList<V>>.getOrError(key: K): MutableList<V> {
return getOrElse(key) { error("There is no such key in map") }
} | 0 | Kotlin | 0 | 0 | 85ef357643e5e4bd2ba0d9a09f4a2d45653a8e28 | 1,881 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Day3.kt | ueneid | 575,213,613 | false | null | class Day3(val inputs: List<String>) {
private fun getPriority(c: Char): Int {
return if (c.isUpperCase()) {
c.lowercaseChar() - 'a' + 1 + 26
} else {
c - 'a' + 1
}
}
fun solve1(): Int {
return inputs.asSequence()
.map { line -> line.chunked(line.length / 2) }
.map { it.map { s -> s.toSet() } }
.map { it[0].intersect(it[1]) }
.sumOf { getPriority(it.first()) }
}
fun solve2(): Int {
return inputs.asSequence().chunked(3)
.map { it.map { s -> s.toSet() } }
.map { it[0].intersect(it[1]).intersect(it[2]) }
.sumOf { getPriority(it.first()) }
}
}
fun main() {
val obj = Day3(Resource.resourceAsListOfString("day3/input.txt"))
println(obj.solve1())
println(obj.solve2())
}
| 0 | Kotlin | 0 | 0 | 743c0a7adadf2d4cae13a0e873a7df16ddd1577c | 858 | adventcode2022 | MIT License |
runner/src/main/kotlin/com/grappenmaker/aoc/Benchmark.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc
import kotlin.io.path.exists
import kotlin.io.path.readLines
import kotlin.system.measureTimeMillis
fun main(args: Array<String>) {
fun Puzzle.input() = defaultInput(year, day)
fun Puzzle.format() = "Year $year Day $day"
fun Puzzle.run() = SolveContext(this, input().readLines()).implementation()
val (available, missing) = puzzles.partition { it.input().exists() }
if (missing.isNotEmpty()) {
println("Missing inputs (${missing.size}) (skipped):")
missing.forEach { println("Year ${it.year} Day ${it.day}") }
println()
}
val willRun = if (args.isNotEmpty()) {
val year = args.first().toInt()
println("Will only run puzzles in year $year")
println()
available.filter { it.year == year }
} else available
require(willRun.isNotEmpty()) { "no puzzles, sad" }
println("\"Warming up\" by running a few random puzzles... if you are unlucky, this can take a while")
repeat(5) { willRun.random().run() }
println("Running ${willRun.size}/${puzzles.size} (available) puzzles, this will take a while...")
println()
val runningYears = willRun.mapTo(hashSetOf()) { it.year }
val benches = years.filter { it.year in runningYears }.map { set ->
set.year to set.puzzles.filter { it in willRun }.map { it to measureTimeMillis { it.run() } }
}
println("All results:")
benches.sortedBy { it.first }.forEach { (set, perPuzzle) ->
println("- Year $set (${perPuzzle.sumOf { (_, t) -> t }}ms)")
perPuzzle.sortedBy { it.first.day }.forEach { (puzzle, time) -> println("\t- Day ${puzzle.day}: ${time}ms") }
println("Fastest puzzle: Day ${perPuzzle.minBy { it.second }.first.day}")
println("Slowest puzzle: Day ${perPuzzle.maxBy { it.second }.first.day}")
}
println()
println(
"Fastest year (based on median): ${
benches.minBy { (_, perPuzzle) ->
val sorted = perPuzzle.map { it.second }.sorted()
sorted[sorted.size / 2]
}.first
}"
)
println("Fastest year (based on mean): ${benches.minBy { (_, p) -> p.sumOf { it.second } / p.size }.first}")
val allBenches = benches.flatMap { it.second }
println("Fastest puzzle: ${allBenches.minBy { it.second }.first.format()}")
println("Slowest puzzle: ${allBenches.maxBy { it.second }.first.format()}")
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,432 | advent-of-code | The Unlicense |
src/Day11.kt | arisaksen | 573,116,584 | false | {"Kotlin": 42887} | import org.assertj.core.api.Assertions.assertThat
// https://adventofcode.com/2022/day/11
fun main() {
data class Test(
var divisible: Long,
val ifTestTrue: Int,
val ifTestFalse: Int
)
data class Monkey(
val startingItems: MutableList<Long>,
val operation: List<String>,
val test: Test,
)
data class Actions(
private val input: String,
) {
val monkeys = mutableMapOf<Int, Monkey>()
var rounds: Int = 0
var monkeyItemInspect = mutableMapOf<Int, Long>()
fun monkeyStealItems() {
input
.split("\n\n")
.map { it.split("\n") }
.forEach {
val monkeyNumber = it[0][7].digitToInt()
val startingItems: MutableList<Long> =
it[1].substringAfterLast(":").split(", ")
.map { it.replace(" ", "").toLong() }.toMutableList()
monkeys.put(
monkeyNumber, Monkey(
operation = it[2].substringAfterLast("old ").split(" ").toMutableList(),
startingItems = startingItems,
test = Test(
divisible = it[3].split(" ").last().toLong(),
ifTestTrue = it[4].split(" ").last().toInt(),
ifTestFalse = it[5].split(" ").last().toInt()
)
)
)
monkeyItemInspect[monkeyNumber] = 0L
}
}
fun divisibility(): Long = monkeys.values.map { it.test.divisible }.reduce(Long::times)
// equivalent fun divisibility(): Long = monkeys.values.map { it.test.divisible }.reduce { acc: Long, elem: Long -> acc * elem }
fun round(relief: (Long) -> Long) {
rounds++
monkeys.forEach { monkey ->
monkey.value.startingItems.forEach { item ->
monkeyItemInspect[monkey.key] = monkeyItemInspect[monkey.key]!! + 1
var itemToThrow: Long = item
when (monkey.value.operation.first()) {
"*" -> {
if (monkey.value.operation.last() == "old") {
itemToThrow = relief(item * item)
} else {
itemToThrow = relief(item * monkey.value.operation.last().toLong())
}
}
"+" -> itemToThrow = relief(item + monkey.value.operation.last().toLong())
else -> error("check input for monkey ${monkey.key}, ${monkey.value.operation}")
}
// print("Round $rounds: Monkey ${monkey.key} throw $itemToThrow($item ${monkey.value.operation} / ${relief}) ")
if (itemToThrow % monkey.value.test.divisible == 0L) {
monkeys[monkey.value.test.ifTestTrue]?.startingItems?.add(itemToThrow)
// print("(is divisable by ${monkey.value.test.divisible})")
// print(" to Monkey${monkey.value.test.ifTestTrue}")
} else {
monkeys[monkey.value.test.ifTestFalse]?.startingItems?.add(itemToThrow)
// print("(not divisable by ${monkey.value.test.divisible})")
// print(" to Monkey${monkey.value.test.ifTestFalse}")
}
// println()
}
monkey.value.startingItems.clear()
}
}
fun monkeyBussiness(): Long =
monkeyItemInspect
.map { it.value }
.sortedDescending()
.take(2)
.fold(1L) { acc, item -> acc * item }
fun printMonkeyBussiness(): Unit {
if (rounds == 20 || rounds % 1000 == 0) {
println("== After round ${rounds} ==")
monkeyItemInspect.forEach {
println("Monkey ${it.key} ${it.value} times")
}
}
}
}
fun part1(input: String): Long =
Actions(input)
.apply { monkeyStealItems() }
.apply { repeat(20) { round() { Long -> Long / 3L } } }
.run { monkeyBussiness() }
fun part2(input: String): Long =
Actions(input)
.apply { monkeyStealItems() }
.apply {
repeat(10_000) {
round() { Long -> Long % divisibility() }
printMonkeyBussiness()
}
}
.run { monkeyBussiness() }
// test if implementation meets criteria from the description, like:
val testInput = readText("Day11_test")
assertThat(part1(testInput)).isEqualTo(10605)
assertThat(part2(testInput)).isEqualTo(2713310158)
// print the puzzle answer
val input = readText("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 85da7e06b3355f2aa92847280c6cb334578c2463 | 5,152 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/jaspervanmerle/aoc2020/day/Day19.kt | jmerle | 317,518,472 | false | null | package com.jaspervanmerle.aoc2020.day
class Day19 : Day("285", "412") {
private val inputParts = getInput().split("\n\n")
private val rules = inputParts[0]
.lines()
.map {
val parts = it.split(": ")
parts[0].toInt() to parts[1]
}
.toMap()
.toMutableMap()
private val messages = inputParts[1].lines()
override fun solvePartOne(): Any {
return countMatchingMessages(false)
}
override fun solvePartTwo(): Any {
return countMatchingMessages(true)
}
private fun countMatchingMessages(advanced: Boolean): Int {
val regex = "^${parseRule(0, advanced)}$".toRegex()
return messages.count { regex.matches(it) }
}
private fun parseRule(ruleIndex: Int, advanced: Boolean): String {
val rule = rules[ruleIndex]!!
if (advanced) {
if (ruleIndex == 8) {
return "(${parseRule(42, true)})+"
} else if (ruleIndex == 11) {
val first = parseRule(42, true)
val second = parseRule(31, true)
val parts = (1..10).map { "(${first.repeat(it)}${second.repeat(it)})" }
return "(${parts.joinToString("|")})"
}
}
return if (rule.contains(" | ")) {
val patterns = rule
.split(" | ")
.map { parseSingleRule(it, advanced) }
"(${patterns.joinToString("|")})"
} else {
parseSingleRule(rule, advanced)
}
}
private fun parseSingleRule(rule: String, advanced: Boolean): String {
if (rule.startsWith("\"")) {
return rule[1].toString()
}
val pattern = rule
.split(" ")
.joinToString("") { parseRule(it.toInt(), advanced) }
return "($pattern)"
}
}
| 0 | Kotlin | 0 | 0 | 81765a46df89533842162f3bfc90f25511b4913e | 1,870 | advent-of-code-2020 | MIT License |
src/main/kotlin/com/github/dangerground/aoc2020/Day4.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
import java.lang.Exception
class Day4(batches: List<List<String>>) {
var passports = batches.map { Passport(it) }
fun countPassportsWithRequiredField() = passports.filter { it.hasRequiredFields() }.count()
fun countValidPassports() = passports.filter { it.isValid() }.count()
}
class Passport(lines: List<String>) {
private val expectedFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
private val expectedEyeColor = listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
private val expectedHairColor = Regex("^#[0-9a-f]{6}$")
private val expectedPassportNumber = Regex("^[0-9]{9}$")
private val fields = HashMap<String, String>()
init {
lines.joinToString(" ")
.trim()
.split(Regex.fromLiteral(" "))
.map { it.split(":") }
.forEach {
fields[it[0]] = it[1]
}
}
fun size() = fields.size
fun hasRequiredFields(): Boolean {
return expectedFields.filter { fields[it] != null }.count() == expectedFields.size
}
fun isValid(): Boolean {
return hasRequiredFields()
&& isValidBirthYear()
&& isValidIssueYear()
&& isValidExpirationYear()
&& isValidHeight()
&& isValidHairColor()
&& isValidEyeColor()
&& isValidPassportNumber()
}
private fun isValidBirthYear() = isYearBetween("byr", 1920, 2002)
private fun isValidIssueYear() = isYearBetween("iyr", 2010, 2020)
private fun isValidExpirationYear() = isYearBetween("eyr", 2020, 2030)
private fun isValidHeight() = isHeightBetween("in", 59, 76) || isHeightBetween("cm", 150, 193)
private fun isValidHairColor() = fields.getOrDefault("hcl", "").matches(expectedHairColor)
private fun isValidEyeColor() = expectedEyeColor.contains(fields.getOrDefault("ecl", ""))
private fun isValidPassportNumber() = fields.getOrDefault("pid", "").matches(expectedPassportNumber)
private fun isYearBetween(field: String, lower: Int, upper: Int): Boolean {
return try {
val year = fields.getOrDefault(field, "").toInt()
year in lower..upper
} catch (e: Exception) {
false
}
}
private fun isHeightBetween(unit: String, lower: Int, upper: Int): Boolean {
val height = fields.getOrDefault("hgt", "")
if (!height.matches(Regex("^\\d+$unit$"))) {
return false
}
return try {
val heightNumber = height.substring(0, height.length - unit.length).toInt()
heightNumber in lower..upper
} catch (e: Exception) {
false
}
}
}
fun main() {
val input = DayInput.batchesOfStringList(4)
val day4 = Day4(input)
// part 1
val part1 = day4.countPassportsWithRequiredField()
println("result part 1: $part1")
// part2
val part2 = day4.countValidPassports()
println("result part 2: $part2")
} | 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 3,118 | adventofcode-2020 | MIT License |
src/main/kotlin/com/github/amolkov/kotlin/algorithms/sorting/MergeSort.kt | amolkov | 122,844,991 | false | null | package com.github.amolkov.kotlin.algorithms.sorting
class MergeSort {
companion object {
/**
* Sorts the specified array into ascending order, according to the natural ordering of its elements,
* using the merge sort algorithm.
*
* @param arr the array to be sorted
*/
fun sort(arr: Array<Int>) {
val helper = Array(arr.size) { 0 }
sort(arr, 0, arr.size - 1, helper)
}
private fun sort(arr: Array<Int>, lo: Int, hi: Int, helper: Array<Int>) {
if (lo >= hi) {
return
}
val mid = lo + (hi - lo) / 2
sort(arr, lo, mid, helper)
sort(arr, mid + 1, hi, helper)
merge(arr, lo, mid, hi, helper)
}
private fun merge(arr: Array<Int>, lo: Int, mid: Int, hi: Int, helper: Array<Int>) {
(lo..hi).forEach { helper[it] = arr[it] }
var left = lo
var right = mid + 1
(lo..hi).forEach {
when {
left > mid -> arr[it] = helper[right++]
right > hi -> arr[it] = helper[left++]
helper[left] <= helper[right] -> arr[it] = helper[left++]
else -> arr[it] = helper[right++]
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | acb6bc2e397087fec8432b3307d0c0ea0c6ba75b | 1,363 | kotlin-algorithms | Apache License 2.0 |
src/main/kotlin/d17_TrickShot/TrickShot.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package d17_TrickShot
import util.Input
import util.Output
fun main() {
Output.day(17, "Trick Shot")
val startTime = Output.startTime()
val targetArea = Input.parseAllText(filename = "/input/d17_target_area.txt")
.split(',')
.map { it.substringAfter("=").split("..").map { n -> n.toInt() } }
val yMaxVelo = (targetArea[1][0] + 1) * -1
Output.part(1, "Highest Y Position", (yMaxVelo * (yMaxVelo + 1)) / 2)
val possibleXVelos = mutableListOf<Pair<Int, Int>>()
val possibleYVelos = mutableListOf<Pair<Int, Int>>()
val maxSteps = (yMaxVelo * 2) + 2
for (step in 1..maxSteps) {
possibleXVelos.addAll(
(1..targetArea[0][1]).mapNotNull { n ->
if ((1..step).sumOf {
val x = n - (it - 1)
if (x > 0) x else 0
} in targetArea[0][0]..targetArea[0][1])
Pair(step, n)
else null
}
)
possibleYVelos.addAll(
(targetArea[1][0]..yMaxVelo).mapNotNull { n ->
if ((1..step).sumOf { n - (it - 1) } in targetArea[1][0]..targetArea[1][1])
Pair(step, n)
else null
}
)
}
val distinctInitialPairs = possibleYVelos.mapNotNull { y ->
val x = possibleXVelos.filter { it.first == y.first }
if (x.isNotEmpty())
x.map { Pair(it.second, y.second) }
else null
}.flatten().toSet()
Output.part(2, "Distinct Initial Velocity Values", distinctInitialPairs.size)
Output.executionTime(startTime)
}
| 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 1,625 | advent-of-code-2021 | MIT License |
src/main/kotlin/com/leetcode/P959.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/286
class P959 {
fun regionsBySlashes(grid: Array<String>): Int {
val n = grid.size
val arr = Array(n * 3) { IntArray(n * 3) }
for (i in 0 until (n * n)) {
val p = intArrayOf(i / n * 3, i % n * 3)
when (grid[i / n][i % n]) {
'\\' -> {
arr[p[0]][p[1]] = 1
arr[p[0] + 1][p[1] + 1] = 1
arr[p[0] + 2][p[1] + 2] = 1
}
'/' -> {
arr[p[0]][p[1] + 2] = 1
arr[p[0] + 1][p[1] + 1] = 1
arr[p[0] + 2][p[1]] = 1
}
}
}
var answer = 0
for (i in arr.indices) {
for (j in arr[i].indices) {
if (arr[i][j] == 0) {
dfs(arr, i, j)
answer++
}
}
}
return answer
}
private fun dfs(grid: Array<IntArray>, i: Int, j: Int) {
if (i !in 0..grid.lastIndex) return
if (j !in 0..grid[i].lastIndex) return
if (grid[i][j] == 1) return
grid[i][j] = 1
dfs(grid, i - 1, j)
dfs(grid, i + 1, j)
dfs(grid, i, j - 1)
dfs(grid, i, j + 1)
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,334 | algorithm | MIT License |
src/leetcodeProblem/leetcode/editor/en/RotateArray.kt | faniabdullah | 382,893,751 | false | null | //Given an array, rotate the array to the right by k steps, where k is non-
//negative.
//
//
// Example 1:
//
//
//Input: nums = [1,2,3,4,5,6,7], k = 3
//Output: [5,6,7,1,2,3,4]
//Explanation:
//rotate 1 steps to the right: [7,1,2,3,4,5,6]
//rotate 2 steps to the right: [6,7,1,2,3,4,5]
//rotate 3 steps to the right: [5,6,7,1,2,3,4]
//
//
// Example 2:
//
//
//Input: nums = [-1,-100,3,99], k = 2
//Output: [3,99,-1,-100]
//Explanation:
//rotate 1 steps to the right: [99,-1,-100,3]
//rotate 2 steps to the right: [3,99,-1,-100]
//
//
//
// Constraints:
//
//
// 1 <= nums.length <= 10⁵
// -2³¹ <= nums[i] <= 2³¹ - 1
// 0 <= k <= 10⁵
//
//
//
// Follow up:
//
//
// Try to come up with as many solutions as you can. There are at least three
//different ways to solve this problem.
// Could you do it in-place with O(1) extra space?
//
// Related Topics Array Math Two Pointers 👍 6302 👎 1055
package leetcodeProblem.leetcode.editor.en
class RotateArray {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun rotate(nums: IntArray, k: Int) {
var k = k
k %= nums.size
reverse(nums, 0, nums.size - 1)
reverse(nums, 0, k - 1)
reverse(nums, k, nums.size - 1)
}
private fun reverse(nums: IntArray, start: Int, end: Int) {
var start = start
var end = end
while (start < end) {
val temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start++
end--
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {
println(RotateArray.Solution().rotate(intArrayOf(1, 2, 3, 4, 5, 6 , 7) , 3))
}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 1,943 | dsa-kotlin | MIT License |
12.kts | pin2t | 725,922,444 | false | {"Kotlin": 48856, "Go": 48364, "Shell": 54} | import java.util.*
var springs: String = ""
var sizes: ArrayList<Int> = ArrayList<Int>()
val cache = HashMap<Pair<Int, Int>, Long>()
fun matched(prefix: String): Boolean {
return prefix.filterIndexed { index, c -> c == springs[index] || springs[index] == '?' }.count() == prefix.length
}
fun matches(prefix: String = "", group: Int = 0): Long {
if (prefix.length > springs.length) return 0
val key = Pair(prefix.length, group)
if (cache.contains(key)) return cache[key]!!
if (group == sizes.size) {
return if (matched(prefix + ".".repeat(springs.length - prefix.length))) 1 else 0
}
var result: Long = 0
for (i in 0..<(springs.length - sizes[group])) {
var p = prefix;
if (group > 0) p += "."
p += ".".repeat(i) + "#".repeat(sizes[group])
if (p.length <= springs.length && matched(p)) {
result += matches(p, group + 1)
}
}
cache[key] = result
return result
}
var sum: Long = 0; var sum2: Long = 0
var scanner = Scanner(System.`in`)
while (scanner.hasNext()) {
val line = scanner.nextLine()
springs = line.split(' ')[0]
sizes = ArrayList(line.split(' ')[1].split(',').map { it.toInt() }.toList())
cache.clear()
sum += matches()
springs = "$springs?$springs?$springs?$springs?$springs"
val sizes2 = ArrayList(sizes);
sizes.addAll(sizes2); sizes.addAll(sizes2); sizes.addAll(sizes2); sizes.addAll(sizes2)
cache.clear()
sum2 += matches()
}
println(listOf(sum, sum2))
| 0 | Kotlin | 1 | 0 | 7575ab03cdadcd581acabd0b603a6f999119bbb6 | 1,508 | aoc2023 | MIT License |
src/main/kotlin/search/BinarySearch.kt | TheAlgorithms | 177,334,737 | false | {"Kotlin": 41212} | package search
/**
* Binary search is an algorithm which finds the position of a target value within an array (Sorted)
*
* Worst-case performance O(log(n))
* Best-case performance O(1)
* Average performance O(log(n))
* Worst-case space complexity O(1)
*/
/**
* @param array is an array where the element should be found
* @param key is an element which should be found
* @return index of the element
*/
fun <T : Comparable<T>> binarySearch(array: Array<T>, key: T): Int {
return binarySearchHelper(array, key, 0, array.size - 1)
}
/**
* @param array The array to search
* @param key The element you are looking for
* @return the location of the key or -1 if the element is not found
**/
fun <T : Comparable<T>> binarySearchHelper(array: Array<T>, key: T, start: Int, end: Int): Int {
if (start > end) {
return -1
}
val mid = start + (end - start) / 2
return when {
array[mid].compareTo(key) == 0 -> mid
array[mid].compareTo(key) > 0 -> binarySearchHelper(array, key, start, mid - 1)
else -> binarySearchHelper(array, key, mid + 1, end)
}
}
| 62 | Kotlin | 369 | 1,221 | e57a8888dec4454d39414082bbe6a672a9d27ad1 | 1,116 | Kotlin | MIT License |
src/Day04.kt | zt64 | 572,594,597 | false | null | fun main() {
val input = readInput("Day04")
fun part1(input: String): Int {
var fullyContaining = 0
input.lines().forEach { pair ->
val (elf1, elf2) = pair.split(",")
val (min1, max1) = elf1.split("-").map(String::toInt)
val (min2, max2) = elf2.split("-").map(String::toInt)
if (
min1 <= min2 && max1 >= max2 ||
min2 <= min1 && max2 >= max1
) fullyContaining++
}
return fullyContaining
}
fun part2(input: String): Int {
var containing = 0
input.lines().forEach { pair ->
val (elf1, elf2) = pair.split(",")
val (min1, max1) = elf1.split("-").map(String::toInt)
val (min2, max2) = elf2.split("-").map(String::toInt)
val assignment1 = min1..max1
val assignment2 = min2..max2
if (
assignment1.first in assignment2 ||
assignment1.last in assignment2 ||
assignment2.first in assignment1 ||
assignment2.last in assignment1
) containing++
}
return containing
}
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 4e4e7ed23d665b33eb10be59670b38d6a5af485d | 1,242 | aoc-2022 | Apache License 2.0 |
src/Day25.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | fun main() {
fun toDec(s: String): Long {
var ans: Long = 0
var pot: Long = 1
for (i in s.length - 1 downTo 0) {
if (s[i] == '=') {
ans -= 2*pot
}
else if (s[i] == '-') {
ans -= pot
}
else {
ans += (s[i] - '0')*pot
}
pot *= 5
}
return ans
}
fun toSNAFU(num: Long): String {
var n = num
var digs = mutableListOf<Int>()
while (n > 0) {
digs.add((n % 5).toInt())
n /= 5
}
val aux = digs.size
for (i in 0 until aux) digs.add(0)
for (i in 0 until digs.size) {
while (digs[i] >= 5) {
digs[i] -= 5
digs[i+1] += 1
}
if (digs[i] == 3) {
digs[i] = -2
digs[i+1] += 1
}
else if (digs[i] == 4) {
digs[i] = -1
digs[i+1] += 1
}
}
var ans = ""
for (i in digs.size - 1 downTo 0) {
if (digs[i] == -2) ans += "="
else if (digs[i] == -1) ans += "-"
else if (ans.length > 0 || digs[i] > 0) ans += digs[i].toString()
}
return ans
}
fun part1(input: List<String>): String {
var sum: Long = 0
for (line in input) {
sum += toDec(line)
}
return toSNAFU(sum)
}
fun part2(input: List<String>): String {
return "x"
}
val input = readInput("Day25")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 1,663 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/year2015/day17/Day17.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2015.day17
import readInput
fun main() {
val input = readInput("2015", "Day17")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = getCombinations(input.toContainers(), 150).size
private fun part2(input: List<String>) = getCombinations(input.toContainers(), 150)
.groupBy { it.size }
.minBy { it.key }.value.size
private data class Container(val capacity: Int, val index: Int)
private fun List<String>.toContainers() = mapIndexed { index, num -> Container(num.toInt(), index) }.toSet()
private fun getCombinations(
remainingContainers: Set<Container>,
remainingEggnog: Int,
containers: Set<Container> = emptySet(),
cache: MutableMap<Pair<Set<Container>, Int>, Set<Set<Container>>> = hashMapOf(),
): Set<Set<Container>> {
if (remainingEggnog < 0) return emptySet()
if (remainingEggnog == 0) return setOf(containers)
val key = Pair(remainingContainers, remainingEggnog)
return cache.getOrPut(key) {
val result = mutableSetOf<Set<Container>>()
for (container in remainingContainers) {
result += getCombinations(
remainingContainers = remainingContainers - container,
remainingEggnog = remainingEggnog - container.capacity,
containers = containers + container,
cache = cache,
)
}
return@getOrPut result
}
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,434 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/days/Day4.kt | andilau | 726,429,411 | false | {"Kotlin": 37060} | package days
import kotlin.math.pow
@AdventOfCodePuzzle(
name = "Scratchcards",
url = "https://adventofcode.com/2023/day/4",
date = Date(day = 4, year = 2023)
)
class Day4(input: List<String>) : Puzzle {
private val scratchcards = input.map { Scratchcard.from(it) }
override fun partOne(): Int = scratchcards.sumOf { it.points }
override fun partTwo(): Int = scratchcards.map { it.matching }
.foldIndexed(List(scratchcards.size) { _ -> 1 }.toMutableList()) { ix, acc, won ->
(ix + 1..ix + won).forEach { acc[it] += acc[ix] }
acc
}
.sum()
data class Scratchcard(val id: Int, val picked: Set<Int>, val winning: Set<Int>) {
val matching: Int
get() = (picked intersect winning).count()
val points: Int
get() = 2.0.pow(matching.toDouble() - 1).toInt()
companion object {
fun from(line: String): Scratchcard {
val id: Int = line.substringBefore(":").substringAfter("Card ").trim().toInt()
val picked: Set<Int> = line.substringAfter(":").substringBefore("|")
.split(' ').filter { it.isNotBlank() }
.map(String::toInt).toSet()
val winning: Set<Int> = line.substringAfter("|")
.split(' ').filter { it.isNotBlank() }
.map(String::toInt).toSet()
return Scratchcard(id, picked, winning)
}
}
}
}
| 3 | Kotlin | 0 | 0 | 9a1f13a9815ab42d7fd1d9e6048085038d26da90 | 1,498 | advent-of-code-2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/aoc2020/ex17.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | fun main() {
val input = readInputFile("aoc2020/input17")
// val input = """
// .#.
// ..#
// ###
// """.trimIndent()
val cubes = input.lines().flatMapIndexed { r, rowString ->
rowString.mapIndexed { c, char ->
if (char == '#') {
Vector4(c,r,0, 0)
} else null
}
}.filterNotNull()
// val cubes = listOf(
// Vector3(0,-1,0),
// Vector3(1,0,0),
// Vector3(-1,1,0),
// Vector3(0,1,0),
// Vector3(1,1,0),
// )
require(cubes.toSet().size == cubes.size)
val cubes1 = cubes.transform(6) { iterate(this) }
//printPlane(cubes1)
println(cubes1.size)
//printPlane(iterate(cubes), -2)
}
private fun iterate(cubes: List<Vector4>): List<Vector4> {
val neighborsCount = countNeighbors(cubes)
// println(neighborsCount[Vector3(1, 2, -1)])
return activateByNeighbors(cubes, neighborsCount)
}
private fun activateByNeighbors(
cubes: List<Vector4>,
neighborsCount: Map<Vector4, Int>
): List<Vector4> {
return neighborsCount.filter { (cube: Vector4, activeNeighbors: Int) ->
if (cube in cubes) {
activeNeighbors == 2 || activeNeighbors == 3
} else {
activeNeighbors == 3
}
}.map { it.key }
}
private fun countNeighbors(cubes: List<Vector4>): MutableMap<Vector4, Int> {
val neighborsCount = mutableMapOf<Vector4, Int>()
cubes.forEach { cube ->
neighbors.map { it + cube }.forEach {
neighborsCount.set(it, neighborsCount.getOrDefault(it, 0) + 1)
}
}
return neighborsCount
}
private val neighbors = listOf(
Vector3(-1, -1, -1),
Vector3(-1, -1, 0),
Vector3(-1, -1, 1),
Vector3(-1, 0, -1),
Vector3(-1, 0, 0),
Vector3(-1, 0, 1),
Vector3(-1, 1, -1),
Vector3(-1, 1, 0),
Vector3(-1, 1, 1),
Vector3(0, -1, -1),
Vector3(0, -1, 0),
Vector3(0, -1, 1),
Vector3(0, 0, -1),
Vector3(0, 0,0),
Vector3(0, 0, 1),
Vector3(0, 1, -1),
Vector3(0, 1, 0),
Vector3(0, 1, 1),
Vector3(1, -1, -1),
Vector3(1, -1, 0),
Vector3(1, -1, 1),
Vector3(1, 0, -1),
Vector3(1, 0, 0),
Vector3(1, 0, 1),
Vector3(1, 1, -1),
Vector3(1, 1, 0),
Vector3(1, 1, 1),
).flatMap {
listOf(Vector4(it,-1), Vector4(it,0), Vector4(it,1))
}.toMutableSet().apply {
remove(Vector4(0,0,0,0))
require(size == 80) { "$size"}
}.toList()
private fun printPlane(cubes: List<Vector3>) {
val minx = cubes.minByOrNull { it.x }!!.x
val maxx = cubes.maxByOrNull { it.x }!!.x
val miny = cubes.minByOrNull { it.y }!!.y
val maxy = cubes.maxByOrNull { it.y }!!.y
val minz = cubes.minByOrNull { it.z }!!.z
val maxz = cubes.maxByOrNull { it.z }!!.z
(minz..maxz).forEach { z ->
println("z=$z")
cubes.filter { it.z == z }.let { planeCubes ->
(miny..maxy).forEach { row ->
planeCubes.filter { it.y == row }.let { rowCubes ->
(minx..maxx).map { col ->
if (rowCubes.find { it.x == col } != null) '#' else '.'
}.joinToString(" ").let {
println(it)
}
}
}
}
println("\n")
}
}
data class Vector3(val x: Int, val y: Int, val z: Int) {
operator fun plus(other: Vector3): Vector3 {
return Vector3(x + other.x, y + other.y, z + other.z)
}
}
data class Vector4(val x: Int, val y: Int, val z: Int, val w: Int) {
constructor(v: Vector3, w: Int): this(v.x, v.y, v.z, w)
operator fun plus(other: Vector4): Vector4 {
return Vector4(x + other.x, y + other.y, z + other.z, w + other.w)
}
} | 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 3,730 | AOC-2021 | MIT License |
src/Day07.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | sealed interface FSEntry {
val name: String
val parent: FSEntry?
}
data class FSFile(override val name: String, val size: Int, override val parent: FSEntry?) : FSEntry
class FSDir(override val name: String, override val parent: FSDir?) : FSEntry {
private val entries = mutableMapOf<String, FSEntry>()
fun add(entry: FSEntry) {
entries[entry.name] = entry
}
fun get(name: String): FSEntry? {
return entries[name]
}
val children: Collection<FSEntry>
get() = entries.values
}
fun main() {
fun countDirectorySizes(start: FSDir): Sequence<Int> {
/**
* Yields sizes of all directories inside [dir] including [dir] itself.
*
* @return the total size of the [dir] directory.
*/
suspend fun SequenceScope<Int>.traverseAndCountSize(dir: FSDir): Int {
var totalSize = 0
for (child in dir.children) {
totalSize += when (child) {
is FSDir -> traverseAndCountSize(child)
is FSFile -> child.size
}
}
yield(totalSize)
return totalSize
}
return sequence { traverseAndCountSize(start) }
}
fun parseCommands(input: List<String>): List<Pair<String, List<String>>> {
val commandsPositions = input.mapIndexedNotNull { idx, line ->
if (line.startsWith("$")) idx else null
}
return (commandsPositions + input.size)
.zipWithNext()
.map { (from, to) -> input.subList(from, to) }
.map { it.first().removePrefix("$ ") to it.drop(1) }
}
fun parseLsEntry(entry: String, currentDir: FSDir): FSEntry {
return if (entry.startsWith("dir")) {
val dirName = entry.removePrefix("dir ")
FSDir(dirName, parent = currentDir)
} else {
val (size, name) = entry.split(" ", limit = 2)
FSFile(name, size.toInt(), parent = currentDir)
}
}
fun buildFileTree(commandsWithResults: List<Pair<String, List<String>>>): FSDir {
val root = FSDir("/", parent = null)
var currentDir = root
for ((command, result) in commandsWithResults) {
when {
command.startsWith("cd") -> {
require(result.isEmpty())
val target = command.removePrefix("cd ")
currentDir = when (target) {
"/" -> root
".." -> currentDir.parent ?: error("No parent")
else -> (currentDir.get(target) ?: error("No such directory")) as? FSDir
?: error("Not a directory")
}
}
command.startsWith("ls") -> {
val entries = result.map { entry -> parseLsEntry(entry, currentDir) }
entries.forEach { currentDir.add(it) }
}
else -> error("Unexpected command '$command'")
}
}
return root
}
fun part1(input: List<String>): Int {
val commandsWithResults = parseCommands(input)
val root = buildFileTree(commandsWithResults)
return countDirectorySizes(root).filter { size -> size <= 100_000 }.sum()
}
fun part2(input: List<String>): Int {
val commandsWithResults = parseCommands(input)
val root = buildFileTree(commandsWithResults)
val totalDiskSpace = 70_000_000
val targetFreeSpace = 30_000_000
val occupiedSpace = countDirectorySizes(root).last()
val freeSpace = totalDiskSpace - occupiedSpace
require(freeSpace < targetFreeSpace)
val spaceToClean = targetFreeSpace - freeSpace
return countDirectorySizes(root)
.filter { it >= spaceToClean }
.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24_933_642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 4,197 | aoc2022 | Apache License 2.0 |
src/main/kotlin/g0801_0900/s0839_similar_string_groups/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0839_similar_string_groups
// #Hard #Array #String #Depth_First_Search #Breadth_First_Search #Union_Find
// #2023_03_28_Time_205_ms_(100.00%)_Space_35.9_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
fun numSimilarGroups(strs: Array<String>): Int {
val visited = BooleanArray(strs.size)
var res = 0
for (i in strs.indices) {
if (!visited[i]) {
res++
bfs(i, visited, strs)
}
}
return res
}
private fun bfs(i: Int, visited: BooleanArray, strs: Array<String>) {
val qu: Queue<String> = LinkedList()
qu.add(strs[i])
visited[i] = true
while (qu.isNotEmpty()) {
val s = qu.poll()
for (j in strs.indices) {
if (visited[j]) {
continue
}
if (isSimilar(s, strs[j])) {
visited[j] = true
qu.add(strs[j])
}
}
}
}
private fun isSimilar(s1: String, s2: String): Boolean {
var c1: Char? = null
var c2: Char? = null
var mismatchCount = 0
for (i in s1.indices) {
if (s1[i] == s2[i]) {
continue
}
mismatchCount++
if (c1 == null) {
c1 = s1[i]
c2 = s2[i]
} else if (s2[i] != c1 || s1[i] != c2) {
return false
} else if (mismatchCount > 2) {
return false
}
}
return true
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,644 | LeetCode-in-Kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.