path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/ginsberg/advent2018/Day10.kt | tginsberg | 155,878,142 | false | null | /*
* Copyright (c) 2018 by <NAME>
*/
/**
* Advent of Code 2018, Day 10 - The Stars Align
*
* Problem Description: http://adventofcode.com/2018/day/10
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day10/
*/
package com.ginsberg.advent2018
class Day10(rawInput: List<String>) {
private val message: Message = Message(rawInput.map { Light.of(it) })
fun solvePart1(): String =
message.resolveMessage().first
fun solvePart2(): Int =
message.resolveMessage().second
private class Message(val lights: List<Light>) {
fun resolveMessage(): Pair<String, Int> {
var lastArea = Long.MAX_VALUE
var thisArea = skyArea()
var timeToResolve = -1 // Account for extra step at the end
while (thisArea < lastArea) {
moveLights()
lastArea = thisArea
thisArea = skyArea()
timeToResolve++
}
moveLights(false) // We've moved one too far, back everything up one.
return Pair(this.toString(), timeToResolve)
}
private fun moveLights(forward: Boolean = true) =
lights.forEach { it.move(forward) }
private fun skyArea(): Long =
rangeX().span * rangeY().span
private fun rangeX(): IntRange =
IntRange(lights.minBy { it.x }!!.x, lights.maxBy { it.x }!!.x)
private fun rangeY(): IntRange =
IntRange(lights.minBy { it.y }!!.y, lights.maxBy { it.y }!!.y)
override fun toString(): String {
val lightSet = lights.map { Pair(it.x, it.y) }.toSet()
return rangeY().joinToString(separator = "\n") { y ->
rangeX().map { x ->
if (Pair(x, y) in lightSet) '#' else '.'
}.joinToString(separator = "")
}
}
}
private class Light(var x: Int, var y: Int, val dX: Int, val dY: Int) {
fun move(forward: Boolean = true) {
if (forward) {
x += dX
y += dY
} else {
x -= dX
y -= dY
}
}
companion object {
fun of(input: String): Light =
input.split(",", "<", ">").map { it.trim() }.run {
Light(this[1].toInt(), this[2].toInt(), this[4].toInt(), this[5].toInt())
}
}
}
}
| 0 | Kotlin | 1 | 18 | f33ff59cff3d5895ee8c4de8b9e2f470647af714 | 2,460 | advent-2018-kotlin | MIT License |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day9/Day9.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day9
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.parseLongs
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 9](https://adventofcode.com/2020/day/9)
*/
object Day9 : DayOf2020(9) {
override fun first(): Any? {
val nums = data.parseLongs("\n")
return nums.windowed(26)
.map { it.dropLast(1) to it.last() }
.map { (head, tail) -> head.flatMapIndexed { i, x -> head.drop(i + 1).map { it + x } }.toSet() to tail }
.first { (head, tail) -> tail !in head }
.second
}
override fun second(): Any? {
val nums = data.parseLongs("\n")
val bad = nums.windowed(26)
.map { it.dropLast(1) to it.last() }
.map { (head, tail) -> head.flatMapIndexed { i, x -> head.drop(i + 1).map { it + x } }.toSet() to tail }
.first { (head, tail) -> tail !in head }
.second
val partials = nums.scan(0L) { acc, value -> acc + value }
var from = 0
var to = 2
while (to in partials.indices) {
val curr = partials[to] - partials[from]
when {
curr < bad -> to++
curr > bad -> {
from++
to = maxOf(to, from + 2)
}
else -> break
}
}
val subset = nums.subList(from, to)
return subset.minOf { it } + subset.maxOf { it }
}
}
fun main() = SomeDay.mainify(Day9)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,367 | adventofcode | MIT License |
src/main/kotlin/dev/siller/aoc2022/Day09.kt | chearius | 575,352,798 | false | {"Kotlin": 41999} | package dev.siller.aoc2022
import kotlin.math.sign
private val examples = listOf(
"""
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent(),
"""
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent()
)
data class Vector(val x: Int, val y: Int)
typealias Position = Vector
private operator fun Vector.plus(other: Vector) = Vector(x + other.x, y + other.y)
private val ORIGIN = Position(0, 0)
private val UP = Vector(0, 1)
private val DOWN = Vector(0, -1)
private val LEFT = Vector(-1, 0)
private val RIGHT = Vector(1, 0)
private fun Position.isTouching(other: Position): Boolean =
other.x in x - 1..x + 1 && other.y in y - 1..y + 1
private fun Position.vectorTo(other: Position): Vector = Vector(other.x - x, other.y - y)
private fun part1(input: List<String>): Int {
val visited = mutableSetOf<Position>()
var headPosition = ORIGIN
var tailPosition = ORIGIN
visited += ORIGIN
input.forEach { line ->
val (direction, count) = getDirectionAndCount(line)
repeat(count) {
headPosition += direction
if (!tailPosition.isTouching(headPosition)) {
val (x, y) = tailPosition.vectorTo(headPosition)
tailPosition += Vector(x.sign, y.sign)
visited += tailPosition
}
}
}
return visited.size
}
private const val KNOTS_COUNT = 10
private fun part2(input: List<String>): Int {
val visited = mutableSetOf<Position>()
val knots = (0 until KNOTS_COUNT).map { ORIGIN }.toMutableList()
visited += ORIGIN
input.forEach { line ->
val (direction, count) = getDirectionAndCount(line)
repeat(count) {
knots[0] += direction
for (i in 1 until KNOTS_COUNT) {
if (!knots[i].isTouching(knots[i - 1])) {
val (x, y) = knots[i].vectorTo(knots[i - 1])
knots[i] += Vector(x.sign, y.sign)
if (i == KNOTS_COUNT - 1) {
visited += knots[i]
}
} else {
break
}
}
}
}
return visited.size
}
private fun getDirectionAndCount(line: String): Pair<Vector, Int> {
val direction = when (line.substringBefore(' ')) {
"U" -> UP
"D" -> DOWN
"L" -> LEFT
"R" -> RIGHT
else -> error("Invalid direction ${line.substringBefore(' ')}")
}
val count = line.substringAfter(' ').toInt()
return Pair(direction, count)
}
fun aocDay09() = aocTaskWithExamples(
day = 9,
part1 = ::part1,
part2 = ::part2,
exampleInput = examples,
expectedOutputPart1 = listOf(13, 88),
expectedOutputPart2 = listOf(1, 36)
)
fun main() {
aocDay09()
}
| 0 | Kotlin | 0 | 0 | e070c0254a658e36566cc9389831b60d9e811cc5 | 2,912 | advent-of-code-2022 | MIT License |
test/leetcode/KSimilarStrings.kt | andrej-dyck | 340,964,799 | false | null | package leetcode
import lib.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.*
import org.junit.jupiter.params.provider.*
/**
* https://leetcode.com/problems/k-similar-strings/
*
* 854. K-Similar Strings
* [Hard]
*
* Strings A and B are K-similar (for some non-negative integer K) if we can swap
* the positions of two letters in A exactly K times so that the resulting string equals B.
*
* Given two anagrams A and B, return the smallest K for which A and B are K-similar.
*
* Note:
* - 1 <= A.length == B.length <= 20
* - A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
*/
fun kSimilarity(a: String, b: String): Int {
require(a.isAnagramOf(b))
fun rec(a: String, b: String): Int = when {
a == b -> 0
a[0] == b[0] -> rec(a.drop(1), b.drop(1))
else -> b.indices
.filter { i -> a[0] == b[i] }
.map { 1 + rec(a.drop(1), b.swap(0, it).drop(1)) }
.minOr { 0 }
}
return rec(a, b)
}
fun String.isAnagramOf(other: String) =
length == other.length && sortedChars().contentEquals(other.sortedChars())
private fun String.sortedChars() = toCharArray().sortedArray()
private fun String.swap(i1: Int, i2: Int) =
if (i1 == i2) this
else this.replace(i1, this[i2]).replace(i2, this[i1])
private fun String.replace(i: Int, c: Char) = replaceRange(i..i, c.toString())
/**
* Unit tests
*/
class KSimilarStringsTest {
@ParameterizedTest
@CsvSource(
"'', '', 0",
"ab, ab, 0",
"ab, ba, 1",
"abc, bca, 2",
"abac, baca, 2",
"aabc, abca, 2"
)
fun `k-similarity of string a and b`(a: String, b: String, expectedKSimilarity: Int) {
assertThat(
kSimilarity(a, b)
).isEqualTo(
expectedKSimilarity
)
}
} | 0 | Kotlin | 0 | 0 | 3e3baf8454c34793d9771f05f330e2668fda7e9d | 1,874 | coding-challenges | MIT License |
domain/src/main/kotlin/com/seanshubin/kotlin/tryme/domain/ratio/Ratio.kt | SeanShubin | 228,113,855 | false | null | package com.seanshubin.kotlin.tryme.domain.ratio
data class Ratio(val numerator: Int, val denominator: Int) : Comparable<Ratio> {
operator fun plus(that: Ratio): Ratio {
val lcm = leastCommonMultiple(denominator, that.denominator)
return Ratio(numerator * lcm / denominator + that.numerator * lcm / that.denominator, lcm).simplify()
}
operator fun minus(that: Ratio): Ratio = (this + -that).simplify()
operator fun times(that: Ratio): Ratio = Ratio(numerator * that.numerator, denominator * that.denominator).simplify()
operator fun div(that: Ratio): Ratio = (this * that.recriprocal()).simplify()
operator fun unaryMinus(): Ratio = Ratio(-numerator, denominator).simplify()
fun recriprocal(): Ratio = Ratio(denominator, numerator).simplify()
fun withDenominator(newDenominator: Int): Ratio = Ratio(numerator * newDenominator / denominator, newDenominator)
override fun compareTo(that: Ratio): Int {
val lcm = leastCommonMultiple(denominator, that.denominator)
return (numerator * lcm / denominator).compareTo(that.numerator * lcm / that.denominator)
}
override fun toString(): String = "$numerator/$denominator"
fun simplify(): Ratio = simplifyFactor().simplifySign()
private fun simplifySign(): Ratio =
if (denominator < 0) Ratio(-numerator, -denominator)
else this
private fun simplifyFactor(): Ratio {
val gcf = greatestCommonFactor(numerator, denominator)
return Ratio(numerator / gcf, denominator / gcf)
}
companion object {
fun greatestCommonFactor(a: Int, b: Int): Int =
if (b == 0) a
else greatestCommonFactor(b, a % b)
fun leastCommonMultiple(a: Int, b: Int): Int =
if (a == 0 && b == 0) 0
else a * b / greatestCommonFactor(a, b)
val regex = Regex("""(-?\d+)/(-?\d+)""")
fun parse(s: String): Ratio {
val matchResult = regex.matchEntire(s)
if (matchResult == null) throw RuntimeException("Value '$s' could did not match expression $regex")
val numerator = matchResult.groupValues[1].toInt()
val denominator = matchResult.groupValues[2].toInt()
return Ratio(numerator, denominator).simplify()
}
}
val toDouble: Double get() = numerator.toDouble() / denominator.toDouble()
}
| 0 | Kotlin | 0 | 0 | abc67c5f43c01bdf55c6d4adcf05b77610c0473a | 2,247 | kotlin-tryme | The Unlicense |
src/Day10.kt | Redstonecrafter0 | 571,787,306 | false | {"Kotlin": 19087} |
fun main() {
fun part1(input: List<String>): Int {
var x = 1
var cycle = 0
var result = 0
var lastAdd = 0
for (cmd in input.map { it.split(" ") }) {
when (cmd[0]) {
"noop" -> cycle++
"addx" -> cycle += 2
}
if ((cycle + 20) / 40 != lastAdd) {
lastAdd = (cycle + 20) / 40
result += (if (cycle % 2 == 1) cycle - 1 else cycle) * x
}
if (cmd[0] == "addx") {
x += cmd[1].toInt()
}
}
return result
}
fun part2(input: List<String>) {
var x = 1
var cycle = 0
var instruction = -1
var leftCycles = 0
val instructions = input.map { it.split(" ") }
while (true) {
if (leftCycles == 0) {
if (instruction >= 0 && instructions[instruction][0] == "addx") {
x += instructions[instruction][1].toInt()
}
instruction++
when (instructions[instruction][0]) {
"noop" -> leftCycles = 1
"addx" -> leftCycles = 2
}
}
leftCycles--
cycle++
if (cycle % 40 in x..(x + 2)) {
print("#")
} else {
print(".")
}
if (cycle % 40 == 0) {
println()
}
if (instruction == instructions.lastIndex) {
break
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858 | 1,844 | Advent-of-Code-2022 | Apache License 2.0 |
advent9/src/main/kotlin/Main.kt | thastreet | 574,294,123 | false | {"Kotlin": 29380} | import java.io.File
import kotlin.math.abs
data class Command(
val direction: Char,
val steps: Int
)
data class Position(
val x: Int,
val y: Int
)
fun Position.distanceFrom(other: Position) =
Distance(x - other.x, y - other.y)
fun Position.incrementX() =
copy(x = x + 1)
fun Position.decrementX() =
copy(x = x - 1)
fun Position.incrementY() =
copy(y = y + 1)
fun Position.decrementY() =
copy(y = y - 1)
data class Distance(
val horizontal: Int,
val vertical: Int
)
fun main(args: Array<String>) {
val lines = File("input.txt").readLines()
val commands = parseCommands(lines)
val part1Answer = part1(commands)
println("part1Answer: $part1Answer")
val part2Answer = part2(commands)
println("part2Answer: $part2Answer")
}
fun parseCommands(lines: List<String>): List<Command> =
lines.map {
val parts = it.split(" ")
Command(parts[0][0], parts[1].toInt())
}
fun part1(commands: List<Command>): Int = simulate(commands, 1)
fun part2(commands: List<Command>): Int = simulate(commands, 9)
fun simulate(commands: List<Command>, tailsCount: Int): Int {
var head = Position(0, 0)
val tails = MutableList(tailsCount) {
Position(0, 0)
}
val tailVisited = mutableSetOf(tails.last())
commands.forEach { command ->
repeat(command.steps) {
when (command.direction) {
'R' -> head = head.incrementX()
'L' -> head = head.decrementX()
'U' -> head = head.decrementY()
'D' -> head = head.incrementY()
}
tails.forEachIndexed { index, position ->
if (index == 0) {
tails[0] = simulateNewPositions(head, position)
} else {
tails[index] = simulateNewPositions(tails[index - 1], tails[index])
}
}
tailVisited.add(tails.last())
}
}
return tailVisited.size
}
fun simulateNewPositions(position1: Position, position2: Position): Position {
val distance = position1.distanceFrom(position2)
var newPosition = position2
if (distance.horizontal > 1 || distance.horizontal < -1) {
newPosition = when {
distance.horizontal > 1 -> newPosition.incrementX()
else -> newPosition.decrementX()
}
when {
distance.vertical >= 1 -> newPosition = newPosition.incrementY()
distance.vertical <= -1 -> newPosition = newPosition.decrementY()
}
} else if (distance.vertical > 1 || distance.vertical < -1) {
newPosition = when {
distance.vertical > 1 -> newPosition.incrementY()
else -> newPosition.decrementY()
}
when {
distance.horizontal >= 1 -> newPosition = newPosition.incrementX()
distance.horizontal <= -1 -> newPosition = newPosition.decrementX()
}
}
val newDistance = position1.distanceFrom(newPosition)
if (abs(newDistance.horizontal) > 1 && abs(newDistance.vertical) > 1) {
throw IllegalStateException()
}
return newPosition
} | 0 | Kotlin | 0 | 0 | e296de7db91dba0b44453601fa2b1696af9dbb15 | 3,172 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day9.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
import java.util.Stack
class Day9 : Day(9) {
override fun partOne(): Any {
val map = inputList.map { it.map { Character.getNumericValue(it) } }
return map.flatMapIndexed { i, row ->
row.mapIndexed { j, height ->
var risk = height + 1
if (i > 0 && map[i-1][j] <= height) risk = 0
if (i < map.size-1 && map[i+1][j] <= height) risk = 0
if (j > 0 && map[i][j-1] <= height) risk = 0
if (j < map.first().size-1 && map[i][j+1] <= height) risk = 0
risk
}
}.sum()
}
override fun partTwo(): Any {
val map = inputList.map { it.map { Character.getNumericValue(it) } }
val color = Array(map.size) { Array(map.first().size) { 0 } }
var lastColor = 0
for (i in map.indices) {
for (j in map.first().indices) {
if (map[i][j] != 9 && color[i][j] == 0) {
lastColor += 1
color[i][j] = lastColor
spreadColor(i, j, color, map)
}
}
}
return color.flatten().groupBy { it }.filterKeys { it != 0 }.values.map { it.size }
.sortedDescending().take(3).reduce { acc, next -> acc * next }
}
private fun spreadColor(iStart: Int, jStart: Int, color: Array<Array<Int>>, map: List<List<Int>>) {
val stack = Stack<Pair<Int, Int>>()
stack.push(iStart to jStart)
while (stack.isNotEmpty()) {
val (i, j) = stack.pop()
if (i > 0 && map[i-1][j] != 9 && color[i-1][j] == 0) {
color[i-1][j] = color[i][j]
stack.push(i-1 to j)
}
if (i < map.size-1 && map[i+1][j] != 9 && color[i+1][j] == 0) {
color[i+1][j] = color[i][j]
stack.push(i+1 to j)
}
if (j > 0 && map[i][j-1] != 9 && color[i][j-1] == 0) {
color[i][j-1] = color[i][j]
stack.push(i to j-1)
}
if (j < map.first().size-1 && map[i][j+1] != 9 && color[i][j+1] == 0) {
color[i][j+1] = color[i][j]
stack.push(i to j+1)
}
}
}
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 2,266 | aoc-2021 | Creative Commons Zero v1.0 Universal |
kotlin/graphs/TreeCenters.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs
import java.util.stream.Stream
object TreeCenters {
// returns 1 or 2 tree centers
// http://en.wikipedia.org/wiki/Graph_center
fun findTreeCenters(tree: Array<List<Integer>>): List<Integer> {
val n = tree.size
var leaves: List<Integer> = ArrayList()
val degree = IntArray(n)
for (i in 0 until n) {
degree[i] = tree[i].size()
if (degree[i] <= 1) {
leaves.add(i)
}
}
var removedLeaves: Int = leaves.size()
while (removedLeaves < n) {
val nleaves: List<Integer> = ArrayList()
for (u in leaves) {
for (v in tree[u]) {
if (--degree[v] == 1) {
nleaves.add(v)
}
}
}
leaves = nleaves
removedLeaves += leaves.size()
}
return leaves
}
// returns vertex that has all its subtrees sizes <= n/2
fun findTreeCentroid(tree: Array<List<Integer>>, u: Int, p: Int): Int {
val n = tree.size
var cnt = 1
var goodCenter = true
for (v in tree[u]) {
if (v == p) continue
val res = findTreeCentroid(tree, v, u)
if (res >= 0) return res
val size = -res
goodCenter = goodCenter and (size <= n / 2)
cnt += size
}
goodCenter = goodCenter and (n - cnt <= n / 2)
return if (goodCenter) u else -cnt
}
fun diameter(tree: Array<List<Integer>>): Int {
val furthestVertex = dfs(tree, 0, -1, 0).toInt()
return (dfs(tree, furthestVertex, -1, 0) ushr 32).toInt()
}
fun dfs(tree: Array<List<Integer>>, u: Int, p: Int, depth: Int): Long {
var res = (depth.toLong() shl 32) + u
for (v in tree[u]) if (v != p) res = Math.max(res, dfs(tree, v, u, depth + 1))
return res
}
// Usage example
fun main(args: Array<String?>?) {
val n = 4
val tree: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() }
tree[3].add(0)
tree[0].add(3)
tree[3].add(1)
tree[1].add(3)
tree[3].add(2)
tree[2].add(3)
System.out.println(3 == findTreeCentroid(tree, 0, -1))
System.out.println(3 == findTreeCenters(tree)[0])
System.out.println(2 == diameter(tree))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,449 | codelibrary | The Unlicense |
code/string/SuffixArray.kt | hakiobo | 397,069,173 | false | null | private fun constructSuffixArray(t: String): IntArray {
val n = t.length
val c = IntArray(max(n, 256))
val rank = IntArray(n) { t[it].toInt() }
val tempRank = IntArray(n)
val suffix = IntArray(n) { it }
val tempSuffix = IntArray(n)
fun countingSort(k: Int) {
var sum = 0
c.fill(0)
for (i in 0 until n) {
c[(if (i + k < n) rank[i + k] else 0)]++
}
for (i in c.indices) {
val temp = c[i]
c[i] = sum
sum += temp
}
for (i in 0 until n) {
tempSuffix[c[if (suffix[i] + k < n) rank[suffix[i] + k] else 0]++] = suffix[i]
}
for (i in 0 until n) {
suffix[i] = tempSuffix[i]
}
}
var k = 1
while (k < n) {
countingSort(k)
countingSort(0)
tempRank[suffix[0]] = 0
var r = 0
for (i in 1 until n) {
tempRank[suffix[i]] =
if (rank[suffix[i]] == rank[suffix[i - 1]] && rank[suffix[i] + k] == rank[suffix[i - 1] + k]) r else ++r
}
for (i in 0 until n) {
rank[i] = tempRank[i]
}
if (rank[suffix[n - 1]] == n - 1) break
k = k shl 1
}
return suffix
}
private fun computeLCP(sa: IntArray, t: String): IntArray {
val n = t.length
val phi = IntArray(n)
val plcp = IntArray(n)
phi[sa[0]] = -1
for (i in 1 until n) {
phi[sa[i]] = sa[i - 1]
}
var l = 0
for (i in 0 until n) {
if (phi[i] == -1) continue
while (t[i + l] == t[phi[i] + l]) l++
plcp[i] = l
l = max(l - 1, 0)
}
return IntArray(n) { plcp[sa[it]] }
}
| 0 | Kotlin | 1 | 2 | f862cc5e7fb6a81715d6ea8ccf7fb08833a58173 | 1,686 | Kotlinaughts | MIT License |
src/main/kotlin/solutions/day25/Day25.kt | Dr-Horv | 112,381,975 | false | null |
package solutions.day25
import solutions.Solver
import utils.splitAtWhitespace
import java.lang.RuntimeException
import java.util.regex.Pattern
enum class Direction {
LEFT,
RIGHT
}
fun Int.move(direction: Direction) = when(direction) {
Direction.LEFT -> this - 1
Direction.RIGHT -> this + 1
}
fun String.toDirection(): Direction = when(this) {
"left" -> Direction.LEFT
"right" -> Direction.RIGHT
else -> throw RuntimeException("Unparsable direction $this")
}
data class State(val onZero: Triple<Int, Direction, String>, val onOne: Triple<Int, Direction, String>)
class Day25: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val inputAsOneString = input.joinToString("\n")
val regex = "in state (\\w):\\s+if the current value is (\\d):\\s+- write the value (\\d)\\.\\s+- Move one slot to the (\\w+)\\.\\s+- Continue with state (\\w)\\.\\s+if the current value is (\\d):\\s+- write the value (\\d)\\.\\s+- Move one slot to the (\\w+)\\.\\s+- Continue with state (\\w)\\."
val pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(inputAsOneString)
val states = mutableMapOf<String, State>()
while (matcher.find()) {
val name = matcher.group(1)
states.put(name, State(
Triple(matcher.group(3).toInt(), matcher.group(4).toDirection(), matcher.group(5)),
Triple(matcher.group(7).toInt(), matcher.group(8).toDirection(), matcher.group(9))
))
}
val firstLine = input[0]
val secondLine = input[1]
var next = firstLine[firstLine.lastIndex-1].toString()
var position = 0
var iterationsLeft = secondLine.splitAtWhitespace()[5].toInt()
val values = mutableMapOf<Int, Int>().withDefault { 0 }
while (iterationsLeft > 0) {
val s = states.getValue(next)
val value = values.getValue(position)
val (write, direction, nextState) = if(value == 0) {
s.onZero
} else {
s.onOne
}
values[position] = write
position = position.move(direction)
next = nextState
iterationsLeft--
}
return values.values.sum().toString()
}
}
| 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 2,362 | Advent-of-Code-2017 | MIT License |
src/main/kotlin/days/aoc2021/Day15.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2021
import days.Day
import java.util.*
import kotlin.Comparator
class Day15 : Day(2021, 15) {
override fun partOne(): Any {
val cave = createCave(inputList)
return calculateLowestRiskPath(cave)
}
override fun partTwo(): Any {
val cave = createFullCave(createCave(inputList))
return calculateLowestRiskPath(cave)
}
fun createCave(inputList: List<String>) : Array<Array<Int>> {
val cave = Array(inputList.first().length) {
Array(inputList.size) { 0 }
}
inputList.forEachIndexed { y, line ->
line.trim().forEachIndexed { x, c ->
cave[x][y] = c - '0'
}
}
return cave
}
fun createFullCave(subset: Array<Array<Int>>): Array<Array<Int>> {
val xSize = subset.first().size
val ySize = subset.size
val cave = Array(xSize * 5) {
Array(ySize * 5) { 0 }
}
for (y in 0 until 5) {
for (x in 0 until 5) {
val increment = x + y
subset.forEachIndexed { originalY, row ->
row.forEachIndexed { originalX, originalValue ->
var newValue = originalValue + increment
if (newValue > 9) {
newValue -= 9
}
cave[x * xSize + originalX][y * ySize + originalY] = newValue
}
}
}
}
return cave
}
fun calculateLowestRiskPath(cave: Array<Array<Int>>): Int {
val goal = Pair(cave.first().lastIndex, cave.lastIndex)
val comparator: Comparator<CaveNode> = compareBy { it.priority }
val frontier = PriorityQueue(comparator)
frontier.add(CaveNode(Pair(0,0), 0))
val risks = mutableMapOf<Pair<Int,Int>, Int>()
risks[Pair(0,0)] = 0
while (frontier.isNotEmpty()) {
val current = frontier.remove()
//println("Looking at ${current.location} (risk at that location is ${cave[current.location.first][current.location.second]})")
if (current.location == goal) {
return risks[current.location]!!
}
getNeighbors(current.location.first, current.location.second, cave).forEach { neighbor ->
val risk = risks[current.location]!! + cave[neighbor.first][neighbor.second]
//print("... risk moving to $neighbor is $risk")
if (!risks.containsKey(neighbor) || risk < risks[neighbor]!!) {
//print(" and it's the low")
risks[neighbor] = risk
frontier.add(CaveNode(neighbor, risk))
}
//println()
}
}
return 0
}
class CaveNode(val location: Pair<Int,Int>, var priority: Int)
fun getNeighbors(x: Int, y: Int, cave: Array<Array<Int>>) = sequence {
if (x != 0)
yield(Pair(x - 1, y))
if (x != cave.first().lastIndex)
yield(Pair(x + 1, y))
if (y != 0)
yield(Pair(x, y - 1))
if (y != cave.lastIndex)
yield(Pair(x, y + 1))
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,251 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
2015/src/main/kotlin/com/koenv/adventofcode/Day7.kt | koesie10 | 47,333,954 | false | null | package com.koenv.adventofcode
class Day7 {
val numberOfWires: Int
get() = wires.size
private val wires = hashMapOf<String, Int>()
private val unsatisfiedDependencies = arrayListOf<Dependency>()
public fun parseCommand(input: String) {
val inputParts = input.trim().split(" -> ", ignoreCase = true)
val command = inputParts[0]
val into = inputParts[1]
if (command.isDigits()) {
wires.put(into, command.toInt())
unsatisfiedDependencies.removeAll { it.into == into }
satisfyDependencies(into)
} else if (command.isLetters()) {
val satisfiable = wires.containsKey(command)
if (!satisfiable) {
unsatisfiedDependencies.add(Dependency(arrayListOf(command), input, into))
} else {
wires.put(into, this[command])
unsatisfiedDependencies.removeAll { it.into == into }
satisfyDependencies(into)
}
} else {
val commandParts = command.split(" ", ignoreCase = true)
if (commandParts.size == 2 && commandParts[0] == "NOT") { // NOT
val first = commandParts[1]
val satisfiable = (first.isDigits() || wires.containsKey(first))
if (!satisfiable) {
unsatisfiedDependencies.add(Dependency(arrayListOf(first), input, into))
} else {
wires.put(into, getValue(first).toInt().inv().toUnsignedShort())
unsatisfiedDependencies.removeAll { it.into == into }
satisfyDependencies(into)
}
} else if (commandParts.size == 3) {
val first = commandParts[0]
val operator = commandParts[1]
val second = commandParts[2]
val satisfiable = (first.isDigits() || wires.containsKey(first)) && (second.isDigits() || wires.containsKey(second))
if (!satisfiable) {
val dependsOn = arrayListOf<String>()
if (!first.isDigits()) {
dependsOn.add(first)
}
if (!second.isDigits()) {
dependsOn.add(second)
}
unsatisfiedDependencies.add(Dependency(dependsOn, input, into))
} else {
val firstValue = if (first.isDigits()) first.toInt() else this[first]
val secondValue = if (second.isDigits()) second.toInt() else this[second]
val resultValue = executeOperation(operator, firstValue, secondValue)
wires.put(into, resultValue.toUnsignedShort())
unsatisfiedDependencies.removeAll { it.into == into }
satisfyDependencies(into)
}
} else {
throw IllegalArgumentException("Invalid command: $input")
}
}
}
public fun parseCommands(input: String) {
return input.lines().forEach {
if (!it.isNullOrBlank()) {
parseCommand(it)
}
}
}
public operator fun get(wireName: String): Int {
return wires[wireName]!!
}
private fun satisfyDependencies(wireName: String) {
unsatisfiedDependencies
.filter { it.dependsOn.contains(wireName) }
.forEach{
val dependsOn = it.dependsOn.filter { !wires.containsKey(it) }
if (dependsOn.isEmpty()) {
parseCommand(it.input)
}
}
}
private fun getValue(wireNameOrValue: String): Int {
if (wireNameOrValue.isDigits()) {
return wireNameOrValue.toInt()
}
return wires[wireNameOrValue]!!
}
private fun executeOperation(operator: String, first: Int, second: Int): Int {
when (operator) {
"AND" -> return first and second
"OR" -> return first or second
"LSHIFT" -> return first shl second
"RSHIFT" -> return first shr second
}
throw IllegalArgumentException("Invalid operator: $operator")
}
fun String.isDigits(): Boolean {
return all { it.isDigit() }
}
fun String.isLetters(): Boolean {
return all { it.isLetter() }
}
fun Int.toUnsignedShort(): Int {
if (this < 0) {
return 65536 + this
}
return this
}
data class Dependency(val dependsOn: MutableList<String>, val input: String, val into: String)
} | 0 | Kotlin | 0 | 0 | 29f3d426cfceaa131371df09785fa6598405a55f | 4,670 | AdventOfCode-Solutions-Kotlin | MIT License |
src/Day09.kt | mikrise2 | 573,939,318 | false | {"Kotlin": 62406} | import kotlin.math.abs
fun main() {
fun headsCount(input: List<String>, size: Int): Int {
val x = MutableList(size) { 0 }
val y = MutableList(size) { 0 }
val tails = mutableSetOf(Pair(0, 0))
input.forEach { line ->
val command = line.split(" ")
repeat(command[1].toInt()) {
when (command[0]) {
"R" -> x[0]++
"L" -> x[0]--
"U" -> y[0]++
"D" -> y[0]--
}
for (i in 1 until size) {
val differentX = x[i - 1] - x[i]
val differentY = y[i - 1] - y[i]
if (abs(differentX) >= 2 || abs(differentY) >= 2) {
x[i] = x[i] + differentX.coerceIn(-1..1)
y[i] = y[i] + differentY.coerceIn(-1..1)
}
}
tails.add(Pair(x[size - 1], y[size - 1]))
}
}
return tails.size
}
fun part1(input: List<String>): Int {
return headsCount(input, 2)
}
fun part2(input: List<String>): Int {
return headsCount(input, 10)
}
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8 | 1,290 | Advent-of-code | Apache License 2.0 |
src/Day03.kt | SebastianHelzer | 573,026,636 | false | {"Kotlin": 27111} |
fun main() {
fun Char.getCharPriority(): Int = when (this) {
in 'A'..'Z' -> this - 'A' + 27
in 'a'..'z' -> this - 'a' + 1
else -> error("Input $this must be a letter")
}
fun part1(input: List<String>): Int = input
.map { line -> line.chunked(line.length/2).map { it.toSet() } }
.map { (first, second) -> (first intersect second).single() }
.sumOf { it.getCharPriority() }
fun part2(input: List<String>): Int = input
.map { it.toSet() }
.chunked(3) { (first, second, third) -> (first intersect second intersect third).single() }
.sumOf { it.getCharPriority() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
checkEquals(157, part1(testInput))
checkEquals(70, part2(testInput))
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e48757626eb2fb5286fa1c59960acd4582432700 | 937 | advent-of-code-2022 | Apache License 2.0 |
src/DayThree.kt | P-ter | 573,301,805 | false | {"Kotlin": 9464} | data class House(val rowIndex: Int, val colIndex: Int)
fun main() {
fun part1(input: List<String>): Int {
val direction = input.first()
val santaMap = mutableMapOf(House(0, 0) to 1)
var count = 1
var currentHouse = santaMap.keys.first()
direction.forEach {
val (rowIndex, colIndex) = currentHouse
currentHouse = when(it) {
'^' -> currentHouse.copy(rowIndex = rowIndex - 1)
'v' -> currentHouse.copy(rowIndex = rowIndex + 1)
'>' -> currentHouse.copy(colIndex = colIndex + 1)
'<' -> currentHouse.copy(colIndex = colIndex -1)
else -> currentHouse
}
val numOfPresent = santaMap.getOrDefault(currentHouse, 0)
if(numOfPresent == 0) {
count++
}
santaMap[currentHouse] = numOfPresent + 1
}
return count
}
fun part2(input: List<String>): Int {
val instruction = input.first()
val presentMap = mutableMapOf(House(0, 0) to 2)
var santaCurrentHouse = House(0, 0)
var robotCurrentHouse = House(0,0)
var count = 1
instruction.forEachIndexed { index, direction ->
var currentHouse = if(index%2 == 0) santaCurrentHouse else robotCurrentHouse
val (rowIndex, colIndex) = currentHouse
currentHouse = when(direction) {
'^' -> currentHouse.copy(rowIndex = rowIndex - 1)
'v' -> currentHouse.copy(rowIndex = rowIndex + 1)
'>' -> currentHouse.copy(colIndex = colIndex + 1)
'<' -> currentHouse.copy(colIndex = colIndex -1)
else -> currentHouse
}
val numOfPresent = presentMap.getOrDefault(currentHouse, 0)
if(numOfPresent == 0) {
count++
}
presentMap[currentHouse] = numOfPresent + 1
if(index % 2 == 0) {
santaCurrentHouse = currentHouse
} else {
robotCurrentHouse = currentHouse
}
}
return count
}
val input = readInput("daythree")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fc46b19451145e0c41b1a50f62c77693865f9894 | 2,245 | aoc-2015 | Apache License 2.0 |
strings/BuddyStrings/kotlin/Solution.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | import kotlin.math.sign
/**
* 859. Buddy Strings.
* <br/>
* Given two strings A and B of lowercase letters,
* return true if you can swap two letters in A so the result is equal to B,
* otherwise, return false.
* Swapping letters is defined as taking two indices
* i and j (0-indexed) such that i != j and swapping the characters
* at A[i] and A[j]. For example, swapping at indices
* 0 and 2 in "abcd" results in "cbad".
* <br/>
* https://leetcode.com/problems/buddy-strings/
*/
fun buddyStrings(A: String, B: String): Boolean {
if(A.length != B.length || A.length < 2) return false
var l1 = -1
var l2 = -1
for(i in A.indices) {
if(A[i] != B[i]) {
if(l1 == -1) {
l1 = i
continue
}
if(l2 == -1) {
l2 = i
if(A[l1] != B[l2] || A[l2] != B[l1]) return false //swap doesn't help
continue
}
return false //more than 2 chars are diff
}
}
if (l1 == -1) { //same, but maybe we could swap two similar letters
return A.groupBy { it.toInt() }.any { (_, v) -> v.size > 1 }
}
if(l2 == -1) return false
return A[l1] == B[l2] && A[l2] == B[l1]
}
fun main() {
print("Buddy Strings:")
var a = true
a = a && buddyStrings("ab", "ba")
a = a && !buddyStrings("ab", "ab")
a = a && buddyStrings("aa", "aa")
a = a && buddyStrings("aaaaaaabc", "aaaaaaacb")
a = a && !buddyStrings("", "aa")
println(if(a) "SUCCESS" else "FAIL")
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 1,555 | codility | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SplitArrayLargestSum.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 410. Split Array Largest Sum
* @see <a href="https://leetcode.com/problems/split-array-largest-sum/">Source</a>
*/
fun interface SplitArrayLargestSum {
operator fun invoke(nums: IntArray, k: Int): Int
}
class SplitArrayLargestSumMaxSum : SplitArrayLargestSum {
override fun invoke(nums: IntArray, k: Int): Int {
// validation
if (nums.isEmpty() || k < 1) {
return -1
}
// get [minMaxSum, maxMaxSum]
var start: Long = 0
var end: Long = 0
for (n in nums) {
start = min(start, n.toLong())
end += n.toLong()
}
// binary search
while (start < end) {
val middle = start + (end - start) / 2
if (validateMaxSum(nums, middle, k - 1)) {
// valid maxSum & cut, so we need to shrink the finding (reduce max sum)
end = middle
} else {
// invalid maxSum & cut, so we need to expand the finding (increase max sum)
start = middle + 1
}
}
return start.toInt()
}
/**
* Given a max sum, we are validating the cuts. Whenever we collect/aggregate enough sum (<= maxSum), we start a new
* group
*/
private fun validateMaxSum(nums: IntArray, maxSum: Long, cuts: Int): Boolean {
var cuts0 = cuts
var agg = 0
for (n in nums) {
// validate value (not needed)
if (n > maxSum || cuts0 < 0) {
return false
}
agg += n
if (agg > maxSum) {
// find a group
agg = n
cuts0--
if (cuts0 < 0) return false
}
}
// cuts may still > 1, which means we can even have less num of cuts for grouping
return true
}
}
class SplitArrayLargestSumGreedy : SplitArrayLargestSum {
override fun invoke(nums: IntArray, k: Int): Int {
var low = 0
var high = 0
var min = Int.MAX_VALUE
for (i in nums.indices) {
low = max(low, nums[i])
high += nums[i]
}
while (low <= high) {
val mid = (low + high) / 2
if (requiredNoOfChunks(nums, mid, k)) {
min = min(min, mid)
high = mid - 1
} else {
low = mid + 1
}
}
return min
}
private fun requiredNoOfChunks(nums: IntArray, mid: Int, m: Int): Boolean {
var chunks = 0
var i = 0
while (i < nums.size) {
var value = 0
while (i < nums.size && nums[i] + value <= mid) {
value += nums[i++]
}
chunks++
}
return chunks <= m
}
}
class SplitArrayLargestSumBinarySearch : SplitArrayLargestSum {
override fun invoke(nums: IntArray, k: Int): Int {
// sanity check
if (nums.isEmpty()) return 0
var lo = 0L
var hi = 0L
for (num in nums) {
lo = maxOf(lo, num.toLong())
hi += num
}
while (lo < hi) {
val mid: Long = lo + (hi - lo) / 2
if (minGroups(mid, nums) > k) {
lo = mid + 1
} else {
hi = mid
}
}
return lo.toInt()
}
private fun minGroups(limit: Long, nums: IntArray): Int {
var sum = 0
var groups = 1
for (num in nums) {
if (sum + num > limit) {
sum = num
++groups
} else {
sum += num
}
}
return groups
}
}
class SplitArrayLargestSumDP : SplitArrayLargestSum {
override fun invoke(nums: IntArray, k: Int): Int {
// sanity check
if (nums.isEmpty()) return 0
val size = nums.size
// 1-indexed, instead of 0-indexed
val prefixSums = IntArray(size + 1)
for (i in 0 until size) {
prefixSums[i + 1] = prefixSums[i] + nums[i]
}
val dp = Array(size + 1) { IntArray(k + 1) { Int.MAX_VALUE } }
dp[0][0] = 0
// 1-indexed, instead of 0-indexed
for (i in 1..size) {
// the actual split(s), starting with 1
for (j in 1..k) {
// [0, k], [k, i]: where to split the array
for (m in 0 until i) {
val subarraySum = prefixSums[i] - prefixSums[m]
dp[i][j] = minOf(dp[i][j], maxOf(dp[m][j - 1], subarraySum))
}
}
}
return dp[size][k]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,357 | kotlab | Apache License 2.0 |
year2021/day18/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day18/part2/Year2021Day18Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
You notice a second question on the back of the homework assignment:
What is the largest magnitude you can get from adding only two of the snailfish numbers?
Note that snailfish addition is not commutative - that is, `x + y` and `y + x `can produce different
results.
Again considering the last example homework assignment above:
```
[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]
[[[5,[2,8]],4],[5,[[9,9],0]]]
[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]
[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]
[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]
[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]
[[[[5,4],[7,7]],8],[[8,3],8]]
[[9,3],[[9,9],[6,[4,9]]]]
[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]
[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]
```
The largest magnitude of the sum of any two snailfish numbers in this list is 3993. This is the
magnitude of `[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]` +
`[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]`, which reduces to
`[[[[7,8],[6,6]],[[6,0],[7,7]]],[[[7,8],[8,8]],[[7,9],[0,6]]]]`.
What is the largest magnitude of any sum of two different snailfish numbers from the homework
assignment?
*/
package com.curtislb.adventofcode.year2021.day18.part2
import com.curtislb.adventofcode.common.iteration.uniquePairs
import com.curtislb.adventofcode.year2021.day18.snailfish.SnailfishNumber
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2021, day 18, part 2.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
var maxMagnitude = 0
val numbers = inputPath.toFile().readLines().map { SnailfishNumber.fromString(it) }
for ((numberA, numberB) in numbers.uniquePairs()) {
val magnitudeAB = (numberA + numberB).magnitude()
val magnitudeBA = (numberB + numberA).magnitude()
maxMagnitude = maxOf(maxMagnitude, magnitudeAB, magnitudeBA)
}
return maxMagnitude
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,003 | AdventOfCode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxProductTree.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 dev.shtanko.algorithms.MOD
import kotlin.math.abs
/**
* 1339. Maximum Product of Splitted Binary Tree
* @see <a href="https://leetcode.com/problems/maximum-product-of-splitted-binary-tree">Source</a>
*/
fun interface MaxProductTree {
operator fun invoke(root: TreeNode?): Int
}
class MaxProductTreeInorder : MaxProductTree {
private var res = 0
override operator fun invoke(root: TreeNode?): Int {
val sum = allSum(root)
inorder(root, sum)
val num1 = res
val num2 = sum - res
var ans = 0
// Calculate the product
for (i in 0 until num1) {
ans += num2
if (ans > MOD) {
ans -= MOD
}
}
return ans
}
private fun inorder(root: TreeNode?, sum: Int): Int {
var cur = 0
if (root == null) {
return 0
}
cur += inorder(root.left, sum)
cur += root.value
cur += inorder(root.right, sum)
val minClose = abs(res - sum / 2)
val curClose = abs(cur - sum / 2)
res = if (curClose < minClose) cur else res
return cur
}
private fun allSum(root: TreeNode?): Int {
return if (root == null) {
0
} else {
root.value + allSum(root.left) + allSum(root.right)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,991 | kotlab | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-11.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2021
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.filterIn
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2021, "11-input")
val test1 = readInputLines(2021, "11-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val cave = OctopusCave(input)
var flashes = 0
repeat(100) {
flashes += cave.step()
}
return flashes
}
private fun part2(input: List<String>): Int {
val cave = OctopusCave(input)
var step = 1
while (true) {
val flashes = cave.step()
if (flashes == 100) return step
step++
}
}
private class OctopusCave(input: List<String>) {
private val area = input.mapIndexed { row, line ->
line.mapIndexed { col, c ->
Octopus(Coord2D(col, row), c.digitToInt())
}
}
fun print() {
area.forEach { row ->
row.forEach {
print(it.energy)
}
println()
}
println()
}
fun step(): Int {
area.forEach { row ->
row.forEach { it.energy++ }
}
val newFlashes = mutableSetOf<Octopus>()
do {
newFlashes.clear()
newFlashes += area.flatMap { line -> line.filter { !it.didFlash && 9 < it.energy } }.toSet()
newFlashes.forEach { it.didFlash = true }
newFlashes.forEach { new ->
new.neighbors()
.filter { !it.didFlash }
.forEach { it.energy++ }
}
} while (newFlashes.isNotEmpty())
var flashes = 0
area.forEach { row ->
row.forEach {
if (it.didFlash) {
it.didFlash = false
it.energy = 0
flashes++
}
}
}
return flashes
}
private fun Octopus.neighbors(): List<Octopus> {
val diffs = coord.adjacent(true).filterIn(area.first().indices, area.indices)
return diffs.map { area[it.y][it.x] }
}
}
private class Octopus(val coord: Coord2D, var energy: Int) {
var didFlash = false
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,471 | advent-of-code | MIT License |
difference/src/commonMain/kotlin/dev/andrewbailey/diff/impl/MyersDiffAlgorithm.kt | andrewbailey | 264,575,064 | false | null | package dev.andrewbailey.diff.impl
import dev.andrewbailey.diff.impl.MyersDiffOperation.*
import kotlin.math.ceil
/**
* This class implements a variation of Eugene Myers' Diffing Algorithm that uses linear space. This
* algorithm has a worst-case runtime of O(M + N + D^2), where N and M are the lengths of [original]
* and [updated], and D is the length of the edit script (i.e. the number of `Insert`s and `Delete`s
* that appear in the result of [generateDiff]). This algorithm has an expected runtime of
* O((M + N) D) and always uses O(D) space.
*
* The basic variation of this algorithm (which uses quadratic space) is a greedy algorithm. In this
* introductory variation, the algorithm places the inputs on a grid. At (0, 0), no inputs from
* either [original] or [updated] have been accepted. Moving to the right (in the positive X
* direction) indicates that the next item in [original] should be removed. Moving downward (in the
* positive Y direction) indicates that the next item in [updated] should be inserted. Moving
* diagonally (in both the positive X and Y direction) indicates that [original] and [updated] share
* a value, so there is no difference.
*
* The greedy algorithm makes multiple passes to find the shortest path from (0, 0) to (N, M). When
* the algorithm runs through the inputs, it can move diagonally for free. Long chains of diagonals
* where both inputs have a matching subsequence are called a [Snake]. In each iteration, the
* possible paths expand either by one unit in a single direction or, if there is a snake,
* diagonally until the end of the snake.
*
* The linear-space implementation of this algorithm is a divide and conquer algorithm that follows
* the same basic principles as the greedy algorithm. The input is traversed forwards and backwards
* simultaneously in a subset of the grid. When the paths in both directions intersect, a shortest
* path has been found and a diff can be outputted.
*
* You can read the technical paper by <NAME> here: http://xmailserver.org/diff2.pdf
*/
internal class MyersDiffAlgorithm<T>(
private val original: List<T>,
private val updated: List<T>
) {
fun generateDiff(): Sequence<MyersDiffOperation<T>> {
return walkSnakes()
.asSequence()
.map { (x1, y1, x2, y2) ->
when {
x1 == x2 -> Insert(value = updated[y1])
y1 == y2 -> Delete
else -> Skip
}
}
}
private fun walkSnakes(): List<Region> {
val path = findPath()
val regions = mutableListOf<Region>()
path.forEach { (p1, p2) ->
var (x1, y1) = walkDiagonal(p1, p2, regions)
val (x2, y2) = p2
val dY = y2 - y1
val dX = x2 - x1
when {
dY > dX -> {
regions += Region(x1, y1, x1, y1 + 1)
y1++
}
dY < dX -> {
regions += Region(x1, y1, x1 + 1, y1)
x1++
}
}
walkDiagonal(Point(x1, y1), p2, regions)
}
return regions
}
private fun walkDiagonal(
start: Point,
end: Point,
regionsOutput: MutableList<Region>
): Point {
var (x1, y1) = start
val (x2, y2) = end
while (x1 < x2 && y1 < y2 && original[x1] == updated[y1]) {
regionsOutput += Region(x1, y1, x1 + 1, y1 + 1)
x1++
y1++
}
return Point(x1, y1)
}
private fun findPath(): List<Snake> {
val snakes = mutableListOf<Snake>()
val stack = mutableListOf<Region>()
stack.push(
Region(
left = 0,
top = 0,
right = original.size,
bottom = updated.size
)
)
while (stack.isNotEmpty()) {
val region = stack.pop()
val snake = midpoint(region)
if (snake != null) {
snakes += snake
val (start, finish) = snake
stack.push(region.copy(
right = start.x,
bottom = start.y
))
stack.push(region.copy(
left = finish.x,
top = finish.y
))
}
}
snakes.sortWith(object : Comparator<Snake> {
override fun compare(a: Snake, b: Snake): Int {
return if (a.start.x == b.start.x) {
a.start.y - b.start.y
} else {
a.start.x - b.start.x
}
}
})
return snakes
}
private fun midpoint(
region: Region
): Snake? {
if (region.size == 0) {
return null
}
val max = ceil(region.size / 2.0f).toInt()
val vForwards = CircularIntArray(2 * max + 1)
vForwards[1] = region.left
val vBackwards = CircularIntArray(2 * max + 1)
vBackwards[1] = region.bottom
for (depth in 0..max) {
forwards(region, vForwards, vBackwards, depth)?.let { return it }
backwards(region, vForwards, vBackwards, depth)?.let { return it }
}
return null
}
private fun forwards(
region: Region,
vForwards: CircularIntArray,
vBackwards: CircularIntArray,
depth: Int
): Snake? {
// This loop is effectively `for (k in (-depth..depth step 2).reversed())`, but avoids
// allocating a Range object.
var k = depth
while (k >= -depth) {
val c = k - region.delta
var endX: Int
val startX: Int
if (k == -depth || (k != -depth && vForwards[k - 1] < vForwards[k + 1])) {
startX = vForwards[k + 1]
endX = startX
} else {
startX = vForwards[k - 1]
endX = startX + 1
}
var endY = region.top + (endX - region.left) - k
val startY = if (depth == 0 || endX != startX) endY else endY - 1
while (endX < region.right && endY < region.bottom &&
original[endX] == updated[endY]) {
endX++
endY++
}
vForwards[k] = endX
if (region.delta.isOdd() && c in -(depth - 1) until depth && endY >= vBackwards[c]) {
return Snake(
start = Point(startX, startY),
end = Point(endX, endY)
)
}
k -= 2
}
return null
}
private fun backwards(
region: Region,
vForwards: CircularIntArray,
vBackwards: CircularIntArray,
depth: Int
): Snake? {
// This loop is effectively `for (c in (-depth..depth step 2).reversed())`, but avoids
// allocating a Range object.
var c = depth
while (c >= -depth) {
val k = c + region.delta
val endY: Int
var startY: Int
if (c == -depth || (c != depth && vBackwards[c - 1] > vBackwards[c + 1])) {
endY = vBackwards[c + 1]
startY = endY
} else {
endY = vBackwards[c - 1]
startY = endY - 1
}
var startX = region.left + (startY - region.top) + k
val endX = if (depth == 0 || startY != endY) startX else startX + 1
while (startX > region.left && startY > region.top &&
original[startX - 1] == updated[startY - 1]) {
startX--
startY--
}
vBackwards[c] = startY
if (region.delta.isEven() && k in -depth..depth && startX <= vForwards[k]) {
return Snake(
start = Point(startX, startY),
end = Point(endX, endY)
)
}
c -= 2
}
return null
}
}
| 2 | Kotlin | 1 | 15 | 3917a096f61bb26efba601436b49f88e10edcd51 | 8,155 | Difference | MIT License |
2021/src/day05/day5.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day05
import java.io.File
import kotlin.math.abs
fun main() {
val input = File("src/day05", "day5_input.txt").readLines()
val lines = input.mapNotNull { parseLine(it) }
val ventMap = VentMap()
lines.filter { isCardinal(it) }.forEach() {
ventMap.processLine(it.first, it.second)
}
println(ventMap.countPointsWithSize(2))
val ventMap2 = VentMap()
lines.forEach() {
ventMap2.processLine(it.first, it.second)
}
println(ventMap2.countPointsWithSize(2))
}
fun parseLine(lineStr : String) : Pair<Pair<Int, Int>, Pair<Int, Int>>? {
val regex = """(?<startX>\d+),(?<startY>\d+) -> (?<endX>\d+),(?<endY>\d+)""".toRegex()
val result = regex.matchEntire(lineStr)!!.groups as? MatchNamedGroupCollection
if (result != null) {
return Pair(Pair(result["startX"]!!.value.toInt(), result["startY"]!!.value.toInt()),
Pair(result["endX"]!!.value.toInt(), result["endY"]!!.value.toInt()))
}
return null
}
fun isCardinal(arg : Pair<Pair<Int, Int>, Pair<Int, Int>>) : Boolean {
return arg.first.first == arg.second.first || arg.first.second == arg.second.second
}
class VentMap() {
// Map of coordinates to count
private val coordinates : MutableMap<Pair<Int, Int>, Int> = mutableMapOf()
/**
* Processes a start and ending point, incrementing the coordinate count
*/
fun processLine(start: Pair<Int, Int>, end : Pair<Int, Int>) {
val xDelta = end.first - start.first
val yDelta = end.second - start.second
// Horizontal, vertical or diagonal with slope 1 or -1
val xStep : Int = if (xDelta == 0) 0 else xDelta / abs(xDelta)
val yStep : Int = if (yDelta == 0) 0 else yDelta / abs(yDelta)
var x = start.first
var y = start.second
while (x != end.first + xStep || y != end.second + yStep) {
coordinates[Pair(x,y)] = coordinates.getOrDefault(Pair(x,y), 0) + 1
x += xStep
y += yStep
}
}
fun countPointsWithSize(size : Int) : Int {
return coordinates.count { it.value >= size }
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 2,126 | adventofcode | Apache License 2.0 |
2021/src/day21/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day21
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(input: Input): Int {
var rolled = 0
val score = intArrayOf(0, 0)
val position = input.map { it - 1 }.toIntArray()
var current = 0
while (score.all { it < 1000 }) {
var move = 0
repeat(3) {
move += (rolled++) % 100 + 1
}
position[current] = (position[current] + move) % 10
score[current] += position[current] + 1
current = 1 - current
}
return rolled * score.find { it < 1000 }!!
}
fun part2(input: Input): Long {
val mem = Array(10) {
Array(10) {
Array(21) {
arrayOfNulls<Pair<Long, Long>?>(21)
}
}
}
fun rec(
firstPosition: Int,
secondPosition: Int,
firstScore: Int,
secondScore: Int,
): Pair<Long, Long> {
check(firstScore < 21)
if (secondScore >= 21) return Pair(0L, 1L)
mem[firstPosition][secondPosition][firstScore][secondScore]?.let { return it }
var firstWins = 0L
var secondWins = 0L
for (i in 1..3) {
for (j in 1..3) {
for (k in 1..3) {
val newPosition = (firstPosition + (i + j + k)) % 10
val (second, first) = rec(
firstPosition = secondPosition,
secondPosition = newPosition,
firstScore = secondScore,
secondScore = firstScore + newPosition + 1
)
firstWins += first
secondWins += second
}
}
}
return Pair(firstWins, secondWins).also {
mem[firstPosition][secondPosition][firstScore][secondScore] = it
}
}
val (first, second) = rec(
firstPosition = input[0] - 1,
secondPosition = input[1] - 1,
firstScore = 0,
secondScore = 0
)
return maxOf(first, second)
}
check(part1(readInput("test-input.txt")) == 739785)
check(part2(readInput("test-input.txt")) == 444356092776315L)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day21/$s")).readLines().mapIndexed { index, line ->
check(line.startsWith("Player ${index + 1} starting position: "))
line.substring("Player ${index + 1} starting position: ".length).toInt()
}
}
private typealias Input = List<Int> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 2,413 | advent-of-code | Apache License 2.0 |
src/2021-Day01.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | fun main() {
fun part1(input: List<String>): Int {
var increments = 0
var last: Int? = null
var next: Int? = null
for (line in input) {
next = line.trim().toInt()
if (last != null && next > last) {
increments++
}
last = next
}
return increments
}
fun part2(input: List<String>): Int {
var nums = input.map { it.trim().toInt() }
var last_deque = ArrayDeque(nums.take(3))
var last = last_deque.sum()
var next_deque = ArrayDeque(nums.subList(1, 4))
var next = next_deque.sum()
var increments = if (next > last) 1 else 0
for (ix in 4 until nums.size) {
last -= last_deque.removeFirst()
last += nums[ix-1]
last_deque.addLast(nums[ix-1])
next -= next_deque.removeFirst()
next += nums[ix]
next_deque.addLast(nums[ix])
if (next > last) {
increments++
}
}
return increments
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"199\n",
"200\n",
"208\n",
"210\n",
"200\n",
"207\n",
"240\n",
"269\n",
"260\n",
"263\n"
)
check(part1(testInput) == 7)
check(part2(testInput) == 5)
val input = readInput("2021-day1")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 1,519 | 2022-aoc-kotlin | Apache License 2.0 |
src/Year2022Day01.kt | zhangt2333 | 575,260,256 | false | {"Kotlin": 34993} | fun main() {
// O(size * log size) -> O(size * log n) -> O(size)
fun List<Int>.topN(n: Int): List<Int> {
if (this.size == n) return this
val x = this.random()
val small = this.filter { it < x }
val equal = this.filter { it == x }
val big = this.filter { it > x }
if (big.size >= n) return big.topN(n)
if (equal.size + big.size >= n) return (equal + big).takeLast(n)
return small.topN(n - equal.size - big.size) + equal + big
}
fun part1(input: String): Int {
val data = input.split("\n\n").map { it.lines().sumOf(String::toInt) }
return data.topN(1).sum()
}
fun part2(input: String): Int {
val data = input.split("\n\n").map { it.lines().sumOf(String::toInt) }
return data.topN(3).sum()
}
val text = readText()
println(part1(text))
println(part2(text))
}
| 0 | Kotlin | 0 | 0 | cdba887c4df3a63c224d5a80073bcad12786ac71 | 894 | aoc-2022-in-kotlin | Apache License 2.0 |
src/test/kotlin/days/y2022/Day08Test.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2022
import days.Day
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.Is.`is`
import org.junit.jupiter.api.Test
class Day08 : Day(2022, 8) {
override fun partOne(input: String): Any {
val grid = parseInput(input)
return grid
.cells()
.count { (y, x) -> isVisible(grid, y, x) }
}
private val directions = listOf(
-1 to 0,
0 to -1,
1 to 0,
0 to 1,
)
fun isVisible(grid: List<List<Int>>, y: Int, x: Int): Boolean {
val curr = grid[y][x]
if (y == 0 || x == 0) return true
for (direction in directions) {
val (dy, dx) = direction
var y2 = y + dy
var x2 = x + dx
var isVisible = true
while (isVisible && y2 >= 0 && x2 >= 0 && y2 < grid.size && x2 < grid[y2].size) {
val next = grid[y2][x2]
if (next >= curr) isVisible = false
y2 += dy
x2 += dx
}
if (isVisible) return true
}
return false
}
override fun partTwo(input: String): Any {
val grid = parseInput(input)
return grid.cells().maxOf { (y, x) -> scenicScore(grid, y, x) }
}
fun scenicScore(grid: List<List<Int>>, y: Int, x: Int): Int {
val height = grid[y][x]
val scores = directions.map { (dy, dx) ->
var y2 = y + dy
var x2 = x + dx
var score = 0
while (y2 >= 0 && x2 >= 0 && y2 < grid.size && x2 < grid[y2].size) {
val next = grid[y2][x2]
score++
if (next >= height) break
y2 += dy
x2 += dx
}
score
}
return scores.product()
}
private fun List<List<Int>>.cells(): Set<Pair<Int, Int>> =
indices.flatMap { y ->
this[y].indices.map { x -> y to x }
}.toSet()
fun parseInput(input: String): List<List<Int>> = input.lines().map { line ->
line.split("").filter { it.isNotBlank() }.map { char ->
char.toInt()
}
}
}
private fun List<Int>.product(): Int = this.fold(1) { acc, i -> acc * i }
class Day08Test {
private val example = """
30373
25512
65332
33549
35390
""".trimIndent()
@Test
fun isVisible() {
listOf(
Pair(0 to 0, true),
Pair(1 to 1, true),
Pair(1 to 3, false),
Pair(2 to 1, true),
Pair(2 to 2, false),
Pair(2 to 3, true),
Pair(3 to 2, true),
Pair(3 to 1, false),
Pair(3 to 3, false),
).forEach { (pos, expected) ->
val (y, x) = pos
val grid = Day08().parseInput(example)
assertThat(Day08().isVisible(grid, y, x), `is`(expected))
}
}
@Test
fun testExampleOne() {
assertThat(Day08().partOne(example), `is`(21))
}
@Test
fun testPartOne() {
assertThat(Day08().partOne(), `is`(1805))
}
@Test
fun scenicScore() {
listOf(
Pair(1 to 2, 4),
Pair(3 to 2, 8),
).forEach { (pos, expected) ->
val (y, x) = pos
val grid = Day08().parseInput(example)
assertThat(Day08().scenicScore(grid, y, x), `is`(expected))
}
}
@Test
fun testExampleTwo() {
assertThat(Day08().partTwo(example), `is`(8))
}
@Test
fun testPartTwo() {
assertThat(Day08().partTwo(), `is`(444528))
}
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 3,683 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/days/Day5.kt | andilau | 726,429,411 | false | {"Kotlin": 37060} | package days
@AdventOfCodePuzzle(
name = "If You Give A Seed A Fertilizer",
url = "https://adventofcode.com/2023/day/5",
date = Date(day = 5, year = 2023)
)
class Day5(input: List<String>) : Puzzle {
private val seeds = input.first().substringAfter("seeds: ").split(' ').map { it.toLong() }
private val seedRanges = seeds.windowed(2, 2).map { (start, length) -> start..<start + length }
private val rangeMaps: MutableList<MutableList<RangeMap>> = input.drop(2)
.filter(String::isNotBlank)
.fold(mutableListOf()) { acc, line ->
if (line.first().isLetter())
acc.add(mutableListOf())
else
acc.last().add(RangeMap.from(line))
acc
}
private val reversed = rangeMaps.reversed().map { ranges -> ranges.map { RangeMap(it.dest, it.source) } }
override fun partOne(): Long {
val minOf = seeds.minOf { seed ->
rangeMaps.fold(seed) { pos, ranges ->
ranges.firstOrNull { pos in it }?.map(pos) ?: pos
}
}
return minOf
}
override fun partTwo(): Long = generateSequence(0L) { it + 1 }
.first { position ->
val start = reversed.fold(position) { pos, ranges ->
ranges.firstOrNull { pos in it }?.map(pos) ?: pos
}
seedRanges.any { start in it }
}
data class RangeMap(val source: LongRange, val dest: LongRange) {
fun map(value: Long): Long = value - source.first + dest.first
operator fun contains(value: Long) = value in source
override fun toString(): String = "RangeMap($source -> $dest)"
companion object {
fun from(line: String): RangeMap = line
.split(' ').map { it.toLong() }
.let { (to, from, length) ->
RangeMap(
from..<from + length,
to..<to + length
)
}
}
}
} | 3 | Kotlin | 0 | 0 | 9a1f13a9815ab42d7fd1d9e6048085038d26da90 | 2,023 | advent-of-code-2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/pl/mrugacz95/aoc/day14/day14.kt | mrugacz95 | 317,354,321 | false | null | package pl.mrugacz95.aoc.day14
import java.lang.RuntimeException
sealed class Command
data class Mem(val addr: Long, val value: Long) : Command()
data class Mask(val mask: String) : Command()
fun generateValues(floatingValue: String): Sequence<String> = sequence {
when {
floatingValue.isEmpty() -> yield("") // break recursion
floatingValue[0] == 'X' -> { // split
yieldAll(generateValues('1' + floatingValue.substring(1, floatingValue.length)))
yieldAll(generateValues('0' + floatingValue.substring(1, floatingValue.length)))
}
else -> { // continue
yieldAll(generateValues(floatingValue.substring(1, floatingValue.length))
.map { floatingValue[0] + it })
}
}
}
fun applyMask(value: String, mask: String): String {
return value.padStart(36, '0').zip(mask).map {
when (it.second) {
'0' -> it.first
else -> it.second
}
}.joinToString("")
}
fun solve(commands: List<Command>, simpleMem: Boolean = true): Long {
val mem = hashMapOf<Long, Long>()
var mask: String? = null
for (command in commands) {
when (command) {
is Mask -> {
mask = command.mask
}
is Mem -> {
val currentMask = mask ?: throw RuntimeException("Mask not initialized")
when {
simpleMem -> {
val zeroMask = currentMask.replace('X', '1').toLong(2)
val oneMask = currentMask.replace('X', '0').toLong(2)
mem[command.addr] = (command.value or oneMask) and zeroMask
}
else -> {
val maskedAddr = applyMask(command.addr.toString(2), currentMask)
for (addr in generateValues(maskedAddr)) {
mem[addr.toLong(2)] = command.value
}
}
}
}
}
}
return mem.values.sum()
}
fun parseLine(line: String): Command {
return when (line.substring(0, 4)) {
"mem[" -> {
val regex = "mem\\[(?<addr>\\d+)] = (?<value>\\d+)".toRegex()
val groups = regex.matchEntire(line)?.groups ?: throw RuntimeException("Unrecognized mem line: $line")
val mem = groups["addr"]?.value?.toLong() ?: throw RuntimeException("Didn't found addr in memory line")
val value = groups["value"]?.value?.toLong() ?: throw RuntimeException("Didn't found value in memory line")
Mem(mem, value)
}
"mask" -> {
val mask = line.replace("mask = ", "")
Mask(mask)
}
else -> throw RuntimeException("Unrecognized line: $line")
}
}
fun main() {
val commands = {}::class.java.getResource("/day14.in")
.readText()
.split("\n")
.map { parseLine(it) }
println("Answer part 1: ${solve(commands)}")
println("Answer part 2: ${solve(commands, false)}")
} | 0 | Kotlin | 0 | 1 | a2f7674a8f81f16cd693854d9f564b52ce6aaaaf | 3,096 | advent-of-code-2020 | Do What The F*ck You Want To Public License |
kotlin-practice/src/main/kotlin/exercise/collection/CollectionOperators3.kt | nicolegeorgieva | 590,020,790 | false | {"Kotlin": 120359} | package exercise.collection
fun main() {
val employees = listOf(
Employee(
employeeId = 124,
name = "Kayla",
department = "HR",
salary = 2000.00
),
Employee(
employeeId = 125,
name = "Lulu",
department = "IT",
salary = 5600.00
),
Employee(
employeeId = 126,
name = "Amy",
department = "Customer support",
salary = 1500.00
)
)
println(filterByLetter(employees, 'U'))
}
data class Employee(
val employeeId: Int,
val name: String,
val department: String,
val salary: Double
)
fun findEmployeeById(employees: List<Employee>, id: Int): Employee? {
return employees.find { it.employeeId == id }
}
// sorts the list of employees alphabetically by their names
fun sortEmployeesByName(employees: List<Employee>): List<Employee> {
return employees.sortedBy { it.name }
}
fun filterEmployeesByDepartment(employees: List<Employee>): Map<String, List<Employee>> {
return employees.groupBy { it.department }
}
fun filterEmployeesByGivenDepartment(employees: List<Employee>, department: String): List<Employee> {
return employees.filter { it.department == department }
}
sealed interface TopNSalariesResult {
data class Error(val message: String) : TopNSalariesResult
data class Success(val list: List<Employee>) : TopNSalariesResult
}
fun findTopNSalaries(employees: List<Employee>, topN: Int): TopNSalariesResult {
if (topN <= 0 || topN > employees.size) return TopNSalariesResult.Error("Invalid criteria")
val res = employees.sortedByDescending { it.salary }.take(topN)
return TopNSalariesResult.Success(res)
}
// Pair(IT, 5600), Pair(HR, 2000)
fun calculateAverageSalaryByDepartment(employees: List<Employee>): Map<String, Double> {
val filtered = filterEmployeesByDepartment(employees)
return filtered.mapValues { (_, filtered) ->
filtered.map { it.salary }.average()
}
}
// Filter employees by a specific letter in their name
fun filterByLetter(employees: List<Employee>, letter: Char): List<Employee> {
return employees.filter { !it.name.uppercase().contains(letter.uppercase()) }
}
| 0 | Kotlin | 0 | 1 | c96a0234cc467dfaee258bdea8ddc743627e2e20 | 2,271 | kotlin-practice | MIT License |
src/main/kotlin/g0801_0900/s0864_shortest_path_to_get_all_keys/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0864_shortest_path_to_get_all_keys
// #Hard #Breadth_First_Search #Bit_Manipulation
// #2022_03_29_Time_176_ms_(100.00%)_Space_36.3_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
private var m = 0
private var n = 0
fun shortestPathAllKeys(stringGrid: Array<String>): Int {
// strategy: BFS + masking
m = stringGrid.size
n = stringGrid[0].length
val grid = Array(m) { CharArray(n) }
var index = 0
// convert to char Array
for (s in stringGrid) {
grid[index++] = s.toCharArray()
}
// number of keys
var count = 0
val q: Queue<IntArray> = LinkedList()
for (i in 0 until m) {
for (j in 0 until n) {
// find starting position
if (grid[i][j] == '@') {
q.add(intArrayOf(i, j, 0))
}
// count number of keys
if (grid[i][j] in 'a'..'f') {
count++
}
}
}
val dx = intArrayOf(-1, 0, 1, 0)
val dy = intArrayOf(0, -1, 0, 1)
// this is the amt of keys we need
val target = (1 shl count) - 1
// keep track of position and current state
val visited = Array(m) {
Array(n) {
BooleanArray(target + 1)
}
}
// set initial position and state to true
visited[q.peek()[0]][q.peek()[1]][0] = true
var steps = 0
while (q.isNotEmpty()) {
// use size to make sure everything is on one level
var size = q.size
while (--size >= 0) {
val curr = q.poll()
val x = curr[0]
val y = curr[1]
val state = curr[2]
// found all keys
if (state == target) {
return steps
}
for (i in 0..3) {
val nx = x + dx[i]
val ny = y + dy[i]
// use new state so we don't mess up current state
var nState = state
// out of bounds or reached wall
if (!inBounds(nx, ny) || grid[nx][ny] == '#') {
continue
}
// found key
// use OR to add key to our current state because if we already had the key the
// digit would still be 1/true
if (grid[nx][ny] in 'a'..'f') {
// bit mask our found key
nState = state or (1 shl grid[nx][ny] - 'a')
}
// found lock
// use & to see if we have the key
// 0 means that the digit we are looking at is 0
// need a 1 at the digit spot which means there is a key there
if (('A' > grid[nx][ny] || grid[nx][ny] > 'F' || nState and (1 shl grid[nx][ny] - 'A') != 0) &&
!visited[nx][ny][nState]
) {
q.add(intArrayOf(nx, ny, nState))
visited[nx][ny][nState] = true
}
}
}
steps++
}
return -1
}
private fun inBounds(x: Int, y: Int): Boolean {
return x in 0 until m && y >= 0 && y < n
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,506 | LeetCode-in-Kotlin | MIT License |
codeforces/globalround7/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.globalround7
fun main() {
val n = readInt()
val p = readInts().map { it - 1 }
val q = readInts().map { it - 1 }
val pRev = IntArray(n)
for (i in p.indices) pRev[p[i]] = i
val st = SegmentsTreeSimple(2 * n)
var alive = n
val ans = q.map {
while (st.getMinBalance() >= 0) st[2 * n - 2 * pRev[--alive] - 1] = -1
st[2 * n - 2 * it - 2] = 1
alive
}
println(ans.map{ it + 1 }.joinToString(" "))
}
class SegmentsTreeSimple(var n: Int) {
var size = 2 * Integer.highestOneBit(n)
var min = IntArray(2 * size)
var sum = IntArray(2 * size)
operator fun set(index: Int, value: Int) {
var i = size + index
min[i] = minOf(0, value)
sum[i] = value
while (i > 1) {
i /= 2
min[i] = minOf(min[2 * i], sum[2 * i] + min[2 * i + 1])
sum[i] = sum[2 * i] + sum[2 * i + 1]
}
}
fun getMinBalance(): Int = min[1]
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,037 | competitions | The Unlicense |
src/main/java/challenges/educative_grokking_coding_interview/twe_pointers/_2/SumOfThree.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.twe_pointers._2
import challenges.util.PrintHyphens
import java.util.*
/**
Given an array of integers, nums, and an integer value, target, determine if
there are any three integers in nums whose sum is equal to the target, that is,
nums[i] + nums[j] + nums[k] == target. Return TRUE if three such integers exist in the array.
Otherwise, return FALSE.
Note: A valid triplet consists of elements with distinct indexes.
https://www.educative.io/courses/grokking-coding-interview-patterns-java/qAW3LvvJrQy
*/
object SumOfThree {
private fun findSumOfThree(nums: IntArray, target: Int): Boolean {
// Sort the input list
Arrays.sort(nums)
var low: Int
var high: Int
var triples: Int
// Fix one integer at a time and find the other two
for (i in 0 until nums.size - 2) {
// Initialize the two pointers
low = i + 1
high = nums.size - 1
// Traverse the list to find the triplet whose sum equals the target
while (low < high) {
triples = nums[i] + nums[low] + nums[high]
// The sum of the triplet equals the target
if (triples == target) {
return true
} else if (triples < target) {
low++
} else {
high--
}
}
}
// No such triplet found whose sum equals the given target
return false
}
@JvmStatic
fun main(args: Array<String>) {
val numsList = arrayOf(
intArrayOf(3, 7, 1, 2, 8, 4, 5),
intArrayOf(-1, 2, 1, -4, 5, -3),
intArrayOf(2, 3, 4, 1, 7, 9),
intArrayOf(1, -1, 0),
intArrayOf(2, 4, 2, 7, 6, 3, 1)
)
val testList = intArrayOf(10, 7, 20, -1, 8)
for (i in testList.indices) {
print(i + 1)
println(".\tInput array: " + numsList[i].contentToString())
if (findSumOfThree(numsList[i], testList[i])) {
println("\tSum for " + testList[i] + " exists ")
} else {
println("\tSum for " + testList[i] + " does not exist ")
}
println(PrintHyphens.repeat("-", 100))
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,347 | CodingChallenges | Apache License 2.0 |
src/Day02.kt | timj11dude | 572,900,585 | false | {"Kotlin": 15953} | fun main() {
/**
* A , X = Rock
* B , Y = Paper
* C , Z = Scissors
*/
fun points(theirs: String, yours: String) = when (theirs) {
"A" -> when (yours) {
"X" -> 3
"Y" -> 6
"Z" -> 0
else -> throw IllegalArgumentException("Unknown yours value")
}
"B" -> when (yours) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> throw IllegalArgumentException("Unknown yours value")
}
"C" -> when (yours) {
"X" -> 6
"Y" -> 0
"Z" -> 3
else -> throw IllegalArgumentException("Unknown yours value")
}
else -> throw IllegalArgumentException("Unknown yours value")
} + when (yours) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> throw IllegalArgumentException("Unknown yours value")
}
fun part1(input: Collection<String>): Int = input
.map { it.split(" ") }
.sumOf { points(it.first(), it.last()) }
fun part2(input: Collection<String>): Int {
fun String.getDrawPoints() = when (this) {
"A" -> 1 + 3
"B" -> 2 + 3
"C" -> 3 + 3
else -> throw IllegalArgumentException("Unknown choice")
}
fun String.getWinPoints() = when (this) {
"A" -> 2 + 6
"B" -> 3 + 6
"C" -> 1 + 6
else -> throw IllegalArgumentException("Unknown choice")
}
fun String.getLosePoints() = when (this) {
"A" -> 3
"B" -> 1
"C" -> 2
else -> throw IllegalArgumentException("Unknown choice")
}
return input
.map { it.split(" ") }
.sumOf {
when (it.last()) {
"X" -> it.first().getLosePoints()
"Y" -> it.first().getDrawPoints()
"Z" -> it.first().getWinPoints()
else -> throw IllegalArgumentException("Unknown outcome")
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 28aa4518ea861bd1b60463b23def22e70b1ed481 | 2,366 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountCharacters.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
/**
* 1160. Find Words That Can Be Formed by Characters
* @see <a href="https://leetcode.com/problems/find-words-that-can-be-formed-by-characters">Source</a>
*/
fun interface CountCharacters {
operator fun invoke(words: Array<String>, chars: String): Int
}
class CountCharactersHashMap : CountCharacters {
override fun invoke(words: Array<String>, chars: String): Int {
val counts: MutableMap<Char, Int> = HashMap()
for (c in chars.toCharArray()) {
counts[c] = counts.getOrDefault(c, 0) + 1
}
var ans = 0
for (word in words) {
val wordCount: MutableMap<Char, Int> = HashMap()
for (c in word.toCharArray()) {
wordCount[c] = wordCount.getOrDefault(c, 0) + 1
}
var good = true
for (c in wordCount.keys) {
if (counts.getOrDefault(c, 0) < wordCount.getOrDefault(c, 0)) {
good = false
break
}
}
if (good) {
ans += word.length
}
}
return ans
}
}
class CountCharactersArray : CountCharacters {
override fun invoke(words: Array<String>, chars: String): Int {
val arr = IntArray(ALPHABET_LETTERS_COUNT)
for (ch in chars.toCharArray()) {
arr[ch - 'a']++
}
var ans = 0
for (s in words) {
val clone = arr.clone()
for (i in s.indices) {
clone[s[i] - 'a']--
if (clone[s[i] - 'a'] < 0) {
break
}
if (i == s.length - 1) {
ans += s.length
}
}
}
return ans
}
}
class CountCharactersStd : CountCharacters {
override fun invoke(words: Array<String>, chars: String): Int {
val countChars = chars.groupingBy { it }.eachCount()
return words.filter { word ->
word.groupingBy { it }.eachCount()
.all { (w, c) -> c <= countChars.getOrDefault(w, 0) }
}
.sumOf { it.length }
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,841 | kotlab | Apache License 2.0 |
src/Day14.kt | SergeiMikhailovskii | 573,781,461 | false | {"Kotlin": 32574} | import kotlin.math.max
import kotlin.math.min
fun main() {
class Point(
val x: Int,
val y: Int
)
val initial = 500
val input = readInput("Day14_test")
val mapped = input.map {
it.split(" -> ").map {
val arr = it.split(",")
Point(arr[0].toInt(), arr[1].toInt())
}
}
var maxY = Int.MIN_VALUE
for (i in mapped.indices) {
for (j in mapped[i].indices) {
maxY = max(maxY, mapped[i][j].y)
}
}
val minX = initial - maxY - 2
val maxX = initial + maxY + 2
val width = maxX - minX + 1
val matrix = Array(maxY + 3) { Array(width) { "." } }
for (j in matrix.last().indices) {
matrix[matrix.size - 1][j] = "#"
}
mapped.forEach {
var start = it[0]
for (i in 1 until it.size) {
val end = it[i]
if (start.x == end.x) {
for (j in min(start.y, end.y)..max(start.y, end.y)) {
matrix[j][start.x - minX] = "#"
}
} else if (start.y == end.y) {
for (j in min(start.x, end.x)..max(start.x, end.x)) {
matrix[start.y][j - minX] = "#"
}
}
start = end
}
}
fun moveLower(point: Point): Boolean {
if (matrix[point.y][point.x] == ".") {
if (!moveLower(Point(y = point.y + 1, x = point.x))) {
matrix[point.y][point.x] = "0"
}
return true
} else if (matrix[point.y][point.x - 1] == ".") {
if (!moveLower(Point(y = point.y + 1, x = point.x - 1))) {
matrix[point.y][point.x - 1] = "0"
}
return true
} else if (matrix[point.y][point.x + 1] == ".") {
if (!moveLower(Point(y = point.y + 1, x = point.x + 1))) {
matrix[point.y][point.x + 1] = "0"
}
return true
}
return false
}
var counter = 0
try {
while (true) {
moveLower(Point(initial - minX, 0))
counter++
}
} catch (e: ArrayIndexOutOfBoundsException) {
println(counter)
}
}
| 0 | Kotlin | 0 | 0 | c7e16d65242d3be6d7e2c7eaf84f90f3f87c3f2d | 2,214 | advent-of-code-kotlin | Apache License 2.0 |
app/src/main/kotlin/day02/Day02.kt | tobiasbexelius | 437,250,135 | false | {"Kotlin": 33606} | package day02
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 2
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay02Part1, ::solveDay02Part2)
}
fun solveDay02Part1(input: List<String>): Int =
input.asSequence()
.map { fullCmd ->
val splitCmd = fullCmd.split(" ")
splitCmd[0] to splitCmd[1].toInt()
}
.fold(0 to 0) { (d, h), (cmd, units) ->
when (cmd) {
"forward" -> d to h + units
"up" -> d - units to h
"down" -> d + units to h
else -> throw IllegalArgumentException()
}
}
.let { (d, h) -> d * h }
fun solveDay02Part2(input: List<String>): Int {
data class Position(val d: Int, val h: Int, val aim: Int)
return input.asSequence()
.map { fullCmd ->
val splitCmd = fullCmd.split(" ")
splitCmd[0] to splitCmd[1].toInt()
}
.fold(Position(0, 0, 0)) { p, (cmd, units) ->
when (cmd) {
"forward" -> p.copy(d = p.d + p.aim * units, h = p.h + units)
"up" -> p.copy(aim = p.aim - units)
"down" -> p.copy(aim = p.aim + units)
else -> throw IllegalArgumentException()
}
}
.let { (d, h) -> d * h }
}
| 0 | Kotlin | 0 | 0 | 3f9783e78e7507eeddde869cf24d34ec6e7e3078 | 1,431 | advent-of-code-21 | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2021/Day4.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 4: Giant Squid ---
* https://adventofcode.com/2021/day/4
*/
class Day4 : Solver {
override fun solve(lines: List<String>): Result {
val (numbers, boards) = parseData(lines)
return Result("${solve(boards, numbers, false)}", "${solve(boards, numbers, true)}")
}
fun solve(boards: MutableList<BingoBoard>, numbers: List<Long>, partB: Boolean): Long {
for (num in numbers) {
boards.forEach { it.mark(num) }
val toRemove = boards.filter { it.isWon() }.filter { boards.contains(it) }
boards.removeAll(toRemove)
if (partB && boards.isEmpty()) return toRemove[0].unmarkedSum() * num
if (!partB && toRemove.isNotEmpty()) return toRemove[0].unmarkedSum() * num
}
error("No board won")
}
private fun parseData(lines: List<String>): Pair<List<Long>, MutableList<BingoBoard>> {
val numbers = lines[0].split(",").map { it.toLong() }
val boards = mutableListOf<BingoBoard>()
for (line in lines.listIterator(1)) {
if (line.isEmpty()) {
boards.add(BingoBoard(mutableListOf()))
} else {
boards.last().feedLine(line)
}
}
return Pair(numbers, boards)
}
}
class BingoBoard(val values: MutableList<Long>) {
fun feedLine(line: String) {
values.addAll(line.split(" ").filter { it.isNotBlank() }.map { it.toLong() })
}
fun mark(num: Long) {
values.replaceAll { if (it == num) -1 else it }
}
fun get(x: Int, y: Int) = values[y * 5 + x]
fun unmarkedSum() = values.filter { it != -1L }.sum()
fun isWon(): Boolean {
(0..4).forEach { y -> if ((0..4).map { x -> get(x, y) }.count { it == -1L } == 5) return true }
(0..4).forEach { x -> if ((0..4).map { y -> get(x, y) }.count { it == -1L } == 5) return true }
return false
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,855 | euler | Apache License 2.0 |
src/Day13.kt | freszu | 573,122,040 | false | {"Kotlin": 32507} | import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.*
sealed interface Packet : Comparable<Packet> {
@JvmInline
value class IntValue(val int: Int) : Packet {
override fun compareTo(other: Packet): Int = when (other) {
is IntValue -> int.compareTo(other.int)
is ListValue -> ListValue(listOf(this)).compareTo(other)
}
}
@JvmInline
value class ListValue(val packets: List<Packet>) : Packet {
override fun compareTo(other: Packet): Int {
when (other) {
is IntValue -> return this.compareTo(ListValue(listOf(other)))
is ListValue -> {
this.packets.indices.forEach { index ->
if (index > other.packets.lastIndex) return 1
val comparison = this.packets[index].compareTo(other.packets[index])
if (comparison != 0) return comparison
}
if (this.packets.size < other.packets.size) return -1
}
}
return 0
}
}
}
fun main() {
fun parsePacket(input: String): Packet {
// surrender - cant skip this additional step even using value classes:
// https://github.com/Kotlin/kotlinx.serialization/issues/2049#issuecomment-1271536271
fun parseJsonArray(jsonElement: JsonElement): Packet {
return when (jsonElement) {
is JsonArray -> Packet.ListValue(jsonElement.map { parseJsonArray(it) })
is JsonPrimitive -> Packet.IntValue(jsonElement.int)
else -> throw IllegalArgumentException("Unknown json element: $jsonElement")
}
}
val jsonArray = Json.decodeFromString<JsonArray>(input)
return parseJsonArray(jsonArray)
}
fun part1(input: String) = input.split("\n\n")
.map {
val (leftPacket, rightPacket) = it.split("\n")
parsePacket(leftPacket) to parsePacket(rightPacket)
}
.withIndex()
.sumOf { (index, pair) ->
val (left, right) = pair
if (left <= right) index + 1 else 0
}
fun part2(input: List<String>): Int {
val divider1 = parsePacket("[[2]]")
val divider2 = parsePacket("[[6]]")
val sorted = input.asSequence()
.filter(String::isNotBlank)
.map(::parsePacket)
.plus(sequenceOf(divider1, divider2))
.sorted()
return (1 + sorted.indexOf(divider1)) * (1 + sorted.indexOf(divider2))
}
val testInput = readInputAsString("Day13_test")
val input = readInputAsString("Day13")
val testInputLines = readInput("Day13_test")
val inputLines = readInput("Day13")
check(part1(testInput) == 13)
println(part1(input))
check(part2(testInputLines) == 140)
println(part2(inputLines))
}
| 0 | Kotlin | 0 | 0 | 2f50262ce2dc5024c6da5e470c0214c584992ddb | 2,923 | aoc2022 | Apache License 2.0 |
src/Day02.kt | flex3r | 572,653,526 | false | {"Kotlin": 63192} | fun main() {
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input.map(::parseLine)
.sumOf { (opponent, player) ->
val baseScore = player + 1
val gameScore = when ((player - opponent).mod(3)) {
0 -> 3
1 -> 6
else -> 0
}
baseScore + gameScore
}
}
private fun part2(input: List<String>): Int {
return input.map(::parseLine)
.sumOf { (opponent, player) ->
val gameScore = player * 3
val move = when (gameScore) {
0 -> 2
3 -> 0
else -> 1
}
val baseScore = (move + opponent).mod(3) + 1
baseScore + gameScore
}
}
private fun parseLine(line: String): Pair<Int, Int> = line.first() - 'A' to line.last() - 'X' | 0 | Kotlin | 0 | 0 | 8604ce3c0c3b56e2e49df641d5bf1e498f445ff9 | 1,055 | aoc-22 | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2022/Day12.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2022
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.XY
import com.s13g.aoc.resultFrom
/**
* --- Day 12: Hill Climbing Algorithm ---
* https://adventofcode.com/2022/day/12
*/
class Day12 : Solver {
override fun solve(lines: List<String>): Result {
return resultFrom(solve(lines, false), solve(lines, true))
}
fun solve(lines: List<String>, partB: Boolean): Int {
val (start, end) = getStartEndPos(lines)
val visited = mutableSetOf<XY>()
var active = if (!partB) setOf(start) else setOf(end)
var length = 0
while ((!partB && !active.contains(end)) ||
(partB && active.none { lines[it.y][it.x] == 'a' })
) {
val old = active.toSet()
active = active.filter { it !in visited }
.flatMap { spawn(it, lines, partB, visited) }.toSet()
visited.addAll(old)
length++
}
return length
}
private fun spawn(
from: XY,
lines: List<String>,
partB: Boolean,
visited: Set<XY>
): List<XY> {
val currentElevation = elevation(from, lines)
val dirOptions = listOf(
XY(from.x - 1, from.y), XY(from.x + 1, from.y),
XY(from.x, from.y - 1), XY(from.x, from.y + 1)
).filter { it !in visited }
val result = mutableListOf<XY>()
for (dir in dirOptions) {
if (dir.x in 0 until lines[0].length && dir.y in lines.indices) {
val newElevation = elevation(dir, lines)
if (!partB) {
if (newElevation in 0..currentElevation + 1) result.add(dir)
} else {
if (newElevation in currentElevation - 1..25) result.add(dir)
}
}
}
return result
}
private fun elevation(pos: XY, lines: List<String>): Int {
val ch = lines[pos.y][pos.x]
if (ch == 'S') return 0
if (ch == 'E') return 'z'.code - 'a'.code
return ch.code - 'a'.code
}
private fun getStartEndPos(lines: List<String>): Pair<XY, XY> {
var start = XY(0, 0)
var end = XY(0, 0)
for ((y, line) in lines.withIndex()) {
for ((x, ch) in line.withIndex()) {
if (ch == 'S') start = XY(x, y)
if (ch == 'E') end = XY(x, y)
}
}
return Pair(start, end)
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,192 | euler | Apache License 2.0 |
src/main/kotlin/aoc2018/day7/Steps.kt | arnab | 75,525,311 | false | null | package aoc2018.day7
data class Step(val id: String, val timeToComplete: Int = 0)
data class Worker(val id: Int, var currentStep: Step? = null, var secondsSpent: Int = 0) {
fun isWorking() = currentStep != null
@Synchronized fun assignWork(step: Step?, seconds: Int = 0) {
currentStep = step
secondsSpent = seconds
}
@Synchronized fun isWorkComplete() = currentStep != null && secondsSpent > currentStep!!.timeToComplete
}
object Steps {
fun calculateOrder(steps: List<Pair<Step, Step>>): List<Step> {
val stepsInOrderOfCompletion = mutableListOf<Step>()
val remainingStepsSorted = (steps.map { it.first } + steps.map { it.second }).distinct().sortedBy { it.id }.toMutableList()
val totalStepsCount = remainingStepsSorted.size
val dependencies: MutableMap<Step, MutableSet<Step>> = steps.fold(mutableMapOf()) { deps, (dependentStep, step) ->
deps.computeIfAbsent(step) { mutableSetOf() }.add(dependentStep)
deps
}
while(stepsInOrderOfCompletion.size < totalStepsCount) {
val nextStep = remainingStepsSorted.first { step ->
!dependencies.containsKey(step) || dependencies.getOrDefault(step, mutableSetOf()).isEmpty()
}
stepsInOrderOfCompletion.add(nextStep)
remainingStepsSorted.remove(nextStep)
dependencies.forEach { _, dependentSteps -> dependentSteps.remove(nextStep) }
}
return stepsInOrderOfCompletion
}
fun calculateOrderWithWorkers(steps: List<Pair<Step, Step>>, numWorkers: Int): Pair<List<Step>, Long> {
var currentTime: Long = 0
val workers = (0..(numWorkers-1)).map { i -> Worker(i) }
val stepsInOrderOfCompletion = mutableListOf<Step>()
val remainingStepsSorted = (steps.map { it.first } + steps.map { it.second }).distinct().sortedBy { it.id }.toMutableList()
val totalStepsCount = remainingStepsSorted.size
val dependencies: MutableMap<Step, MutableSet<Step>> = steps.fold(mutableMapOf()) { deps, (dependentStep, step) ->
deps.computeIfAbsent(step) { mutableSetOf() }.add(dependentStep)
deps
}
while(stepsInOrderOfCompletion.size < totalStepsCount || workers.any(Worker::isWorking)) {
// 1. Update current worker's states
workers.filter(Worker::isWorking).forEach { worker ->
worker.secondsSpent++
if (worker.isWorkComplete()) {
val completedStep = worker.currentStep!!
stepsInOrderOfCompletion.add(completedStep)
dependencies.forEach { _, dependentSteps -> dependentSteps.remove(completedStep) }
worker.assignWork(null)
}
}
// 2. Assign new worker to idle workers
workers.filterNot(Worker::isWorking).forEach {
val nextStep = remainingStepsSorted.firstOrNull { step ->
!dependencies.containsKey(step) || dependencies.getOrDefault(step, mutableSetOf()).isEmpty()
}
if (nextStep != null) {
remainingStepsSorted.remove(nextStep)
it.assignWork(nextStep, 1)
}
}
report(currentTime, workers, stepsInOrderOfCompletion)
currentTime++
}
return Pair(stepsInOrderOfCompletion, currentTime - 1)
}
private fun report(currentTime: Long, workers: List<Worker>, stepsInOrderOfCompletion: MutableList<Step>) {
val printWorker = { w:Worker -> w.currentStep?.id ?: "." }
println("Time: $currentTime " +
"Workers: [${workers.map(printWorker).joinToString(" ")}] " +
"Completed: ${stepsInOrderOfCompletion.map(Step::id).joinToString("")}")
}
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 3,877 | adventofcode | MIT License |
src/main/kotlin/com/headlessideas/adventofcode/december10/KnotHash.kt | Nandi | 113,094,752 | false | null | package com.headlessideas.adventofcode.december10
fun main(args: Array<String>) {
val input = "147,37,249,1,31,2,226,0,161,71,254,243,183,255,30,70"
val knotHash = KnotHash(input)
println(knotHash.hash())
}
class KnotHash(input: String) {
private val seed = input.toCharArray().map { it.toInt() } + listOf(17, 31, 73, 47, 23)
private val sparseHash = IntArray(256, { it })
private var current = 0
private var skip = 0
private lateinit var hash: String
fun hash(): String {
for (i in 1..64) {
calculateSparseHash()
}
hash = sparseHash.asSequence()
.batch(16)
.map { it.reduce { a, b -> a.xor(b) } }
.map { it.toString(16).padStart(2, '0') }
.joinToString(separator = "")
return hash
}
private fun calculateSparseHash() {
for (length in seed) {
val subArray = sparseHash.subArray(current, length).reversedArray()
sparseHash.setAll(current, subArray)
current = (current + length + skip) % sparseHash.size
skip++
}
}
}
fun IntArray.subArray(start: Int, length: Int): IntArray {
val sub = (start..(start + length - 1)).map { get(it % size) }
return sub.toIntArray()
}
fun IntArray.setAll(pos: Int, values: IntArray) {
values.forEachIndexed { i, v -> set((pos + i) % size, v) }
}
//https://stackoverflow.com/questions/34498368/kotlin-convert-large-list-to-sublist-of-set-partition-size
fun <T> Sequence<T>.batch(n: Int): Sequence<List<T>> {
return BatchingSequence(this, n)
}
private class BatchingSequence<T>(val source: Sequence<T>, val batchSize: Int) : Sequence<List<T>> {
override fun iterator(): Iterator<List<T>> = object : AbstractIterator<List<T>>() {
val iterate = if (batchSize > 0) source.iterator() else emptyList<T>().iterator()
override fun computeNext() {
if (iterate.hasNext()) setNext(iterate.asSequence().take(batchSize).toList())
else done()
}
}
} | 0 | Kotlin | 0 | 0 | 2d8f72b785cf53ff374e9322a84c001e525b9ee6 | 2,064 | adventofcode-2017 | MIT License |
src/Day06.kt | kent10000 | 573,114,356 | false | {"Kotlin": 11288} | fun main() {
fun MutableList<Char>.addRemove(char: Char) {
this.removeAt(0)
this.add(char)
}
fun CharIterator.nextChars(count: Int): List<Char> {
val list = mutableListOf<Char>()
for (u in 0 until count) {
list.add(this.nextChar())
}
return list
}
fun findMessageIndex(input: String, sequenceLength: Int): Int {
val s = input.iterator()
var char4 = s.nextChars(sequenceLength).toMutableList()
var count = sequenceLength
while (char4.distinct().size != sequenceLength) {
char4.addRemove(s.nextChar())
count++
}
return count
}
fun part1(input: List<String>): Int {
return findMessageIndex(input.first(), 4)
//val sections = input.first().chunked(4)
/*for ((i, section) in sections.withIndex()) {
if (section.toList().distinct().size != section.count()) continue
return (i*4) + 4
}*/
//return 0
}
fun part2(input: List<String>): Int {
return findMessageIndex(input.first(), 14)
}
/* test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
*/
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c128d05ab06ecb2cb56206e22988c7ca688886ad | 1,387 | advent-of-code-2022 | Apache License 2.0 |
parserkt-ext/src/commonMain/kotlin/org/parserkt/pat/ext/NumUnitPattern.kt | ParserKt | 242,278,819 | false | null | package org.parserkt.pat.ext
import org.parserkt.*
import org.parserkt.util.*
import org.parserkt.pat.*
import org.parserkt.pat.complex.PairedTriePattern
// File: pat/ext/NumUnitPattern
typealias NumUnit<NUM, IN> = Pair<NUM, Iterable<IN>>
/*
val num = RepeatUn(asInt(), LexicalBasics.digitFor('0'..'9')) { it.toString().map { it-'0' } }
val timeUnit = PairedKeywordPattern<Int>().apply { mergeStrings("s" to 1, "min" to 60, "hr" to 60*60) }
val time = TrieNumUnit(num, timeUnit, IntOps)
*/
/** Pattern for `"2hr1min14s"`, note that reverse map won't be updated every [show] */
abstract class NumUnitPattern<IN, NUM: Comparable<NUM>>(val number: Pattern<IN, NUM>, open val unit: Pattern<IN, NUM>,
protected val op: NumOps<NUM>): PreetyPattern<IN, NUM>() {
protected open fun rescue(s: Feed<IN>, acc: NUM, i: NUM): NUM? = notParsed.also { s.error("expecting unit for $i (accumulated $acc)") }
override fun read(s: Feed<IN>): NUM? {
var accumulator: NUM = op.zero
var lastUnit: NumUnit<NUM, IN>? = null
var i: NUM? = number.read(s) ?: return notParsed
while (i != notParsed) { // i=num, k=unit
val k = unit.read(s) ?: rescue(s, accumulator, i) ?: return notParsed
val unit = reversedPairsDsc.first { it.first == k }
accumulator = (if (lastUnit == null) joinUnitsInitial(s, k, i) ?: return notParsed
else joinUnits(s, lastUnit, unit, accumulator, i)) ?: return accumulator
lastUnit = unit //->
i = number.read(s)
}
return accumulator
}
override fun show(s: Output<IN>, value: NUM?) {
if (value == null) return
var rest: NUM = value
var lastUnit: NumUnit<NUM, IN>? = null
while (rest != op.zero) {
val unit = maxCmpLE(rest)
if (lastUnit != null) joinUnitsShow(s, lastUnit, unit)
lastUnit = unit //->
val (ratio, name) = unit
val i = op.div(ratio, rest); rest = op.rem(ratio, rest)
number.show(s, i); name.forEach(s)
}
}
protected abstract val map: Map<Iterable<IN>, NUM>
protected val reversedPairsDsc by lazy { map.reversedMap().toList().sortedByDescending { it.first } }
protected fun maxCmpLE(value: NUM) = reversedPairsDsc.first { it.first <= value }
override fun toPreetyDoc() = listOf("NumUnit", number, unit).preety().colonParens()
protected open fun joinUnitsInitial(s: Feed<IN>, k: NUM, i: NUM): NUM? = op.times(k, i)
protected open fun joinUnits(s: Feed<IN>, u0: NumUnit<NUM, IN>, u1: NumUnit<NUM, IN>, acc: NUM, i: NUM): NUM? = op.run { plus(times(u1.first, i), acc) }
protected open fun joinUnitsShow(s: Output<IN>, u0: NumUnit<NUM, IN>, u1: NumUnit<NUM, IN>) {}
}
open class TrieNumUnit<IN, NUM: Comparable<NUM>>(number: Pattern<IN, NUM>, override val unit: PairedTriePattern<IN, NUM>,
op: NumOps<NUM>): NumUnitPattern<IN, NUM>(number, unit, op) {
override val map get() = unit.map
}
| 1 | Kotlin | 0 | 11 | 37599098dc9aafef7b509536e6d17ceca370d6cf | 2,852 | ParserKt | MIT License |
src/day04/Day04.kt | Puju2496 | 576,611,911 | false | {"Kotlin": 46156} | package day04
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val input = readInput("src/day04", "Day04")
println("Part1")
part1(input)
println("Part2")
part2(input)
}
private fun part1(inputs: List<String>) {
var sum = 0
inputs.forEach {
val pair = it.split(",", "-", limit = 4).map {
it.toInt()
}
if ((pair[0] <= pair[2] && pair[1] >= pair[3]) || (pair[0] >= pair[2] && pair[1] <= pair[3])) {
sum += 1
}
println("${inputs.indexOf(it)} - $pair - $sum")
}
}
private fun part2(inputs: List<String>) {
var sum = 0
inputs.forEach {
val pair = it.split(",", "-", limit = 4).map {
it.toInt()
}
sum += when {
pair[2] <= pair[1] && pair[1] <= pair[3] -> 1
pair[0] <= pair[2] && pair[2] <= pair[1] -> 1
pair[0] <= pair[3] && pair[3] <= pair[1] -> 1
pair[2] <= pair[0] && pair[0] <= pair[3] -> 1
else -> 0
}
println("${inputs.indexOf(it)} - $pair - $sum")
}
} | 0 | Kotlin | 0 | 0 | e04f89c67f6170441651a1fe2bd1f2448a2cf64e | 1,131 | advent-of-code-2022 | Apache License 2.0 |
src/Day01.kt | SebastianHelzer | 573,026,636 | false | {"Kotlin": 27111} | fun main() {
fun getTotalCalories(input: List<String>): List<Int> {
val indicesOfSpaces = input.mapIndexedNotNull { index, value ->
if (value.isBlank()) index else null
} + input.lastIndex
val calories = indicesOfSpaces.windowed(2, 1) { indices ->
input
.subList(indices.first(), indices.last() + 1)
.mapNotNull { it.toIntOrNull() }
}
return calories.map { it.sum() }
}
fun part1(input: List<String>): Int = getTotalCalories(input).max()
fun part2(input: List<String>): Int = getTotalCalories(input)
.sorted()
.takeLast(3)
.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e48757626eb2fb5286fa1c59960acd4582432700 | 952 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/solutions/day11/Day11.kt | Dr-Horv | 112,381,975 | false | null |
package solutions.day11
import solutions.Solver
data class Position(val x: Int, val y: Int)
enum class Direction {
N,
NE,
SE,
S,
SW,
NW
}
fun String.toDirection(): Direction = when(this) {
"n" -> Direction.N
"ne" -> Direction.NE
"se" -> Direction.SE
"s" -> Direction.S
"sw" -> Direction.SW
"nw" -> Direction.NW
else -> throw RuntimeException("Unparsable direction")
}
fun Position.go(dir: Direction) : Position = when(dir){
Direction.N -> Position(x, y + 2)
Direction.NE -> Position(x+1, y+1)
Direction.SE -> Position(x+1, y-1)
Direction.S -> Position(x, y-2)
Direction.SW -> Position(x-1, y-1)
Direction.NW -> Position(x-1, y+1)
}
fun Position.distance(): Int {
val xPos = Math.abs(x)
val yPos = Math.abs(y)
return (yPos + xPos)/2
}
class Day11: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val map = input.first()
.split(",")
.map(String::trim)
.map(String::toDirection)
var curr = Position(0,0)
var furthest = curr
map.forEach {
curr = curr.go(it)
if(partTwo && curr.distance() > furthest.distance()) {
furthest = curr
}
}
return if(!partTwo) {
(curr.distance()).toString()
} else {
(furthest.distance()).toString()
}
}
}
| 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 1,457 | Advent-of-Code-2017 | MIT License |
src/main/kotlin/com/ginsberg/advent2020/Day18.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 18 - Operation Order
* Problem Description: http://adventofcode.com/2020/day/18
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day18/
*/
package com.ginsberg.advent2020
class Day18(input: List<String>) {
private val equations = input.map { it.replace(" ", "") }
fun solvePart1(): Long =
equations.sumOf { solvePart1(it.iterator()) }
fun solvePart2(): Long =
equations.sumOf { solvePart2(it.iterator()) }
private fun solvePart1(equation: CharIterator): Long {
val numbers = mutableListOf<Long>()
var op = '+'
while (equation.hasNext()) {
when (val next = equation.nextChar()) {
'(' -> numbers += solvePart1(equation)
')' -> break
in setOf('+', '*') -> op = next
else -> numbers += next.asLong()
}
if (numbers.size == 2) {
val a = numbers.removeLast()
val b = numbers.removeLast()
numbers += if (op == '+') a + b else a * b
}
}
return numbers.first()
}
private fun solvePart2(equation: CharIterator): Long {
val multiplyThese = mutableListOf<Long>()
var added = 0L
while (equation.hasNext()) {
val next = equation.nextChar()
when {
next == '(' -> added += solvePart2(equation)
next == ')' -> break
next == '*' -> {
multiplyThese += added
added = 0L
}
next.isDigit() -> added += next.asLong()
}
}
return (multiplyThese + added).product()
}
}
| 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 1,796 | advent-2020-kotlin | Apache License 2.0 |
leetcode-75-kotlin/src/main/kotlin/MaximumAverageSubarrayI.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* You are given an integer array nums consisting of n elements, and an integer k.
*
* Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value.
* Any answer with a calculation error less than 10-5 will be accepted.
*
*
*
* Example 1:
*
* Input: nums = [1,12,-5,-6,50,3], k = 4
* Output: 12.75000
* Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
* Example 2:
*
* Input: nums = [5], k = 1
* Output: 5.00000
*
*
* Constraints:
*
* n == nums.length
* 1 <= k <= n <= 10^5
* -10^4 <= nums[i] <= 10^4
* @see <a href="https://leetcode.com/problems/maximum-average-subarray-i/">LeetCode</a>
*/
fun findMaxAverage(nums: IntArray, k: Int): Double {
var currentSum: Double = 0.0
var startIndex = 0
var endIndex = k
for (index in 0 until endIndex) {
currentSum += nums[index]
}
var maxAverage = currentSum / k
while (endIndex < nums.size) {
currentSum += nums[endIndex++]
currentSum -= nums[startIndex++]
maxAverage = maxOf(maxAverage, currentSum / k)
}
return maxAverage
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,136 | leetcode-75 | Apache License 2.0 |
src/Day12.kt | MerickBao | 572,842,983 | false | {"Kotlin": 28200} | import java.util.LinkedList
import kotlin.math.min
fun main() {
fun bfs(grid: Array<CharArray>, sx: Int, sy: Int, ex: Int, ey: Int): Int {
var ans = 0
val n = grid.size
val m = grid[0].size
val seen = Array(n){ BooleanArray(m) }
seen[sx][sy] = true
val dx = listOf(-1, 1, 0, 0)
val dy = listOf(0, 0, -1, 1)
val q = LinkedList<List<Int>>()
q.offer(listOf(sx, sy))
while (!q.isEmpty()) {
var size = q.size
while (size-- > 0) {
val now = q.poll()
for (i in 0 until 4) {
val x = now[0] + dx[i]
val y = now[1] + dy[i]
if (x < 0 || x >= n || y < 0 || y >= m) continue
if (seen[x][y] || grid[x][y] - grid[now[0]][now[1]] > 1) continue
if (x == ex && y == ey) return ans + 1
seen[x][y] = true
q.offer(listOf(x, y))
}
}
ans++
}
return 1000000000
}
fun game(input: List<String>) {
var sx = 0
var sy = 0
var ex = 0
var ey = 0
val starters: ArrayList<List<Int>> = arrayListOf()
val grid = Array(input.size) { CharArray(input[0].length) }
for (i in input.indices) {
grid[i] = input[i].toCharArray()
for (j in 0 until input[0].length) {
if (input[i][j] == 'S') {
sx = i
sy = j
grid[i][j] = 'a'
}
if (input[i][j] == 'E') {
ex = i
ey = j
grid[i][j] = 'z'
}
if (grid[i][j] == 'a') starters.add(listOf(i, j))
}
}
println(bfs(grid, sx, sy, ex, ey))
var ans = 1000000000
for (start in starters) {
ans = min(ans, bfs(grid, start[0], start[1], ex, ey))
}
println(ans)
}
val input = readInput("Day12")
game(input)
} | 0 | Kotlin | 0 | 0 | 70a4a52aa5164f541a8dd544c2e3231436410f4b | 2,105 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/de/dikodam/calendar/Day09.kt | dikodam | 433,719,746 | false | {"Kotlin": 51383} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.Coordinates2D
import de.dikodam.executeTasks
import java.util.*
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day09().executeTasks()
}
class Day09 : AbstractDay() {
val input: Map<Coordinates2D, Int> = readInputLines()
/*
val input: Map<Coordinates2D, Int> = """2199943210
3987894921
9856789892
8767896789
9899965678""".trim().lines()
*/
.flatMapIndexed { y, line ->
line.asSequence()
.mapIndexed { x, i -> Coordinates2D(x, y) to i.digitToInt() }
}
.toMap()
override fun task1(): String {
return input.map { (coord, i) -> i to getNeighbors(coord, input) }
.filter { (spot, neighbors) -> neighbors.all { n -> n > spot } }
.map { (spot, _) -> spot + 1 }
.sumOf { it }
.toString()
}
fun getNeighbors(point: Coordinates2D, map: Map<Coordinates2D, Int>): List<Int> {
val up = point.copy(x = point.x - 1)
val down = point.copy(x = point.x + 1)
val left = point.copy(y = point.y - 1)
val right = point.copy(y = point.y + 1)
return listOf(up, down, left, right)
.mapNotNull { map[it] }
}
fun getNeighborsCoords(point: Coordinates2D, map: Map<Coordinates2D, Int>): List<Coordinates2D> {
val up = point.copy(x = point.x - 1)
val down = point.copy(x = point.x + 1)
val left = point.copy(y = point.y - 1)
val right = point.copy(y = point.y + 1)
return listOf(up, down, left, right)
.filter { spot -> spot in map.keys }
}
override fun task2(): String {
// identify basins by breadth first search
// for each point,
// if registered, skip
// if not registered, register
// if ==9 skip else start new basin:
// getNeighbors
// filterNonRegistered Neighbors
// register each != 9 as part current basin
// flatMap each != 9 neighbor to its neighbors
val basins = mutableListOf<Basin>()
val visitedPoints = mutableSetOf<Coordinates2D>()
for (point in input.keys) {
if (point in visitedPoints) continue
visitedPoints += point
if (input[point] == 9) continue
val currentBasin = mutableSetOf<Coordinates2D>()
currentBasin += point
val stack = ArrayDeque<Coordinates2D>()
stack += getNeighborsCoords(point, input)
while (stack.isNotEmpty()) {
val currentPoint = stack.remove()
if (currentPoint in visitedPoints) continue
visitedPoints += currentPoint
if (input[currentPoint] == 9) continue
currentBasin += currentPoint
stack += getNeighborsCoords(currentPoint, input)
}
basins.add(currentBasin)
}
val result = basins.map { it.size }
.sortedDescending()
.take(3)
.reduce(Int::times)
return "$result"
}
}
typealias Basin = Set<Coordinates2D>
| 0 | Kotlin | 0 | 1 | 4934242280cebe5f56ca8d7dcf46a43f5f75a2a2 | 3,175 | aoc-2021 | MIT License |
src/Day08.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} | fun main() {
fun part1(input: List<String>): Int {
val grid = input
.map { it.chars().map { c -> c - 48 }.toArray() }.toTypedArray()
val width = grid[0].size
val height = grid.size
var visibleTrees = width*2 + height*2 - 4
for (row in 1..< grid.lastIndex) {
for (col in 1..< grid[row].lastIndex) {
var visible = 4
left@for (beforeCol in 0..<col) {
if (grid[row][beforeCol] >= grid[row][col]) {
visible--
break@left
}
}
right@for (afterCol in col+1 .. grid[row].lastIndex) {
if (grid[row][afterCol] >= grid[row][col]) {
visible--
break@right
}
}
top@for (beforeRow in 0..<row) {
if (grid[beforeRow][col] >= grid[row][col]) {
visible--
break@top
}
}
bottom@for (afterRow in row+1 .. grid.lastIndex) {
if (grid[afterRow][col] >= grid[row][col]) {
visible--
break@bottom
}
}
if (visible > 0) {
visibleTrees++
}
}
}
return visibleTrees
}
fun part2(input: List<String>): Int {
val grid = input
.map { it.chars().map { c -> c - 48 }.toArray() }.toTypedArray()
val width = grid[0].size
val height = grid.size
val scenicScore = Array(height) { IntArray(width) }
for (row in 1..< grid.lastIndex) {
for (col in 1..< grid[row].lastIndex) {
var (l,r,t,b) = arrayOf(0, 0, 0, 0)
left@for (beforeCol in col-1 downTo 0) {
l++
if (grid[row][beforeCol] >= grid[row][col]) {
break@left
}
}
right@for (afterCol in col+1 .. grid[row].lastIndex) {
r++
if (grid[row][afterCol] >= grid[row][col]) {
break@right
}
}
top@for (beforeRow in row-1 downTo 0) {
t++
if (grid[beforeRow][col] >= grid[row][col]) {
break@top
}
}
bottom@for (afterRow in row+1 .. grid.lastIndex) {
b++
if (grid[afterRow][col] >= grid[row][col]) {
break@bottom
}
}
scenicScore[row][col] = l*r*b*t
}
}
return scenicScore.maxOf { it.max() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 3,214 | aoc-2022 | Apache License 2.0 |
src/main/algorithms/searching/IceCreamParlour.kt | vamsitallapudi | 119,534,182 | false | {"Java": 24691, "Kotlin": 20452} | package main.algorithms.searching
import java.util.*
import kotlin.collections.*
import kotlin.ranges.*
import kotlin.text.*
// Complete the whatFlavors function below.
fun whatFlavors(menu: Array<Int>, money: Int): Array<Int>? {
val sortedMenu = menu.clone()
Arrays.sort(sortedMenu)
for ( i in 0 until sortedMenu.size) {
val compliment = money - sortedMenu[i]
val location = Arrays.binarySearch(sortedMenu, i+1, sortedMenu.size, compliment)
if(location >=0 && location < sortedMenu.size && sortedMenu[location] == compliment) {
return getIndicesFromValue(menu, sortedMenu[i], compliment)
}
}
return null
}
fun getIndicesFromValue(menu: Array<Int>, value1: Int, value2: Int): Array<Int> {
val index1 = indexOf(menu,value1, -1)
val index2 = indexOf(menu,value2,index1)
val indices:Array<Int> = Array(2){0}
indices[0] = Math.min(index1,index2)
indices[1] = Math.max(index1,index2)
return indices
}
fun indexOf(array:Array<Int>, value:Int, excludeIndex:Int) :Int{
for( i in 0 until array.size) {
if(array[i] == value && i != excludeIndex) {
return i
}
}
return -1
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val t = scan.nextLine().trim().toInt()
for (tItr in 1..t) {
val money = scan.nextLine().trim().toInt()
val n = scan.nextLine().trim().toInt()
val cost = scan.nextLine().trim().split(" ").map{ it.trim().toInt() }.toTypedArray()
(whatFlavors(cost,money)?.map { print("${it+1} ") })
println()
}
}
| 0 | Java | 1 | 1 | 9349fa7488fcabcb9c58ce5852d97996a9c4efd3 | 1,619 | HackerEarth | Apache License 2.0 |
src/main/kotlin/codes/jakob/aoc/solution/Day10.kt | The-Self-Taught-Software-Engineer | 433,875,929 | false | {"Kotlin": 56277} | package codes.jakob.aoc.solution
import java.util.*
object Day10 : Solution() {
override fun solvePart1(input: String): Any {
return parseInput(input)
.mapNotNull { characters: List<Character> ->
try {
match(characters)
null
} catch (exception: IllegalCharacterException) {
exception.actual
}
}
.countBy { it }
.map { (character: Character, count: Int) -> Scorer.calculateScoreForMismatch(character) * count }
.sum()
}
override fun solvePart2(input: String): Any {
return parseInput(input)
.mapNotNull { characters: List<Character> ->
try {
match(characters)
} catch (exception: IllegalCharacterException) {
null
}
}
.filterNot { it.matching }
.map { matchResult: MatchResult ->
matchResult.missing.fold(0L) { accumulator: Long, character: Character ->
(accumulator * 5) + Scorer.calculateScoreForCompletion(character)
}
}
.sorted()
.middleOrNull()!!
}
private fun match(characters: List<Character>): MatchResult {
val stack: Stack<Character> = Stack()
for (current: Character in characters) {
if (current.type == Character.Type.OPEN) {
stack.push(current)
} else {
val matchingCurrent: Character = current.opposite()
val top: Character? = stack.peekOrNull()
if (matchingCurrent == top) {
stack.pop()
} else {
throw IllegalCharacterException(top?.opposite(), current)
}
}
}
val missing: List<Character> = stack.map { it.opposite() }.reversed()
return MatchResult(characters, stack.isEmpty(), missing)
}
private fun parseInput(input: String): List<List<Character>> {
return input
.splitMultiline()
.map { line ->
line
.split("")
.filter { it.isNotBlank() }
.map { it.toSingleChar() }
.map { Character.fromChar(it) ?: error("Character $it not supported") }
}
}
object Scorer {
private val MISMATCH_SCORES: Map<Character, Int> = mapOf(
Character.CLOSE_PARENTHESES to 3,
Character.CLOSE_BRACKET to 57,
Character.CLOSE_BRACE to 1197,
Character.CLOSE_ANGLE to 25137,
)
private val COMPLETION_SCORES: Map<Character, Int> = mapOf(
Character.CLOSE_PARENTHESES to 1,
Character.CLOSE_BRACKET to 2,
Character.CLOSE_BRACE to 3,
Character.CLOSE_ANGLE to 4,
)
fun calculateScoreForMismatch(character: Character): Int {
require(character.type == Character.Type.CLOSE) { "Only closing characters are scored" }
return MISMATCH_SCORES[character] ?: error("Character $character not tracked")
}
fun calculateScoreForCompletion(character: Character): Int {
require(character.type == Character.Type.CLOSE) { "Only closing characters are scored" }
return COMPLETION_SCORES[character] ?: error("Character $character not tracked")
}
}
enum class Character(val type: Type, val char: Char) {
OPEN_PARENTHESES(Type.OPEN, '(') {
override fun opposite(): Character = CLOSE_PARENTHESES
},
CLOSE_PARENTHESES(Type.CLOSE, ')') {
override fun opposite(): Character = OPEN_PARENTHESES
},
OPEN_BRACKET(Type.OPEN, '[') {
override fun opposite(): Character = CLOSE_BRACKET
},
CLOSE_BRACKET(Type.CLOSE, ']') {
override fun opposite(): Character = OPEN_BRACKET
},
OPEN_BRACE(Type.OPEN, '{') {
override fun opposite(): Character = CLOSE_BRACE
},
CLOSE_BRACE(Type.CLOSE, '}') {
override fun opposite(): Character = OPEN_BRACE
},
OPEN_ANGLE(Type.OPEN, '<') {
override fun opposite(): Character = CLOSE_ANGLE
},
CLOSE_ANGLE(Type.CLOSE, '>') {
override fun opposite(): Character = OPEN_ANGLE
};
abstract fun opposite(): Character
override fun toString(): String = char.toString()
enum class Type {
OPEN,
CLOSE;
}
companion object {
fun fromChar(char: Char): Character? {
return values().find { it.char == char }
}
}
}
data class MatchResult(
val characters: List<Character>,
val matching: Boolean,
val missing: List<Character>,
)
class IllegalCharacterException(
val expected: Character?,
val actual: Character,
) : RuntimeException("Expected $expected, but found $actual instead.")
}
fun main() {
Day10.solve()
}
| 0 | Kotlin | 0 | 6 | d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c | 5,200 | advent-of-code-2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MergeIntervals.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Stack
fun interface MergeIntervals {
operator fun invoke(intervals: Array<IntArray>): Array<IntArray>
}
class MergeIntervalsConnectedComponents : MergeIntervals {
private var graph: MutableMap<IntArray, MutableList<IntArray>> = HashMap()
private var nodesInComp: MutableMap<Int, MutableList<IntArray>> = HashMap()
private var visited: MutableSet<IntArray> = HashSet()
override operator fun invoke(intervals: Array<IntArray>): Array<IntArray> {
return merge(intervals)
}
// return whether two intervals overlap (inclusive)
private fun overlap(a: IntArray, b: IntArray): Boolean {
return a[0] <= b[1] && b[0] <= a[1]
}
// build a graph where an undirected edge between intervals u and v exists
// iff u and v overlap.
private fun buildGraph(intervals: Array<IntArray>) {
for (interval in intervals) {
graph[interval] = LinkedList<IntArray>()
}
for (interval1 in intervals) {
for (interval2 in intervals) {
if (overlap(interval1, interval2)) {
graph[interval1]?.add(interval2)
graph[interval2]?.add(interval1)
}
}
}
}
// merges all of the nodes in this connected component into one interval.
private fun mergeNodes(nodes: List<IntArray>): IntArray {
var minStart = nodes[0][0]
for (node in nodes) {
minStart = minStart.coerceAtMost(node[0])
}
var maxEnd = nodes[0][1]
for (node in nodes) {
maxEnd = maxEnd.coerceAtLeast(node[1])
}
return intArrayOf(minStart, maxEnd)
}
// use depth-first search to mark all nodes in the same connected component
// with the same integer.
private fun markComponentDFS(start: IntArray, compNumber: Int) {
val stack: Stack<IntArray> = Stack()
stack.add(start)
while (stack.isNotEmpty()) {
val node: IntArray = stack.pop()
if (!visited.contains(node)) {
visited.add(node)
if (nodesInComp[compNumber] == null) {
nodesInComp[compNumber] = LinkedList()
}
nodesInComp[compNumber]?.add(node)
graph[node]?.let {
for (child in it) {
stack.add(child)
}
}
}
}
}
// gets the connected components of the interval overlap graph.
private fun buildComponents(intervals: Array<IntArray>) {
var compNumber = 0
for (interval in intervals) {
if (!visited.contains(interval)) {
markComponentDFS(interval, compNumber)
compNumber++
}
}
}
private fun merge(intervals: Array<IntArray>): Array<IntArray> {
buildGraph(intervals)
buildComponents(intervals)
// for each component, merge all intervals into one interval.
val merged: MutableList<IntArray> = LinkedList()
for (element in nodesInComp) {
merged.add(mergeNodes(element.value))
}
return merged.toTypedArray()
}
}
class MergeIntervalsSorting : MergeIntervals {
override operator fun invoke(intervals: Array<IntArray>): Array<IntArray> {
val i = intervals.toList().sortedWith(IntervalComparator())
val merged = LinkedList<IntArray>()
for (interval in i) {
// if the list of merged intervals is empty or if the current
// interval does not overlap with the previous, simply append it.
if (merged.isEmpty() || merged.last[1] < interval[0]) {
merged.add(interval)
} else {
merged.last[1] = merged.last[1].coerceAtLeast(interval[1])
}
}
return merged.toTypedArray()
}
private class IntervalComparator : Comparator<IntArray?> {
override fun compare(a: IntArray?, b: IntArray?): Int {
if (a == null || b == null) return -1
return if (a[0] < b[0]) -1 else if (a[0] == b[0]) 0 else 1
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,861 | kotlab | Apache License 2.0 |
src/Day08.kt | SnyderConsulting | 573,040,913 | false | {"Kotlin": 46459} | fun main() {
fun part1(input: List<String>): Int {
val treeGrid = fillTreeGrid(input)
checkRtl(input, treeGrid)
checkLtr(input, treeGrid)
checkTtb(input, treeGrid)
checkBtt(input, treeGrid)
return treeGrid.flatten().count { it }
}
fun part2(input: List<String>): Int {
val treeGrid = fillTreeGridForViewing(input)
checkRtlForViewing(input, treeGrid)
checkLtrForViewing(input, treeGrid)
checkTtbForViewing(input, treeGrid)
checkBttForViewing(input, treeGrid)
return treeGrid.flatten().maxOf { it.getViewingScore() }
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
//region part1
fun fillTreeGrid(input: List<String>): List<MutableList<Boolean>> {
val treeGrid = mutableListOf<MutableList<Boolean>>()
input.forEach { line ->
treeGrid.add(mutableListOf())
repeat(line.length) {
treeGrid.last().add(false)
}
}
return treeGrid
}
fun checkLtr(input: List<String>, treeGrid: List<MutableList<Boolean>>) {
input.forEachIndexed { y, line ->
var tallestTree = -1
line.forEachIndexed { x, char ->
if (char.toString().toInt() > tallestTree) {
tallestTree = char.toString().toInt()
treeGrid[y][x] = true
}
}
}
}
fun checkRtl(input: List<String>, treeGrid: List<MutableList<Boolean>>) {
input.forEachIndexed { y, line ->
var tallestTree = -1
line.reversed().forEachIndexed { x, char ->
if (char.toString().toInt() > tallestTree) {
tallestTree = char.toString().toInt()
treeGrid[y][line.length - 1 - x] = true
}
}
}
}
fun checkTtb(input: List<String>, treeGrid: List<MutableList<Boolean>>) {
repeat(input.first().length) { x ->
var tallestTree = -1
input.forEachIndexed { y, line ->
if (line[x].toString().toInt() > tallestTree) {
tallestTree = line[x].toString().toInt()
treeGrid[y][x] = true
}
}
}
}
fun checkBtt(input: List<String>, treeGrid: List<MutableList<Boolean>>) {
repeat(input.first().length) { x ->
var tallestTree = -1
input.reversed().forEachIndexed { y, line ->
if (line[x].toString().toInt() > tallestTree) {
tallestTree = line[x].toString().toInt()
treeGrid[input.size - 1 - y][x] = true
}
}
}
}
//endregion
//region part2
fun fillTreeGridForViewing(input: List<String>): List<MutableList<ViewingDistance>> {
val treeGrid = mutableListOf<MutableList<ViewingDistance>>()
input.forEach { line ->
treeGrid.add(mutableListOf())
repeat(line.length) {
treeGrid.last().add(ViewingDistance())
}
}
return treeGrid
}
fun checkLtrForViewing(input: List<String>, treeGrid: List<MutableList<ViewingDistance>>) {
input.forEachIndexed { y, line ->
val trees = mutableListOf<Int>()
line.forEachIndexed { x, char ->
val height = char.toString().toInt()
treeGrid[y][x].apply {
this.left = trees.toList().reversed()
this.height = height
}
trees.add(height)
}
}
}
fun checkRtlForViewing(input: List<String>, treeGrid: List<MutableList<ViewingDistance>>) {
input.forEachIndexed { y, line ->
val trees = mutableListOf<Int>()
line.reversed().forEachIndexed { x, char ->
val height = char.toString().toInt()
treeGrid[y][line.length - 1 - x].apply {
this.right = trees.toList().reversed()
this.height = height
}
trees.add(height)
}
}
}
fun checkTtbForViewing(input: List<String>, treeGrid: List<MutableList<ViewingDistance>>) {
repeat(input.first().length) { x ->
val trees = mutableListOf<Int>()
input.forEachIndexed { y, line ->
val height = line[x].toString().toInt()
treeGrid[y][x].apply {
this.top = trees.toList().reversed()
this.height = height
}
trees.add(height)
}
}
}
fun checkBttForViewing(input: List<String>, treeGrid: List<MutableList<ViewingDistance>>) {
repeat(input.first().length) { x ->
val trees = mutableListOf<Int>()
input.reversed().forEachIndexed { y, line ->
val height = line[x].toString().toInt()
treeGrid[input.size - 1 - y][x].apply {
this.bottom = trees.toList().reversed()
this.height = height
}
trees.add(height)
}
}
}
data class ViewingDistance(
var height: Int = 0,
var top: List<Int> = emptyList(),
var bottom: List<Int> = emptyList(),
var left: List<Int> = emptyList(),
var right: List<Int> = emptyList()
) {
fun getViewingScore(): Int {
val topVisible = top.getViewingScore(height)
val bottomVisible = bottom.getViewingScore(height)
val leftVisible = left.getViewingScore(height)
val rightVisible = right.getViewingScore(height)
return topVisible * bottomVisible * leftVisible * rightVisible
}
}
fun List<Int>.getViewingScore(height: Int): Int {
return indexOfFirst { it >= height }.let {
if (it == -1) {
this
} else {
toMutableList().dropLast(size - it - 1)
}
}.size
}
//endregion | 0 | Kotlin | 0 | 0 | ee8806b1b4916fe0b3d576b37269c7e76712a921 | 5,614 | Advent-Of-Code-2022 | Apache License 2.0 |
src/main/kotlin/Day7.kt | noamfreeman | 572,834,940 | false | {"Kotlin": 30332} | import java.lang.Integer.max
private val exampleInput = """
${'$'} cd /
${'$'} ls
dir a
14848514 b.txt
8504156 c.dat
dir d
${'$'} cd a
${'$'} ls
dir e
29116 f
2557 g
62596 h.lst
${'$'} cd e
${'$'} ls
584 i
${'$'} cd ..
${'$'} cd ..
${'$'} cd d
${'$'} ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
""".trimIndent()
private val exampleFileSystem = """
- / (dir)
- a (dir)
- e (dir)
- i (file, size=584)
- f (file, size=29116)
- g (file, size=2557)
- h.lst (file, size=62596)
- b.txt (file, size=14848514)
- c.dat (file, size=8504156)
- d (dir)
- j (file, size=4060174)
- d.log (file, size=8033020)
- d.ext (file, size=5626152)
- k (file, size=7214296)
""".trimIndent()
fun main() {
println("day7")
println()
println("part1")
assertEqualString(parseFileSystem(exampleInput).repr(), exampleFileSystem)
assertEquals(part1(exampleInput), 95437)
println(part1(readInputFile("day7_input.txt")))
println()
println("part2")
assertEquals(part2(exampleInput), 24_933_642)
println(part2(readInputFile("day7_input.txt")))
}
private fun part1(input: String): Int {
val fileSystem = parseFileSystem(input)
return fileSystem.getAllDirs().filter {
it.totalSize() < 100_000
}.sumOf { it.totalSize() }
}
private fun part2(input: String): Int {
val fileSystem = parseFileSystem(input)
val totalSize = fileSystem.totalSize()
val availableSpace = (70_000_000 - totalSize)
val moreSpaceNeeded = max(30_000_000 - availableSpace, 0)
return fileSystem.getAllDirs()
.map {it.totalSize() }
.filter {
it > moreSpaceNeeded
}.minOf { it }
}
private fun parseFileSystem(input: String): FileSystem {
val fileSystem = FileSystem()
input.lines().forEach { line ->
if (line.startsWith("$")) {
if (line == "% ls") {
// do nothing
} else if (line.startsWith("$ cd ")) {
val dirname = line.drop("$ cd ".length)
fileSystem.moveTo(dirname)
}
} else {
if (line.startsWith("dir ")) {
val dirname = line.drop("dir ".length)
fileSystem.addDir(dirname)
} else {
val (number, name) = line.split(" ")
fileSystem.addFile(name, number.toInt())
}
}
}
return fileSystem
}
private class FileSystem {
private var root = Dir("/", mutableListOf())
private var currentPath: List<Dir> = listOf(root)
private fun currentDir() = currentPath.last()
fun addDir(name: String) {
currentDir().addChild(name)
}
fun totalSize() = root.totalSize()
fun addFile(name: String, size: Int) {
currentDir().children.add(File(name, size))
}
fun moveTo(path: String) {
when (path) {
"/" -> currentPath = listOf(root)
".." -> currentPath = currentPath.dropLast(1)
else -> {
val dir = currentDir().addChild(path)
currentPath = currentPath + dir
}
}
}
fun repr(): String {
return root.repr()
}
fun getAllDirs(): Sequence<Dir> {
return sequence {
val current = mutableListOf(root)
suspend fun SequenceScope<Dir>.yieldNext() {
val dir = current.removeAt(0)
yield(dir)
current.addAll(dir.children.filterIsInstance<Dir>())
}
while (current.isNotEmpty()) {
yieldNext()
}
}
}
}
private sealed interface Entry {
fun repr(): String
}
private class File(val name: String, val size: Int) : Entry {
override fun repr(): String = toString() + "\n"
override fun toString(): String = "- $name (file, size=$size)"
}
private class Dir(val name: String, val children: MutableList<Entry>) : Entry {
private fun findDir(path: String): Dir? {
return children.filterIsInstance<Dir>().find {
it.name == path
}
}
fun addChild(path: String): Dir {
val existingDir = findDir(path)
if (existingDir != null) return existingDir
val newDir = Dir(path, mutableListOf())
children.add(newDir)
return newDir
}
override fun toString(): String = "- $name (dir)"
override fun repr(): String {
val children = children.joinToString("") {
it.repr()
}.indent()
return "$this\n$children"
}
}
private fun Entry.totalSize(): Int = when(this) {
is File -> this.size
is Dir -> this.children.sumOf { it.totalSize() }
}
private fun String.indent(): String {
return lines().filter { it.isNotBlank() }.joinToString("") { " $it\n" }
} | 0 | Kotlin | 0 | 0 | 1751869e237afa3b8466b213dd095f051ac49bef | 4,890 | advent_of_code_2022 | MIT License |
src/main/kotlin/dp/LFBS.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
// find the length of the longest CONTIGUOUS SUBSTRING that appears both
// forward and backward in T[1..n]
fun main(args: Array<String>) {
val Ts = arrayOf(
"ALGORITHM", // 0
"RECURSION", // "R ... R" -> 1
"REDIVIDE", // "EDI ... IDE" -> 3
"DYNAMICPROGRAMMINGMANYTIMES" // "YNAM ... MANY" -> 4
)
Ts
.map { it.toCharOneArray() }
.forEach { println(it.lfbs()) }
}
fun OneArray<Char>.lfbs(): Int {
val T = this
val n = T.size
if (n < 2) {
return 0
}
// dp(i, j) = len of substring starting @ i and ending @ j
// memoization structure: 2d array dp[1..n, 1..n] : dp[i, j] = dp(i, j)
val dp = OneArray(n) { OneArray(n) { 0 } }
// space complexity: O(n^2)
// we want max{ dp(i, j) }
var max = 0
// dp(i, j) = 0 if T[i] != T[j] or i >= j
// dp(i, j) = 1 + dp(i + 1, j - 1) o/w
// dependency: dp(i, j) depends on dp(i + 1, j - 1) that is entry to the lower left
// evaluation order: outer loop for i from n - 1 down to 1 (bottom up)
for (i in n - 1 downTo 1) {
// inner loop for j from i + 1..n
for (j in i + 1..n) {
dp[i, j] = if (T[i] != T[j]) {
0
} else {
1 + dp[i + 1, j - 1]
}
max = max(max, dp[i, j])
}
}
// time complexity: O(n^2)
return max
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,244 | AlgoKt | MIT License |
src/main/kotlin/g0701_0800/s0787_cheapest_flights_within_k_stops/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0701_0800.s0787_cheapest_flights_within_k_stops
// #Medium #Dynamic_Programming #Depth_First_Search #Breadth_First_Search #Heap_Priority_Queue
// #Graph #Shortest_Path #2023_03_13_Time_185_ms_(99.20%)_Space_36.6_MB_(89.64%)
class Solution {
fun findCheapestPrice(n: Int, flights: Array<IntArray>, src: Int, dst: Int, k: Int): Int {
// k + 2 becase there are total of k(intermediate stops) + 1(src) + 1(dst)
// dp[i][j] = cost to reach j using atmost i edges from src
val dp = Array(k + 2) { IntArray(n) }
for (row in dp) {
row.fill(Int.MAX_VALUE)
}
// cost to reach src is always 0
for (i in 0..k + 1) {
dp[i][src] = 0
}
// k+1 because k stops + dst
for (i in 1..k + 1) {
for (flight in flights) {
val srcAirport = flight[0]
val destAirport = flight[1]
val cost = flight[2]
// if cost to reach srcAirport in i - 1 steps is already found out then
// the cost to reach destAirport will be min(cost to reach destAirport computed
// already from some other srcAirport OR cost to reach srcAirport in i - 1 steps +
// the cost to reach destAirport from srcAirport)
if (dp[i - 1][srcAirport] != Int.MAX_VALUE) {
dp[i][destAirport] = dp[i][destAirport].coerceAtMost(dp[i - 1][srcAirport] + cost)
}
}
}
// checking for dp[k + 1][dst] because there are 'k + 2' airports in a path and distance
// covered between 'k + 2' airports is 'k + 1'
return if (dp[k + 1][dst] == Int.MAX_VALUE) -1 else dp[k + 1][dst]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,744 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/Day04.kt | joostbaas | 573,096,671 | false | {"Kotlin": 45397} | typealias AssignedSections = IntRange
fun readIntoPairOfSectionAssignments(line: String): Pair<AssignedSections, AssignedSections> {
val (first, second) = line.split(',').map { range ->
val (begin, end) = range.split('-').map { it.toInt() }
(begin..end)
}
return first to second
}
fun Pair<AssignedSections, AssignedSections>.haveOverlap(): Boolean =
first.any { second.contains(it) }
fun oneFullyContainsOther(assignedSectionsPair: Pair<AssignedSections, AssignedSections>): Boolean {
infix fun AssignedSections.fullyContains(other: AssignedSections) = other.all { this.contains(it) }
val (first, second) = assignedSectionsPair
return first fullyContains second || second fullyContains first
}
fun day04Part1(input: List<String>): Int =
input.map(::readIntoPairOfSectionAssignments)
.count(::oneFullyContainsOther)
fun day04Part2(input: List<String>): Int =
input.map(::readIntoPairOfSectionAssignments)
.count { it.haveOverlap() }
| 0 | Kotlin | 0 | 0 | 8d4e3c87f6f2e34002b6dbc89c377f5a0860f571 | 1,006 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day12.kt | tobiasae | 434,034,540 | false | {"Kotlin": 72901} | class Day12 : Solvable("12") {
override fun solveA(input: List<String>): String {
return countWays(getMap(input), setOf("start"), "start").toString()
}
override fun solveB(input: List<String>): String {
return countWaysDouble(getMap(input), setOf("start"), false, "start").toString()
}
private fun countWays(
map: Map<String, MutableSet<String>>,
visited: Set<String>,
current: String
): Int {
var count = 0
map[current]?.forEach {
if (it == "end") count++
else if (it.first().isUpperCase() || !visited.contains(it))
count += countWays(map, setOf(current) + visited, it)
}
return count
}
private fun countWaysDouble(
map: Map<String, MutableSet<String>>,
visited: Set<String>,
doubleTaken: Boolean,
current: String
): Int {
var count = 0
map[current]?.forEach {
if (it == "end") count++
else if (it.first().isLowerCase() && visited.contains(it)) {
if (!doubleTaken && it != "start") {
count += countWaysDouble(map, visited, true, it)
}
} else count += countWaysDouble(map, visited + setOf(it), doubleTaken, it)
}
return count
}
fun getMap(input: List<String>): Map<String, MutableSet<String>> {
val map = mutableMapOf<String, MutableSet<String>>()
input.forEach {
val (a, b) = it.split("-")
map[a] = (map[a] ?: mutableSetOf()).also { it.add(b) }
map[b] = (map[b] ?: mutableSetOf()).also { it.add(a) }
}
return map
}
}
| 0 | Kotlin | 0 | 0 | 16233aa7c4820db072f35e7b08213d0bd3a5be69 | 1,735 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/day02/Day02.kt | sophiepoole | 573,708,897 | false | null | package day02
import readInput
fun main() {
// A/X = 1 = Rock
// B/Y = 2 = Paper
// C/Z = 3 = Scissors
// 0 loss(X) 3 draw(Y) 6 for win(Z)
fun part1GetScore(round: Pair<Char, Char>) =
when (round) {
'A' to 'X' -> 4
'A' to 'Y' -> 8
'A' to 'Z' -> 3
'B' to 'X' -> 1
'B' to 'Y' -> 5
'B' to 'Z' -> 9
'C' to 'X' -> 7
'C' to 'Y' -> 2
'C' to 'Z' -> 6
else -> 0
}
fun part1(input: List<String>): Int = input.map { it[0] to it[2] }.sumOf { part1GetScore(it) }
fun part2GetScore(round: Pair<Char, Char>) =
when (round) {
'A' to 'X' -> 3
'A' to 'Y' -> 4
'A' to 'Z' -> 8
'B' to 'X' -> 1
'B' to 'Y' -> 5
'B' to 'Z' -> 9
'C' to 'X' -> 2
'C' to 'Y' -> 6
'C' to 'Z' -> 7
else -> 0
}
fun part2(input: List<String>): Int = input.map { it[0] to it[2] }.sumOf { part2GetScore(it) }
val testInput = readInput("day02/input_test")
println("----------Test----------")
println("Part 1: ${part1(testInput)}")
println("Part 2: ${part2(testInput)}")
val input = readInput("day02/input")
println("----------Input----------")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 00ad7d82cfcac2cb8a902b310f01a6eedba985eb | 1,409 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | underwindfall | 573,471,357 | false | {"Kotlin": 42718} | private const val OLD = -1
fun main() {
val dayId = "11"
val input = readInput("Day${dayId}")
class R(var r: IntArray)
class Monkey(
val its: ArrayList<R>,
val oc: Char,
val z: Int,
val d: Int,
val tt: Int,
val tf: Int
) {
var cnt: Int = 0
}
val ms = input.parts { s ->
val si = s[1].substringAfter("Starting items: ").split(", ").map { it.toInt() }
val op = s[2].substringAfter("Operation: new = old ")
val oc = op[0]
val zz = op.substring(2)
val z = if (zz == "old") OLD else zz.toInt()
val d = s[3].substringAfter("Test: divisible by ").toInt()
val tt = s[4].substringAfter("If true: throw to monkey ").toInt()
val tf = s[5].substringAfter("If false: throw to monkey ").toInt()
Monkey(ArrayList(si.map { R(intArrayOf(it)) }), oc, z, d, tt, tf)
}
val ds = ms.map { it.d }
println(ds)
val n = ds.size
for (m in ms) {
for (i in m.its) {
val b = IntArray(n)
for (j in 0 until n) {
b[j] = i.r[0] % ds[j]
}
i.r = b
}
}
repeat(10000) {
for (m in ms) {
for (i in m.its) {
m.cnt++
for (j in 0 until n) {
var w = i.r[j]
val z = if (m.z == OLD) w else m.z
when (m.oc) {
'*' -> w *= z
'+' -> w += z
else -> error(m.oc)
}
w %= ds[j]
i.r[j] = w
}
val j = ds.indexOf(m.d)
when (i.r[j]) {
0 -> ms[m.tt].its += i
else -> ms[m.tf].its += i
}
}
m.its.clear()
}
}
val (a, b) = ms.sortedByDescending { it.cnt }.take(2)
val ans = a.cnt.toLong() * b.cnt
println(ans)
}
| 0 | Kotlin | 0 | 0 | 0e7caf00319ce99c6772add017c6dd3c933b96f0 | 2,013 | aoc-2022 | Apache License 2.0 |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day10.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
import com.akikanellis.adventofcode.year2022.utils.Point
object Day10 {
fun sumOfSignalStrengths(input: String): Int {
val cyclesOfInterest = IntProgression.fromClosedRange(20, 220, 40)
return systemSnapshots(input)
.filter { cyclesOfInterest.contains(it.cycle) }
.sumOf { it.signalStrength }
}
fun displayOutput(input: String) = systemSnapshots(input)
.last()
.crt
.displayOutput()
private fun systemSnapshots(input: String): List<SystemSnapshot> {
val instructions = input
.lines()
.filter { it.isNotBlank() }
.map { Instruction(it) }
.toMutableList()
return (1..240)
.fold(
listOf(
SystemSnapshot(
cycle = 0,
sprite = (0..2),
signalStrength = 0,
crt = Crt(Pair(40, 6))
)
)
) { snapshots, cycle ->
val lastSnapshot = snapshots.last()
val lastSprite = lastSnapshot.sprite
val signalStrength = (lastSprite.first + 1) * cycle
val crt = lastSnapshot.crt.drawNextPixel(lastSprite)
val instruction = instructions[0].decreasedCost()
instructions[0] = instruction
val sprite = if (instruction.remainingCost == 0) {
instruction.updatedSprite(lastSprite).also { instructions.removeFirst() }
} else {
lastSprite
}
snapshots + SystemSnapshot(
cycle = cycle,
sprite = sprite,
signalStrength = signalStrength,
crt = crt
)
}
}
private data class SystemSnapshot(
val cycle: Int,
val sprite: IntRange,
val signalStrength: Int,
val crt: Crt
)
private data class Instruction(
private val instruction: String,
val name: String = instruction.split(" ")[0],
val startingCost: Int = if (name == "addx") 2 else 1,
val remainingCost: Int = startingCost
) {
fun decreasedCost() = copy(remainingCost = remainingCost - 1)
fun updatedSprite(sprite: IntRange) = if (name == "addx") {
val valueToIncreaseSpriteBy = instruction.split(" ")[1].toInt()
IntRange(
sprite.first + valueToIncreaseSpriteBy,
sprite.last + valueToIncreaseSpriteBy
)
} else {
sprite
}
}
data class Crt(
private val size: Pair<Int, Int>,
private val drawnPixels: List<Pixel> = emptyList()
) {
private val lastDrawnPixel = drawnPixels.lastOrNull()
fun drawNextPixel(sprite: IntRange): Crt {
val nextPixelPosition = nextPixelPosition()
val nextPixelCharacter = if (sprite.contains(nextPixelPosition.x)) '#' else '.'
return copy(drawnPixels = drawnPixels + Pixel(nextPixelPosition, nextPixelCharacter))
}
private fun nextPixelPosition() = when {
lastDrawnPixel == null -> Point.ZERO
reachedTheEdge(lastDrawnPixel) -> lastDrawnPixel.position.zeroX().plusY()
else -> lastDrawnPixel.position.plusX()
}
private fun reachedTheEdge(lastDrawnPixel: Pixel) =
size.first - lastDrawnPixel.position.x == 1
fun displayOutput() = drawnPixels
.chunked(size.first)
.joinToString("\n") { row ->
row.joinToString("") { pixel ->
pixel.character.toString()
}
}
}
data class Pixel(val position: Point, val character: Char = ' ')
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 3,919 | advent-of-code | MIT License |
src/main/kotlin/com/groundsfam/advent/y2023/d10/Day10.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d10
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.Direction
import com.groundsfam.advent.Direction.DOWN
import com.groundsfam.advent.Direction.LEFT
import com.groundsfam.advent.Direction.RIGHT
import com.groundsfam.advent.Direction.UP
import com.groundsfam.advent.grids.Grid
import com.groundsfam.advent.points.go
import com.groundsfam.advent.grids.containsPoint
import com.groundsfam.advent.grids.map
import com.groundsfam.advent.points.Point
import com.groundsfam.advent.timed
import com.groundsfam.advent.grids.toGrid
import kotlin.io.path.div
import kotlin.io.path.useLines
// contains the two directions that this pipe connects
typealias Pipe = Set<Direction>
fun Pipe(vararg dirs: Direction): Pipe = setOf(*dirs)
fun Char.toPipe(): Pipe =
when (this) {
'|' -> Pipe(UP, DOWN)
'-' -> Pipe(LEFT, RIGHT)
'F' -> Pipe(RIGHT, DOWN)
'7' -> Pipe(LEFT, DOWN)
'J' -> Pipe(LEFT, UP)
'L' -> Pipe(RIGHT, UP)
else -> Pipe()
}
class Solution(private val start: Point, private val pipes: Grid<Pipe>) {
// if loop[point] is not null, then point is in the main loop
// and the direction is the where the loop is going to next
// for corners, always choose the vertical direction, for purpose
// of finding the interior points
private val loop: Grid<Direction?>
private val loopLength: Int
// the direction, either UP or DOWN, of the leftmost edge of the loop
private val leftLoopDir: Direction
init {
loop = pipes.map { null }
var _loopLength = 0
var prevDir: Direction = Direction.entries
.filter { dir ->
val adjacent = start.go(dir)
pipes.containsPoint(adjacent) && -dir in pipes[adjacent]
}.let { dirs ->
// choose vertical direction if possible
dirs.firstOrNull { it.isVertical() } ?: dirs.first()
}
loop[start] = prevDir
var curr: Point = start.go(prevDir)
_loopLength++
while (curr != start) {
val nextDir = pipes[curr].first { it != -prevDir }
// choose vertical direction if possible
loop[curr] = if (prevDir.isVertical()) prevDir else nextDir
prevDir = nextDir
curr = curr.go(prevDir)
_loopLength++
}
loopLength = _loopLength
leftLoopDir = loop.firstNotNullOf { row ->
row.firstOrNull { it != null }
}
}
fun farthestLoopPoint(): Int = loopLength / 2
fun loopInterior(): Int =
pipes.indices.sumOf { y ->
val row = pipes[y]
var count = 0
var prevVerticalDir: Direction? = null
row.indices.forEach { x ->
when (val d = loop[Point(x, y)]) {
null -> {
if (prevVerticalDir == leftLoopDir) {
count++
}
}
UP, DOWN -> {
prevVerticalDir = d
}
else -> {} // ignore
}
}
count
}
}
fun main() = timed {
val solution = (DATAPATH / "2023/day10.txt").useLines { lines ->
var start: Point? = null
val pipes = lines
.mapIndexed { y, line ->
line.mapIndexed { x, c ->
if (c == 'S') {
start = Point(x, y)
}
c.toPipe()
}
}
.toList()
.toGrid()
Solution(start!!, pipes)
}
println("Part one: ${solution.farthestLoopPoint()}")
println("Part two: ${solution.loopInterior()}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,827 | advent-of-code | MIT License |
src/main/kotlin/Day17.kt | Yeah69 | 317,335,309 | false | {"Kotlin": 73241} | class Day17 : Day() {
override val label: String get() = "17"
private data class Quadruple(val x: Int, val y: Int, val z: Int, val w: Int)
private fun <T> initialState(factory: (Int, Int) -> T) = input
.lineSequence()
.flatMapIndexed { y, line -> line
.asSequence()
.mapIndexed { x, c -> Pair(x, c) }
.filter { (_, c) -> c == '#' }
.map { (x, _) -> factory(x, y) } }
.toHashSet()
private val initialStateZero by lazy { initialState { x, y -> Triple(x, y, 0) } }
private val initialStateOne by lazy { initialState { x, y -> Quadruple(x, y, 0, 0) } }
private fun <T> HashSet<T>.cycle(neighborhood: (T) -> Sequence<T>): HashSet<T> = this
.flatMap { neighborhood(it) }
.distinct()
.filter {
val active = this.contains(it)
val activeNeighbors = neighborhood(it)
.filter { n -> n != it }
.filter { n -> this.contains(n) }
.count()
active && activeNeighbors == 2 || activeNeighbors == 3
}
.toHashSet()
private fun <T> logic(initialState: HashSet<T>, neighborhood: (T) -> Sequence<T>): String = (0 until 6)
.fold(initialState) { prevState, _ -> prevState.cycle { neighborhood(it) } }
.count()
.toString()
private fun Int.range(): IntRange = (this - 1)..(this + 1)
override fun taskZeroLogic(): String = logic(initialStateZero) {
val (x, y, z) = it
sequence {
for(x_ in x.range())
for(y_ in y.range())
for(z_ in z.range())
yield (Triple(x_, y_, z_)) } }
override fun taskOneLogic(): String = logic(initialStateOne) {
val (x, y, z, w) = it
sequence {
for(x_ in x.range())
for(y_ in y.range())
for(z_ in z.range())
for(w_ in w.range())
yield (Quadruple(x_, y_, z_, w_)) } }
} | 0 | Kotlin | 0 | 0 | 23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec | 2,037 | AdventOfCodeKotlin | The Unlicense |
src/day05/Day05.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day05
import readText
import java.util.*
fun main() {
fun getCrateStacks(input: List<String>): MutableList<Stack<Char>> {
var crates = input[0].split("\n")
val numStacks = crates.last().last()
val stacks = MutableList<Stack<Char>>(numStacks.digitToInt()) { Stack() }
crates = crates.dropLast(1).reversed()
for (row in crates) {
// skip over any whitespace
var i = row.indexOfFirst { !it.isWhitespace() }
while (i < row.length) {
// hop 4 indices at a time to check for a value
while (row[i].isWhitespace()) {
i += 4
}
val crate = row[i + 1]
stacks[i/4].push(crate)
i += 4
}
}
return stacks
}
fun part1(input: List<String>): String {
var stacks = getCrateStacks(input)
var instructions = input[1].split("\n")
for (instruction in instructions) {
val splitInstruction = instruction.split(" ")
var amount = splitInstruction[1].toInt()
val stack1 = splitInstruction[3].toInt() - 1 // translate to index
val stack2 = splitInstruction[5].toInt() - 1 // translate to index
while (amount > 0) {
var crate = stacks[stack1].pop()
stacks[stack2].push(crate)
amount -= 1
}
}
var answer = ""
for (stack in stacks) {
answer += stack.peek()
}
return answer
}
fun part2(input: List<String>): String {
val stacks = getCrateStacks(input)
val instructions = input[1].split("\n")
for (instruction in instructions) {
val splitInstruction = instruction.split(" ")
var amount = splitInstruction[1].toInt()
val stack1 = splitInstruction[3].toInt() - 1 // translate to index
val stack2 = splitInstruction[5].toInt() - 1 // translate to index
var tempStack = Stack<Char>()
while (amount > 0) {
var crate = stacks[stack1].pop()
tempStack.push(crate)
amount -= 1
}
while (tempStack.isNotEmpty()) {
stacks[stack2].push(tempStack.pop())
}
}
var answer = ""
for (stack in stacks) {
answer += stack.peek()
}
return answer
}
var testInput = readText("day05/test").split("\n\n")
println(part1(testInput))
println(part2(testInput))
var input = readText("day05/input").split("\n\n")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 2,731 | aoc2022 | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2021/Day5.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import kotlin.math.sign
/**
* --- Day 5: Hydrothermal Venture ---
* https://adventofcode.com/2021/day/5
*/
class Day5 : Solver {
override fun solve(lines: List<String>): Result {
val regex = """([0-9]+),([0-9]+) -> ([0-9]+),([0-9]+)""".toRegex()
val input = lines.map { regex.find(it)!!.destructured }
.map { (x1, y1, x2, y2) -> Line(Point(x1.toInt(), y1.toInt()), Point(x2.toInt(), y2.toInt())) }
val area = mutableListOf<Point>()
for (i in input) {
val validForA = i.a.x == i.b.x || i.a.y == i.b.y
val dir = Point((i.b.x - i.a.x).sign, (i.b.y - i.a.y).sign)
area.add(Point(i.a.x, i.a.y, validForA))
while (i.a != i.b) {
i.a.x += dir.x
i.a.y += dir.y
area.add(Point(i.a.x, i.a.y, validForA))
}
}
val partA = area.filter { it.partA }.groupBy { it }.count { it.value.size > 1 }
val partB = area.groupBy { "${it.x},${it.y}" }.count { it.value.size > 1 }
return Result("$partA", "$partB")
}
private data class Point(var x: Int, var y: Int, val partA: Boolean = false)
private data class Line(val a: Point, val b: Point)
}
| 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,208 | euler | Apache License 2.0 |
src/year2022/day03/Day03.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day03
import check
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day03_test")
check(part1(testInput), 157)
check(part2(testInput), 70)
val input = readInput("2022", "Day03")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int = input.sumOf {
it.chunked(it.length / 2).firstCommonChar.priority
}
private fun part2(input: List<String>): Int = input.windowed(3, 3).sumOf {
it.firstCommonChar.priority
}
private val List<String>.firstCommonChar: Char
get() = map { it.bitmask }.reduce { acc, mask -> acc and mask }.firstActiveChar
private val String.bitmask: Long
get() = fold(0) { acc, c -> acc or c.mask }
private val Long.firstActiveChar: Char
get() {
for (i in 0..51) {
if (this and (1L shl i) != 0L) {
return if (i < 26) 'a' + i
else 'A' + (i - 26)
}
}
error("no active char")
}
private val Char.mask: Long
get() = 1L shl if (isLowerCase()) minus('a') else minus('A') + 26
private val Char.priority: Int
get() = if (isLowerCase()) minus('a') + 1 else minus('A') + 27 | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,260 | AdventOfCode | Apache License 2.0 |
src/Day03.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | val alphabet = (('a'..'z') + ('A' .. 'Z')).toList()
fun main() {
fun duplicates(first: String, second: String) =
(first.indices)
.filter { second.indexOf(first[it]) >= 0 }
.map { first[it] }
fun priority(element: Char) = alphabet.indexOf(element) + 1
fun findDuplicate(first: String, second: String): Int {
return priority(duplicates(first, second).first())
}
fun part1(input: List<String>): Int {
return input.asSequence()
.map { findDuplicate(it, it.substring(it.length / 2)) }
.sum()
}
fun part2(input: List<String>): Int {
return input.chunked(3).asSequence()
.map { duplicates(it[0], it[1]).find { dupe -> it[2].indexOf(dupe) >= 0 }!! }
.map { priority(it) }
.sum()
}
part1(readInput("input")).println()
part2(readInput("input")).println()
} | 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 949 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | askeron | 572,955,924 | false | {"Kotlin": 24616} | import kotlin.math.max
typealias PointMap = Map<Point, Int>
class Day08 : Day<Int>(21, 8, 1779, 172224) {
private fun parseInput(input: List<String>): PointMap {
return input.IntMatrixToPointMap()
}
override fun part1(input: List<String>): Int {
return parseInput(input).let { pointMap -> pointMap.keys.count { pointMap.isVisibleFromOutside(it) } }
}
override fun part2(input: List<String>): Int {
return parseInput(input).let { pointMap -> pointMap.keys.maxOf { pointMap.getScenicScore(it) } }
}
private fun Set<Point>.viewLinesFromEdge(point: Point): List<List<Point>> = listOf(
filter { it.x == point.x }.partition { it.y < point.y },
filter { it.y == point.y }.partition { it.x < point.x },
).flatMap { listOf(it.first, it.second.filter { it != point }.reversed()) }
private fun PointMap.isVisibleFromOutside(point: Point): Boolean = keys.viewLinesFromEdge(point)
.also { if (it.any { it.isEmpty() }) return true }
.any { it.all { get(it)!! < get(point)!! } }
private fun PointMap.getScenicScore(point: Point): Int = keys.viewLinesFromEdge(point)
.map { it.reversed().map { get(it)!! }.takeWhilePlusOne { it < get(point)!! }.count() }
.reduce { a, b -> a * b}
}
| 0 | Kotlin | 0 | 1 | 6c7cf9cf12404b8451745c1e5b2f1827264dc3b8 | 1,285 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day05.kt | daniyarmukhanov | 572,847,967 | false | {"Kotlin": 9474} | fun main() {
fun part1(inputStack: Array<String>, input: List<String>): String {
input.forEachIndexed { index, line ->
val digits = line.split(" ").mapNotNull { it.toIntOrNull() }
val size = digits[0]
val from = digits[1] - 1
val to = digits[2] - 1
repeat(size) {
inputStack[to] =
inputStack[to].toMutableList().apply { add(inputStack[from].toCharArray().last()) }.joinToString("")
inputStack[from] = inputStack[from].toMutableList().apply { removeLast() }.joinToString("")
}
}
return inputStack.map { it.last() }.joinToString("")
}
fun part2(inputStack: Array<String>, input: List<String>): String {
input.forEachIndexed { index, line ->
val digits = line.split(" ").mapNotNull { it.toIntOrNull() }
val size = digits[0]
val from = digits[1] - 1
val to = digits[2] - 1
val fromStr = inputStack[from]
inputStack[to] =
inputStack[to].toMutableList().apply { addAll(fromStr.toList().takeLast(size)) }.joinToString("")
inputStack[from] = fromStr.toMutableList().take(inputStack[from].length - size).joinToString("")
}
return inputStack.map { it.last() }.joinToString("")
}
val testInput = readInput("Day05_test")
check(part1(inputTest, testInput) == "CMZ")
check(part2(inputTestPart2, testInput) == "MCD")
val input = readInput("Day05")
println(part1(inputData, input))
println(part2(inputDataPart2, input))
}
val inputTest = arrayOf("ZN", "MCD", "P")
val inputTestPart2 = arrayOf("ZN", "MCD", "P")
val inputData = mutableListOf<String>().apply {
add("FCPGQR")
add("WTCP")
add("BHPMC")
add("LTQSMPR")
add("PHJZVGN")
add("DPJ")
add("LGPZFJTR")
add("NLHCFPTJ")
add("GVZQHTCW")
}.toTypedArray()
val inputDataPart2 = mutableListOf<String>().apply {
add("FCPGQR")
add("WTCP")
add("BHPMC")
add("LTQSMPR")
add("PHJZVGN")
add("DPJ")
add("LGPZFJTR")
add("NLHCFPTJ")
add("GVZQHTCW")
}.toTypedArray()
| 0 | Kotlin | 0 | 0 | ebad16b2809ef0e3c7034d5eed75e6a8ea34c854 | 2,185 | aoc22 | Apache License 2.0 |
src/main/kotlin/day05/Day05.kt | Malo-T | 575,370,082 | false | null | package day05
import day05.Day05.Step
private typealias Stack = MutableList<Char>
private typealias Storage = MutableList<Stack>
private const val EMPTY = ' '
private fun List<String>.indexOfStackNumbers() = indexOfFirst { it.startsWith(" 1") }
private val stepRegex = """move (\d+) from (\d+) to (\d+)""".toRegex()
private fun String.toStep() = stepRegex.find(this)!!.groupValues.let { (_, amount, from, to) ->
Step(
amount = amount.toInt(),
from = from.toInt(),
to = to.toInt()
)
}
// CrateMover 9000 moves one by one
private fun Storage.move(step: Step) {
(0 until step.amount).forEach { _ ->
this[step.toIndex].add(this[step.fromIndex].last())
this[step.fromIndex].removeLast()
}
}
// CrateMover 9001 moves by batch
private fun Storage.moveV2(step: Step) {
this[step.toIndex].addAll(this[step.fromIndex].takeLast(step.amount))
this[step.fromIndex] = this[step.fromIndex].dropLast(step.amount).toMutableList()
}
class Day05 {
data class Step(
val amount: Int,
val from: Int,
val to: Int,
) {
val fromIndex: Int
get() = from - 1
val toIndex: Int
get() = to - 1
}
fun parse(input: String): Pair<Storage, List<Step>> {
val storage: Storage = input
.lines()
.let { lines -> lines.subList(0, lines.indexOfStackNumbers()) }
.map { row -> row.chunked(4).map { it[1] } }
// transform rows to columns (stacks)
.let { rows ->
rows.fold(
initial = List(rows.first().size) { mutableListOf<Char>() },
operation = { columns, row ->
columns.apply {
forEachIndexed { columnIndex, column ->
// remove empty values
if (row[columnIndex] != EMPTY) {
column.add(row[columnIndex])
}
}
}
}
).map { it.reversed().toMutableList() } // bottom to top of the stack
}.toMutableList()
.onEach { println(it) }
val steps = input
.lines()
.let { lines -> lines.subList(lines.indexOfStackNumbers() + 2, lines.size) }
.map { it.toStep() }
.onEach { println(it) }
return storage to steps
}
fun part1(parsed: Pair<Storage, List<Step>>): String {
val (storage, steps) = parsed
steps.forEach { step -> storage.move(step) }
return storage.joinToString(separator = "") { stack -> "${stack.last()}" }
}
fun part2(parsed: Pair<Storage, List<Step>>): String {
val (storage, steps) = parsed
steps.forEach { step -> storage.moveV2(step) }
return storage.joinToString(separator = "") { stack -> "${stack.last()}" }
}
}
| 0 | Kotlin | 0 | 0 | f4edefa30c568716e71a5379d0a02b0275199963 | 2,986 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinFlips.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
/**
* 1318. Minimum Flips to Make a OR b Equal to c
* @see <a href="https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/">Source</a>
*/
fun interface MinFlips {
operator fun invoke(a: Int, b: Int, c: Int): Int
}
/**
* Approach 1: Bit Manipulation
*/
class MinFlipsBitManipulation : MinFlips {
override operator fun invoke(a: Int, b: Int, c: Int): Int {
var answer = 0
var a1 = a
var b1 = b
var c1 = c
while ((a1 != 0) or (b1 != 0) or (c1 != 0)) {
if (c1 and 1 == 1) {
if (a1 and 1 == 0 && b1 and 1 == 0) {
answer++
}
} else {
answer += (a1 and 1) + (b1 and 1)
}
a1 = a1 shr 1
b1 = b1 shr 1
c1 = c1 shr 1
}
return answer
}
}
/**
* Approach 2: Count the Number of Set Bits Using Built-in Function
*/
class MinFlipsSetBits : MinFlips {
override operator fun invoke(a: Int, b: Int, c: Int): Int {
return Integer.bitCount(a or b xor c) + Integer.bitCount(a and b and (a or b xor c))
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,776 | kotlab | Apache License 2.0 |
src/Day14.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import Material.*
import java.awt.Point
import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
val cave = Cave.parse(input) // .also { println(it) }
val sandSource = Point(500, 0)
var steps = 0
while (cave.pourSand(sandSource)) {
steps++
}
return steps
}
fun part2(input: List<String>): Int {
val cave = Cave.parse(input, true) // .also { println(it) }
val sandSource = Point(500, 0)
var steps = 0
while (cave.pourSand(sandSource)) {
steps++
}
return steps
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
assertEquals(24, part1(testInput))
assertEquals(93, part2(testInput))
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
private enum class Material(val isSolid: Boolean) {
SAND(true),
ROCK(true),
AIR(false);
override fun toString() =
when (this) {
SAND -> "o"
ROCK -> "#"
AIR -> "."
}
}
private data class Structure(val material: Material, val path: List<Point>)
private class Line(a: Point, b: Point) : Iterable<Point> {
val start: Point = if (a.x < b.x || a.y < b.y) a else b
val end: Point = if (a.x < b.x || a.y < b.y) b else a
init {
require(start.x == end.x || start.y == end.y) {
"Points must represent a horizontal or vertical line"
}
}
override fun iterator(): Iterator<Point> = PointByPointIterator()
private inner class PointByPointIterator : Iterator<Point> {
val isHorizontalLine = start.y == end.y
var currentOffset = 0
override fun hasNext(): Boolean {
return if (isHorizontalLine) {
start.x + currentOffset <= end.x
} else {
start.y + currentOffset <= end.y
}
}
override fun next(): Point {
if (!hasNext())
throw NoSuchElementException("No further points on line: end of line already reached.")
return if (isHorizontalLine) {
Point(start.x + currentOffset++, start.y)
} else {
Point(start.x, start.y + currentOffset++)
}
}
}
}
private class Cave(val map: Array<Array<Material>>) {
/** @return true if sand comes to rest and source is not blocked */
fun pourSand(source: Point): Boolean {
val isSourceBlocked = map[source.x][source.y].isSolid
if (isSourceBlocked) return false
val restPoint = simulateFallingMaterial(source)
if (restPoint != null) {
map[restPoint.x][restPoint.y] = SAND
}
return restPoint != null
}
/** @return point where falling material comes to rest or null if it falls into void */
private fun simulateFallingMaterial(source: Point): Point? {
for (y in source.y..map[source.x].lastIndex) {
if (map[source.x][y].isSolid) {
return when {
!map[source.x - 1][y].isSolid -> simulateFallingMaterial(Point(source.x - 1, y))
!map[source.x + 1][y].isSolid -> simulateFallingMaterial(Point(source.x + 1, y))
else -> Point(source.x, y - 1)
}
}
}
return null
}
private fun add(structures: List<Structure>) {
for (structure in structures) {
for (i in 0 until structure.path.lastIndex) {
val line = Line(structure.path[i], structure.path[i + 1])
for (point in line) {
map[point.x][point.y] = structure.material
}
}
}
}
override fun toString() = buildString {
for (y in map[0].indices) {
for (x in 490..510) {
append(map[x][y])
}
appendLine()
}
}
companion object {
fun parse(input: List<String>, withFloor: Boolean = false): Cave {
val structures =
input
.map { line ->
line.split(" -> ").map { xyPair ->
Point(
xyPair.split(",").first().toInt(),
xyPair.split(",").last().toInt(),
)
}
}
.map { points -> Structure(ROCK, points) }
val yOfLowestStructure = structures.flatMap { it.path }.maxOf { it.y }
val xOfMostRightStructure = structures.flatMap { it.path }.maxOf { it.x }
val floor =
Structure(
ROCK,
listOf(
Point(0, yOfLowestStructure + 2),
Point(xOfMostRightStructure * 2, yOfLowestStructure + 2)),
)
val map = Array(xOfMostRightStructure * 2 + 1) { Array(yOfLowestStructure + 2 + 1) { AIR } }
return Cave(map).apply {
add(structures)
if (withFloor) add(listOf(floor))
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 4,638 | aoc2022 | Apache License 2.0 |
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/combinations.kt | xiaodongw | 247,462,184 | true | {"Kotlin": 2089944, "HTML": 423, "Java": 153} | package io.kotest.property.arbitrary
import io.kotest.property.Gen
import io.kotest.property.RandomSource
import io.kotest.property.Sample
/**
* Returns a stream of values based on weights:
*
* Arb.choose(1 to 'A', 2 to 'B') will generate 'A' 33% of the time
* and 'B' 66% of the time.
*
* @throws IllegalArgumentException If any negative weight is given or only
* weights of zero are given.
*/
fun <A : Any> Arb.Companion.choose(a: Pair<Int, A>, b: Pair<Int, A>, vararg cs: Pair<Int, A>): Arb<A> {
val allPairs = listOf(a, b) + cs
val weights = allPairs.map { it.first }
require(weights.all { it >= 0 }) { "Negative weights not allowed" }
require(weights.any { it > 0 }) { "At least one weight must be greater than zero" }
return object : BasicArb<A> {
// The algorithm for pick is a migration of
// the algorithm from Haskell QuickCheck
// http://hackage.haskell.org/package/QuickCheck
// See function frequency in the package Test.QuickCheck
private tailrec fun pick(n: Int, l: Sequence<Pair<Int, A>>): A {
val (w, e) = l.first()
return if (n <= w) e
else pick(n - w, l.drop(1))
}
override fun edgecases(): List<A> = emptyList()
override fun sample(rs: RandomSource): Sample<A> {
val total = weights.sum()
val n = rs.random.nextInt(1, total + 1)
val value = pick(n, allPairs.asSequence())
return Sample(value)
}
}
}
/**
* Generates random permutations of a list.
*/
fun <A> Arb.Companion.shuffle(list: List<A>) = arb { list.shuffled(it.random) }
/**
* Generates a random subsequence, including the empty list.
*/
fun <A> Arb.Companion.subsequence(list: List<A>) = arb {
list.take(it.random.nextInt(0, list.size + 1))
}
/**
* Randomly selects one of the given generators to generate the next element.
* The input must be non-empty.
*/
fun <A> Arb.Companion.choice(vararg gens: Gen<A>): Arb<A> = arb {
gens.asList().shuffled(it.random).first().generate(it).first().value
}
| 1 | Kotlin | 0 | 0 | f14814a8d8d3ade611b8b004219ba6b3dd9cf979 | 2,036 | kotest | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2020/d24/Day24.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2020.d24
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.points.Point
import kotlin.io.path.div
import kotlin.io.path.useLines
enum class Direction {
W,
NW,
NE,
E,
SE,
SW
}
// convention for this problem:
// going NE changes only Y coord, while going NW changes both X and Y
// going SE changes X and Y coords, while going SW only changes X
// these conventions are consistent with movement on a hexagonal grid
fun Direction.asPoint(): Point = when (this) {
Direction.W -> Point(-1, 0)
Direction.NW -> Point(-1, -1)
Direction.NE -> Point(0, -1)
Direction.E -> Point(1, 0)
Direction.SE -> Point(1, 1)
Direction.SW -> Point(0, 1)
}
fun Point.adjacents(): List<Point> = Direction.entries.map { this + it.asPoint() }
fun initialBlackTiles(tileIdentifiers: List<List<Direction>>): Set<Point> {
val flippedSet = mutableSetOf<Point>()
tileIdentifiers.forEach { directions ->
val tile = directions.fold(Point(0, 0)) { point, direction ->
point + direction.asPoint()
}
if (tile in flippedSet) {
flippedSet.remove(tile)
}
else {
flippedSet.add(tile)
}
}
return flippedSet
}
// given the current black tiles, return the set of black tiles after tiles are
// flipped according to rules in part two
fun flipTiles(blackTiles: Set<Point>): Set<Point> {
val tilesToFlip = mutableSetOf<Point>()
// find matching black tiles
blackTiles.forEach { tile ->
tile
.adjacents()
.count { it in blackTiles }
.takeIf { it !in setOf(1, 2) }
?.also {
tilesToFlip.add(tile)
}
}
// find matching white tiles
blackTiles.forEach { tile ->
tile.adjacents()
.filter { it !in blackTiles }
.forEach { whiteTile ->
whiteTile
.adjacents()
.count { it in blackTiles }
.takeIf { it == 2 }
?.also {
tilesToFlip.add(whiteTile)
}
}
}
// return symmetric difference
return (blackTiles + tilesToFlip) - (blackTiles.intersect(tilesToFlip))
}
fun main() {
val tileIdentifiers = (DATAPATH / "2020/day24.txt").useLines { lines ->
lines.toList().map { line ->
val list = mutableListOf<Direction>()
var i = 0
while (i < line.length) {
when (line[i]) {
'e' ->
Direction.E
.also { i++ }
'w' ->
Direction.W
.also { i++ }
'n' ->
(if (line[i+1] == 'e') Direction.NE
else Direction.NW)
.also { i += 2 }
's' ->
(if (line[i+1] == 'e') Direction.SE
else Direction.SW)
.also { i += 2 }
else -> throw RuntimeException("Illegal character ${list[i]} at position $i of $line")
}.also {
list.add(it)
}
}
list.toList() // make it immutable
}
}
var blackTiles = initialBlackTiles(tileIdentifiers)
.also { println("Part one: ${it.size}") }
repeat(100) {
blackTiles = flipTiles(blackTiles)
}
println("Part two: ${blackTiles.size}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,623 | advent-of-code | MIT License |
src/main/java/challenges/educative_grokking_coding_interview/k_way_merge/_2/KSmallestNumber.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.k_way_merge._2
import java.util.*
/**
You are given an m number of sorted lists in ascending order and an integer, k, find the kth
smallest number among all the given lists.
Although there can be repeating values in the lists, each element is considered unique and, therefore,
contributes to calculating the kth
smallest element.
If k is greater than the total number of elements in the input lists, return the greatest element from all the
lists and if there are no elements in the input lists, return 0.
https://www.educative.io/courses/grokking-coding-interview-patterns-java/qAjl2YpWQwD
*/
internal object KSmallestNumber {
private fun kSmallestNumber(lists: List<List<Int?>>, k: Int): Int {
// storing the length of lists to use it in a loop later
val listLength = lists.size
// declaring a min-heap to keep track of smallest elements
val kthSmallest = PriorityQueue { a: IntArray, b: IntArray ->
a[0] - b[0]
}
for (index in 0 until listLength) {
// if there are no elements in the input lists, continue
if (lists[index].isEmpty()) {
continue
} else {
// placing the first element of each list in the min-heap
kthSmallest.offer(intArrayOf(lists[index][0]!!, index, 0))
}
}
// set a counter to match if our kth element
// equals to that counter, return that number
var numbersChecked = 0
var smallestNumber = 0
while (!kthSmallest.isEmpty()) { // iterating over the elements pushed in our min-heap
// get the smallest number from top of heap and its corresponding list and index
val smallest = kthSmallest.poll()
smallestNumber = smallest[0]
val listIndex = smallest[1]
val numIndex = smallest[2]
numbersChecked++
if (numbersChecked == k) {
break
}
// if there are more elements in list of the top element,
// add the next element of that list to the min-heap
if (numIndex + 1 < lists[smallest[1]].size) {
kthSmallest.offer(intArrayOf(lists[listIndex][numIndex + 1]!!, listIndex, numIndex + 1))
}
}
// return the Kth number found in input lists
return smallestNumber
}
@JvmStatic
fun main(args: Array<String>) {
val lists = listOf(
listOf(
listOf(2, 6, 8),
listOf(3, 6, 10),
listOf(5, 8, 11)
),
listOf(
listOf(1, 2, 3),
listOf(4, 5),
listOf(6, 7, 8, 15),
listOf(10, 11, 12, 13),
listOf(5, 10)
),
listOf(
listOf(),
listOf(),
listOf()
),
listOf(
listOf(1, 1, 3, 8),
listOf(5, 5, 7, 9),
listOf(3, 5, 8, 12)
),
listOf(
listOf(5, 8, 9, 17),
listOf(),
listOf(8, 17, 23, 24)
)
)
val k = intArrayOf(5, 50, 7, 4, 8)
// loop to execute till the length of list k
for (i in k.indices) {
println(
"${i + 1}.\t Input lists: " + lists[i] +
"\n\t K = " + k[i] +
"\n\t " + k[i] + "th smallest number from the given lists is: " +
kSmallestNumber(lists[i], k[i])
)
println(String(CharArray(100)).replace('\u0000', '-'))
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 3,764 | CodingChallenges | Apache License 2.0 |
src/day20/Main.kt | nikwotton | 572,814,041 | false | {"Kotlin": 77320} | package day20
import java.io.File
import kotlin.math.abs
val workingDir = "src/${object {}.javaClass.`package`.name}"
fun main() {
val sample = File("$workingDir/sample.txt")
val input1 = File("$workingDir/input_1.txt")
println("Step 1a: ${runStep1(sample)}") // 3
println("Step 1b: ${runStep1(input1)}") // 17490
println("Step 2a: ${runStep2(sample)}") // 1623178306
println("Step 2b: ${runStep2(input1)}") // 1632917375836
}
data class Node(val value: Int, val shrunkValue: Long, var prev: Node?, var next: Node?, var originalPrev: Node?, var originalNext: Node?) {
fun printLine() {
var c = this
val ret = ArrayList<Long>()
do {
ret.add(c.shrunkValue)
c = c.next!!
} while (c != this)
println(ret)
}
}
fun runStep1(input: File): String {
val inputNumbers = input.readLines().map { it.toInt() }.map { Node(it, -1, null, null, null, null) }
inputNumbers.forEachIndexed { index, node ->
when (index) {
0 -> {
node.next = inputNumbers[1]
node.prev = inputNumbers.last()
}
inputNumbers.size-1 -> {
node.next = inputNumbers.first()
node.prev = inputNumbers[index-1]
}
else -> {
node.next = inputNumbers[index+1]
node.prev = inputNumbers[index-1]
}
}
}
inputNumbers.forEach {
it.originalNext = it.next
it.originalPrev = it.prev
}
var current = inputNumbers.first()
do {
if (current.value < 0) {
repeat(abs(current.value)) {
val twoBack = current.prev!!.prev!!
val oneBack = current.prev!!
val next = current.next!!
twoBack.next = current
oneBack.prev = current
oneBack.next = next
next.prev = oneBack
current.prev = twoBack
current.next = oneBack
}
} else if (current.value == 0) {
Unit
} else if (current.value > 0) {
repeat(current.value) {
val prev = current.prev!!
val oneForward = current.next!!
val twoForward = current.next!!.next!!
prev.next = oneForward
oneForward.prev = prev
oneForward.next = current
twoForward.prev = current
current.prev = oneForward
current.next = twoForward
}
} else TODO()
current = current.originalNext!!
} while (current != inputNumbers.first())
tailrec fun Node.atIndex(index: Int): Node {
if (index == 0) return this
return next!!.atIndex(index-1)
}
return listOf(1000, 2000, 3000).sumOf { inputNumbers.first { it.value == 0 }.atIndex(it).value }.toString()
}
fun runStep2(input: File): String {
val decryptionKey = 811589153L
val lines = input.readLines().count { it.isNotBlank() } - 1
val inputNumbers = input.readLines().map { it.toInt() }.map {
Node(((it * decryptionKey) % lines).toInt(), it * decryptionKey, null, null, null, null)
}
inputNumbers.forEachIndexed { index, node ->
when (index) {
0 -> {
node.next = inputNumbers[1]
node.prev = inputNumbers.last()
}
inputNumbers.size-1 -> {
node.next = inputNumbers.first()
node.prev = inputNumbers[index-1]
}
else -> {
node.next = inputNumbers[index+1]
node.prev = inputNumbers[index-1]
}
}
}
inputNumbers.forEach {
it.originalNext = it.next
it.originalPrev = it.prev
}
repeat(10) {
var current = inputNumbers.first()
do {
if (current.value < 0) {
repeat(abs(current.value)) {
val twoBack = current.prev!!.prev!!
val oneBack = current.prev!!
val next = current.next!!
twoBack.next = current
oneBack.prev = current
oneBack.next = next
next.prev = oneBack
current.prev = twoBack
current.next = oneBack
}
} else if (current.value == 0) {
Unit
} else if (current.value > 0) {
repeat(current.value) {
val prev = current.prev!!
val oneForward = current.next!!
val twoForward = current.next!!.next!!
prev.next = oneForward
oneForward.prev = prev
oneForward.next = current
twoForward.prev = current
current.prev = oneForward
current.next = twoForward
}
} else TODO()
current = current.originalNext!!
} while (current != inputNumbers.first())
}
tailrec fun Node.atIndex(index: Int): Node {
if (index == 0) return this
return next!!.atIndex(index-1)
}
return listOf(1000, 2000, 3000).sumOf {
(inputNumbers.first { it.value == 0 }.atIndex(it).shrunkValue)
}.toString()
}
| 0 | Kotlin | 0 | 0 | dee6a1c34bfe3530ae6a8417db85ac590af16909 | 5,415 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day20.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
class Day20 : Day(20) {
override fun partOne(): Any {
val numbers = parseNumbers()
mixNumbers(numbers)
return generateSequence(numbers.find { it.value == 0L }) { it.next }.take(numbers.size).map { it.value }.toList()
.let { it[1000 % numbers.size] + it[2000 % numbers.size] + it[3000 % numbers.size] }
}
override fun partTwo(): Any {
val numbers = parseNumbers(811589153)
mixNumbers(numbers, 10)
return generateSequence(numbers.find { it.value == 0L }) { it.next }.take(numbers.size).map { it.value }.toList()
.let { it[1000 % numbers.size] + it[2000 % numbers.size] + it[3000 % numbers.size] }
}
private fun parseNumbers(decryptionKey: Long = 1): List<Num> {
val numbers = inputList.map {
Num(it.toLong() * decryptionKey)
}.also {
it.zipWithNext { from, to ->
from.next = to
to.prev = from
}
}
numbers.first().prev = numbers.last()
numbers.last().next = numbers.first()
return numbers
}
private fun mixNumbers(numbers: List<Num>, reps: Int = 1) {
repeat (reps) {
numbers.forEach { value -> move(value, value.value.toSteps(numbers.size)) }
}
}
private fun move(element: Num, steps: Int) {
generateSequence(element) { it.next }
.take(steps + 1)
.last()
.let { nextTo ->
if (nextTo != element) {
val a = element.prev!!
val b = element.next!!
val ntn = nextTo.next!!
connect(a, b)
connect(nextTo, element)
connect(element, ntn)
}
}
}
private fun connect(from: Num, to: Num) {
from.next = to
to.prev = from
}
private fun Long.toSteps(size: Int): Int {
val cycle = size - 1
return if (this >= 0) (this % cycle).toInt()
else (this % cycle + cycle).toInt() % cycle
}
data class Num(val value: Long, var prev: Num? = null, var next: Num? = null) {
override fun toString(): String {
return "Num(value=$value, prev=${prev?.value}, next=${next?.value})"
}
}
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 2,327 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/questions/DailyTemperatures.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
import java.util.*
/**
* Given an array of integers `temperatures` represents the daily temperatures, return an array answer
* such that `answer[i]` is the number of days you have to wait after the `ith` day to get a warmer temperature.
* If there is no future day for which this is possible, keep `answer[i] == 0` instead.
*
* [Source](https://leetcode.com/problems/daily-temperatures/)
*/
@UseCommentAsDocumentation
private fun dailyTemperatures(temperatures: IntArray): IntArray {
val ans = IntArray(temperatures.size) { 0 }
// Maintain an actual index that points the next higher temperature than current
// indices = 0, 1, 2, 3, 4
// temp = 4, 9, 6, 5, 7
// successorPointer = 1, 0, 4, 4, null
val successorPointer = Array<Int?>(temperatures.size) { null }
// no further higher temperature for last element
successorPointer[successorPointer.lastIndex] = null
for (i in temperatures.lastIndex - 1 downTo 0) {
val currentTemp = temperatures[i]
val nextTemp = temperatures[i + 1]
if (nextTemp > currentTemp) {
ans[i] = 1
successorPointer[i] = i + 1
} else {
val nextIndex = findImmediateSuccessorIndex(temperatures, successorPointer, i + 1, temperatures[i])
if (nextIndex == null) {
ans[i] = 0 // no higher temp
} else {
ans[i] = nextIndex - i
successorPointer[i] = nextIndex
}
}
}
return ans
}
private fun findImmediateSuccessorIndex(
temperatures: IntArray,
successorPointers: Array<Int?>,
index: Int?,
target: Int
): Int? {
if (index == null) {
return null
}
val nextIndex = successorPointers[index] ?: return null
return if (temperatures[nextIndex] > target) { // found next higher temp
nextIndex
} else {
// not found so go to whatever its successor is
findImmediateSuccessorIndex(temperatures, successorPointers, nextIndex, target)
}
}
fun main() {
dailyTemperatures(intArrayOf(80, 34, 80, 80, 80, 34, 34, 34, 34, 34)) shouldBe
intArrayOf(0, 1, 0, 0, 0, 0, 0, 0, 0, 0)
dailyTemperatures(intArrayOf(34, 80, 80, 34, 34, 80, 80, 80, 80, 34)) shouldBe
intArrayOf(1, 0, 0, 2, 1, 0, 0, 0, 0, 0)
dailyTemperatures(intArrayOf(89, 62, 70, 58, 47, 47, 46, 76, 100, 70)) shouldBe
intArrayOf(8, 1, 5, 4, 3, 2, 1, 1, 0, 0)
dailyTemperatures(intArrayOf(30, 60, 90)) shouldBe intArrayOf(1, 1, 0)
dailyTemperatures(intArrayOf(73, 74, 75, 71, 69, 72, 76, 73)) shouldBe intArrayOf(1, 1, 4, 2, 1, 1, 0, 0)
dailyTemperatures(intArrayOf(30, 40, 50, 60)) shouldBe intArrayOf(1, 1, 1, 0)
}
| 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,825 | algorithms | MIT License |
advent/src/test/kotlin/org/elwaxoro/advent/y2022/Dec21.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2022
import org.elwaxoro.advent.PuzzleDayTester
import java.lang.IllegalStateException
/**
* Day 21: Monkey Math
*/
class Dec21 : PuzzleDayTester(21, 2022) {
/**
* Root monkey shout. Computer monkey type that into AOC
*/
override fun part1(): Any = loader().solveForRoot().doTheMonkeyMath() == 104272990112064
/**
* Narrow down the `humn` factor (lol) with a little binary search
* using Long.MAX_VALUE here caused the search to find some other local minimum that was close to the solution but not exact (diff of like 16)
* picked something lower for the upper bound to start with so the program will finish and produce the correct result
* answer could be one of two numbers for my input:
* 3220993874133 OR 3220993874134
*/
override fun part2(): Any = loader().toMutableMap().let { initialMap ->
var upper = 100000000000000000L
var lower = 0L
var guess = upper/2
while(true) {
initialMap["humn"] = "$guess"
val (left, _, right) = initialMap.solveForRoot().split(" ")
val diff = left.toLong() - right.toLong()
if(left == right) {
return guess
} else if(diff > 0) {
// guess is too low
lower = guess
} else {
// guess is too high
upper = guess
}
guess = ((upper-lower)/2) + lower
}
}
private fun Map<String, String>.solveForRoot(): String = toMutableMap().let { unsolved ->
val solvedMap = mutableMapOf<String, Long>()
val digitRegex = "-*\\d+".toRegex()
val root = unsolved.remove("root")!!
val (rootL, rootO, rootR) = root.split(" ")
while (!solvedMap.containsKey(rootL) || !solvedMap.containsKey(rootR)) {
val iter = unsolved.entries.iterator()
while (iter.hasNext()) {
val (variable, equation) = iter.next()
if (equation.matches(digitRegex)) {
solvedMap[variable] = equation.toLong()
iter.remove()
} else {
val (left, operator, right) = equation.split(" ")
if (left.matches(digitRegex) && right.matches(digitRegex)) {
solvedMap[variable] = equation.doTheMonkeyMath()
iter.remove()
} else {
val leftFix = "${solvedMap[left] ?: left}"
val rightFix = "${solvedMap[right] ?: right}"
unsolved[variable] = "$leftFix $operator $rightFix"
}
}
}
}
"${solvedMap[rootL]} $rootO ${solvedMap[rootR]}"
}
private fun String.doTheMonkeyMath() = split(" ").let { (left, operator, right) ->
when (operator) {
"+" -> left.toLong() + right.toLong()
"-" -> left.toLong() - right.toLong()
"*" -> left.toLong() * right.toLong()
"/" -> left.toLong() / right.toLong()
else -> throw IllegalStateException("YUNO MATH?? $left $operator $right")
}
}
private fun loader(): Map<String, String> = load().map { it.split(": ") }.associate { it[0] to it[1] }
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 3,337 | advent-of-code | MIT License |
src/year_2022/day_22/Day22.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_22
import readInput
import util.*
import kotlin.IllegalArgumentException
import kotlin.math.abs
typealias BoardPositions = Map<Point, Boolean>
sealed class Movement {
data class Move(val steps: Int): Movement()
data class Turn(val direction: TurnDirection): Movement()
}
enum class TurnDirection {
RIGHT,
LEFT,
;
}
enum class Facing(val value: Int) {
RIGHT(0),
DOWN(1),
LEFT(2),
UP(3),
;
fun turn(direction: TurnDirection): Facing {
return when (direction) {
TurnDirection.RIGHT -> when (this) {
UP -> RIGHT
RIGHT -> DOWN
DOWN -> LEFT
LEFT -> UP
}
TurnDirection.LEFT -> {
when (this) {
UP -> LEFT
RIGHT -> UP
DOWN -> RIGHT
LEFT -> DOWN
}
}
}
}
}
class Day22(text: List<String>) {
private val board: BoardPositions
private val movements: List<Movement>
init {
val (board, movements) = parseText(text)
this.board = board
this.movements = movements
}
/**
* @return
*/
fun solutionOne(): Int {
var currentFacing = Facing.RIGHT
var currPoint = board
.filter { it.key.second == 1 }
.filter { it.value }
.keys
.minBy { it.first }
movements.forEach { movement ->
when (movement) {
is Movement.Turn -> {
val newFacing = currentFacing.turn(movement.direction)
println("Turning ${movement.direction} and now facing $newFacing")
currentFacing = currentFacing.turn(movement.direction)
}
is Movement.Move -> {
println("Moving ${movement.steps} steps")
for (step in 1..movement.steps) {
var potentialPoint = when (currentFacing) {
Facing.UP -> currPoint.first to currPoint.second - 1
Facing.DOWN -> currPoint.first to currPoint.second + 1
Facing.RIGHT -> currPoint.first + 1 to currPoint.second
Facing.LEFT -> currPoint.first - 1 to currPoint.second
}
// if not on the board find the wrap around
if (board[potentialPoint] == null) {
potentialPoint = findWrapAround(currPoint, currentFacing)
}
// if the spot is open, move there (it should exist in the map)
if (board[potentialPoint] == null) {
throw IllegalArgumentException("WHAT HAVE I DONE")
}
if (board[potentialPoint] == true) {
// println("Moving to $potentialPoint")
currPoint = potentialPoint
}
}
// println("Arrived at $currPoint")
}
}
}
// The final password is the sum of 1000 times the row, 4 times the column, and the facing.
return (1_000 * (currPoint.second)) + (4 * (currPoint.first) ) + currentFacing.value
}
/**
* @return
*/
fun solutionTwo(faceSize: Int): Int {
var currentFacing = Facing.RIGHT
var currPoint = board
.filter { it.key.second == 1 }
.filter { it.value }
.keys
.minBy { it.first }
movements.forEach { movement ->
when (movement) {
is Movement.Turn -> {
val newFacing = currentFacing.turn(movement.direction)
// println("Turning ${movement.direction} and now facing $newFacing")
currentFacing = currentFacing.turn(movement.direction)
}
is Movement.Move -> {
// println("Moving ${movement.steps} steps")
for (step in 1..movement.steps) {
var potentialFacing = currentFacing
var potentialPoint = when (currentFacing) {
Facing.UP -> currPoint.first to currPoint.second - 1
Facing.DOWN -> currPoint.first to currPoint.second + 1
Facing.RIGHT -> currPoint.first + 1 to currPoint.second
Facing.LEFT -> currPoint.first - 1 to currPoint.second
}
if (whichFace(potentialPoint, faceSize) != whichFace(currPoint, faceSize)) {
val result = wrapCubeToPointAndFacing(faceSize, currPoint, currentFacing)
potentialPoint = result.first
potentialFacing = result.second
}
if (potentialPoint !in board) {
throw IllegalArgumentException("Moving to unknown point!!? $potentialPoint")
}
// if the spot is open, move there (it should exist in the map)
if (board[potentialPoint] == true) {
currPoint = potentialPoint
currentFacing = potentialFacing
}
}
}
}
}
// The final password is the sum of 1000 times the row, 4 times the column, and the facing.
return (1_000 * (currPoint.second)) + (4 * (currPoint.first) ) + currentFacing.value
}
private fun parseText(text: List<String>): Pair<BoardPositions, List<Movement>> {
val positions = text
.subList(0, text.size - 2)
.flatMapIndexed { row, line ->
line.mapIndexedNotNull { col, char ->
when (char) {
'.' -> Point(col + 1, row + 1) to true
'#' -> Point(col + 1, row + 1) to false
else -> { null }
}
}
}.associate { it.first to it.second }
var builder = ""
val movements = mutableListOf<Movement>()
text.last().forEach { char ->
if (char.isLetter()) {
val turnMovement = when (char) {
'R' -> Movement.Turn(TurnDirection.RIGHT)
'L' -> Movement.Turn(TurnDirection.LEFT)
else -> throw IllegalArgumentException("Unknown letter: $char")
}
if (builder.isNotEmpty()) {
movements.add(Movement.Move(Integer.parseInt(builder)))
}
movements.add(turnMovement)
builder = ""
} else {
builder += char
}
}
if (builder.isNotEmpty()) {
movements.add(Movement.Move(Integer.parseInt(builder)))
}
return positions to movements
}
private fun findWrapAround(point: Point, facing: Facing): Point {
var result = point
when (facing) {
Facing.UP -> {
var checkDown = point.down()
while(board.contains(checkDown)) {
result = checkDown
checkDown = checkDown.down()
}
}
Facing.RIGHT -> {
var checkLeft = point.left()
while(board.contains(checkLeft)) {
result = checkLeft
checkLeft = checkLeft.left()
}
}
Facing.DOWN -> {
var checkUp = point.up()
while(board.contains(checkUp)) {
result = checkUp
checkUp = checkUp.up()
}
}
Facing.LEFT -> {
var checkRight = point.right()
while(board.contains(checkRight)) {
result = checkRight
checkRight = checkRight.right()
}
}
}
return result
}
/**
* Face 1 = (100, 0) -> (149, 49)
* Face 2 = ( 50, 50) -> (149, 99)
* Face 3 = ( 0, 100) -> ( 49, 149)
* Face 4 = ( 50, 100) -> ( 99, 149)
* Face 5 = ( 0, 150) -> ( 49, 199)
*/
private fun whichFace(point: Point, faceSize: Int): Int {
return when {
point.first in (faceSize + 1)..(faceSize * 2) && point.second in 1.. faceSize -> 0
point.first in ((faceSize * 2) + 1)..(faceSize * 3) && point.second in 1.. faceSize -> 1
point.first in (faceSize + 1)..(faceSize * 2) && point.second in (faceSize + 1)..(faceSize * 2) -> 2
point.first in 1.. (faceSize) && point.second in (faceSize * 2) + 1..(faceSize * 3) -> 3
point.first in (faceSize + 1)..(faceSize * 2) && point.second in (faceSize * 2) + 1 .. (faceSize * 3) -> 4
point.first in 1..(faceSize) && point.second in (faceSize * 3) + 1 .. (faceSize * 4) -> 5
else -> -1
}
}
private fun wrapCubeToPointAndFacing(faceSize: Int, point: Point, currentFacing: Facing): Pair<Point, Facing> {
return when(whichFace(point, faceSize)) {
0 -> {
when (currentFacing) {
Facing.UP -> {
val col = 1 // left edge of Face 5
val row = point.first + (2 * faceSize) // move down 2 faces and then continue on a side turn
(col to row) to Facing.RIGHT // 0 -> 5 is on a sideways turn
}
Facing.RIGHT -> point.right() to Facing.RIGHT // continue on Face 1
Facing.DOWN -> point.down() to Facing.DOWN // continue on Face 2
Facing.LEFT -> {
val col = 1 // left edge of Face 3
val row = (faceSize - point.second) + (2 * faceSize) + 1 // move down 2 faces and then invert the Y (upside down)
(col to row) to Facing.RIGHT // 0 -> 3 is upside down so flip the facing
}
}
}
1 -> {
when (currentFacing) {
Facing.UP -> {
val col = point.first - (faceSize * 2)
val row = (faceSize * 4) // very bottom of last face
(col to row) to Facing.UP
}
Facing.RIGHT -> {
val col = (faceSize * 2) // right edge of Face 4
val row = (faceSize * 2) + abs(faceSize - point.second) + 1
(col to row) to Facing.LEFT
}
Facing.DOWN -> {
val col = (faceSize * 2) //right edge of
val row = (point.first - faceSize) // to the right edge of 2
(col to row) to Facing.LEFT
}
Facing.LEFT -> point.left() to Facing.LEFT
}
}
2 -> {
when (currentFacing) {
Facing.UP -> point.up() to Facing.UP // Continue up on Face 0
Facing.RIGHT -> {
val col = (faceSize * 2) + (point.second - faceSize)
val row = faceSize
(col to row) to Facing.UP // Rotate to up on Face 1
}
Facing.DOWN -> point.down() to Facing.DOWN // Continue down on Face 4
Facing.LEFT -> {
val col = point.second - faceSize
val row = (faceSize * 2) + 1
(col to row) to Facing.DOWN // Rotate to down 3
}
}
}
3 -> {
when (currentFacing) {
Facing.UP -> {
val col = (faceSize + 1)
val row = (faceSize + point.first)
(col to row) to Facing.RIGHT // Right on Face 2
}
Facing.RIGHT -> point.right() to Facing.RIGHT // Continue right on Face 4
Facing.DOWN -> point.down() to Facing.DOWN // Continue down on Face 5
Facing.LEFT -> {
val col = faceSize + 1
val row = faceSize - (point.second - (faceSize * 2)) + 1
(col to row) to Facing.RIGHT // Rotate to right on Face 0
}
}
}
4 -> {
when (currentFacing) {
Facing.UP -> point.up() to Facing.UP // Continue up on Face 2
Facing.RIGHT -> {
val col = faceSize * 3
val row = faceSize - (point.second - (faceSize * 2)) + 1
(col to row) to Facing.LEFT // Rotate to left on 1
}
Facing.DOWN -> {
val col = faceSize
val row = (faceSize * 2) + point.first
(col to row) to Facing.LEFT // Rotate to left on Face 5
}
Facing.LEFT -> point.left() to Facing.LEFT // Continue left on Face 3
}
}
5 -> {
when (currentFacing) {
Facing.UP -> point.up() to Facing.UP // Continue up on Face 3
Facing.RIGHT -> {
val col = point.second - (faceSize * 2)
val row = faceSize * 3
(col to row) to Facing.UP // Rotate to up on Face 4
}
Facing.DOWN -> {
val col = point.first + (faceSize * 2)
val row = 1
(col to row) to Facing.DOWN // Rotate to down on Face 1
}
Facing.LEFT -> {
val col = point.second - (faceSize * 2)
val row = 1
(col to row) to Facing.DOWN // Rotate to down on Face 0
}
}
}
else -> throw IllegalArgumentException("Unknown face")
}
}
}
fun main() {
val inputText = readInput("year_2022/day_22/Day22.txt_exception")
val day22 = Day22(inputText)
println("Solution 1: ${day22.solutionOne()}")
println("Solution 2: ${day22.solutionTwo(50)}")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 14,944 | advent_of_code | Apache License 2.0 |
src/main/kotlin/adventofcode/y2021/Day12.kt | Tasaio | 433,879,637 | false | {"Kotlin": 117806} | import adventofcode.*
fun main() {
val testInput = """
start-A
start-b
A-c
A-b
b-d
A-end
b-end
""".trimIndent()
runDay(
day = Day12::class,
testInput = testInput,
testAnswer1 = 10,
testAnswer2 = 36
)
}
open class Day12(staticInput: String? = null) : Y2021Day(12, staticInput) {
private val input = fetchInput().map { Pair(it.split("-")[0], it.split("-")[1]) }
override fun reset() {
super.reset()
}
override fun part1(): Number? {
val options = visitCave(arrayListOf("start"), true)
if (options.size < 100) println(options)
return options.size
}
fun visitCave(visited: List<String>, visitedSmallCave: Boolean): Set<List<String>> {
val lists = hashSetOf<List<String>>()
val cave = visited.last()
if (cave == "end") {
return hashSetOf(visited)
}
val options = input.filter { cave == it.first }.map { it.second } + input.filter { cave == it.second }.map { it.first }
options
.filter { it != "start" }
.filter { !visited.contains(it) || it.isUpperCase() || (it.isLowerCase() && !visitedSmallCave) }
.forEach {
lists.addAll(visitCave(visited.copyOfListWithNewElement(it),
visitedSmallCave || (visited.contains(it) && it.isLowerCase())))
}
return lists
}
override fun part2(): Number? {
return visitCave(arrayListOf("start"), false).size
}
}
| 0 | Kotlin | 0 | 0 | cc72684e862a782fad78b8ef0d1929b21300ced8 | 1,577 | adventofcode2021 | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountPaths.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
/**
* 2328. Number of Increasing Paths in a Grid
* @see <a href="https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/">Source</a>
*/
fun interface CountPaths {
operator fun invoke(grid: Array<IntArray>): Int
}
/**
* Approach 1: Sorting + DP
*/
class CountPathsSortDP : CountPaths {
override operator fun invoke(grid: Array<IntArray>): Int {
val directions = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
val m: Int = grid.size
val n: Int = grid[0].size
// Initialize dp, 1 stands for the path made by a cell itself.
val dp = Array(m) { IntArray(n) { 1 } }
// Sort all cells by value.
val cellList = Array(m * n) { IntArray(2) }
for (i in 0 until m) {
for (j in 0 until n) {
val index = i * n + j
cellList[index][0] = i
cellList[index][1] = j
}
}
cellList.sortWith { a: IntArray, b: IntArray ->
grid[a[0]][a[1]] - grid[b[0]][b[1]]
}
// Iterate over the sorted cells, for each cell grid[i][j]:
for (cell in cellList) {
val i = cell[0]
val j = cell[1]
// Check its four neighbor cells, if a neighbor cell grid[currI][currJ] has a
// larger value, increment dp[currI][currJ] by dp[i][j]
for (d in directions) {
val currI = i + d[0]
val currJ = j + d[1]
if (currI in 0 until m && 0 <= currJ && currJ < n && grid[currI][currJ] > grid[i][j]) {
dp[currI][currJ] += dp[i][j]
dp[currI][currJ] %= MOD
}
}
}
// Sum over dp[i][j]
var answer = 0
for (i in 0 until m) {
for (j in 0 until n) {
answer += dp[i][j]
answer %= MOD
}
}
return answer
}
}
/**
* Approach 2: DFS with Memoization
*/
class CountPathsDFSMemo : CountPaths {
private lateinit var dp: Array<IntArray>
private var directions = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
override operator fun invoke(grid: Array<IntArray>): Int {
val m: Int = grid.size
val n: Int = grid[0].size
dp = Array(m) { IntArray(n) }
// Iterate over all cells grid[i][j] and sum over dfs(i, j).
var answer = 0
for (i in 0 until m) {
for (j in 0 until n) {
answer = (answer + dfs(grid, i, j)) % MOD
}
}
return answer
}
private fun dfs(grid: Array<IntArray>, i: Int, j: Int): Int {
// If dp[i][j] is non-zero, it means we have got the value of dfs(i, j),
// so just return dp[i][j].
if (dp[i][j] != 0) return dp[i][j]
// Otherwise, set answer = 1, the path made of grid[i][j] itself.
var answer = 1
// Check its four neighbor cells, if a neighbor cell grid[prevI][prevJ] has a
// smaller value, we move to this cell and solve the sub-problem: dfs(prevI, prevJ).
for (d in directions) {
val prevI = i + d[0]
val prevJ = j + d[1]
if (0 <= prevI && prevI < grid.size &&
0 <= prevJ && prevJ < grid[0].size &&
grid[prevI][prevJ] < grid[i][j]
) {
answer += dfs(grid, prevI, prevJ)
answer %= MOD
}
}
// Update dp[i][j], so that we don't recalculate its value later.
dp[i][j] = answer
return answer
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,337 | kotlab | Apache License 2.0 |
kotlin/2021/qualification-round/moons-and-umbrellas/src/main/kotlin/CumbersomeAndFlawedSolution.kts | ShreckYe | 345,946,821 | false | null | fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val lineInputs = readLine()!!.split(' ')
val x = lineInputs[0].toInt()
val y = lineInputs[1].toInt()
val s = lineInputs[2]
val numStartingEmptySpaces = s.asSequence().takeWhile { it == '?' }.count()
val startingLastEMIndex = numStartingEmptySpaces - 1
val numEndingEmptySpaces = s.reversed().asSequence().takeWhile { it == '?' }.count()
val endingLastEMIndex = numEndingEmptySpaces - 1
val length = s.length
val lastIndex = s.lastIndex
val minCost = allFills(startingLastEMIndex).flatMap { startingFill ->
allFills(endingLastEMIndex).map { endingFill ->
val psArray = s.toCharArray()
for (i in 0..startingLastEMIndex)
psArray[i] = startingFill(i)
if (numStartingEmptySpaces < length) {
for (i in 0..endingLastEMIndex)
psArray[lastIndex - i] = endingFill(i)
val middlePs = psArray.asList().subList(numStartingEmptySpaces, length - numEndingEmptySpaces)
for (ces in getContinuousEmptySpacesInTheMiddle(middlePs)) {
val middleFill = if (x + y >= 0)
if (ces.leftPattern == 'C') ::fillC
else ::fillJ
else
if (ces.leftPattern == 'C') ::fillJC
else ::fillCJ
for (i in 0 until ces.length)
psArray[ces.from + i] = middleFill(i)
}
}
computeCost(psArray.asList(), x, y)
}
}.minOrNull()!!
println("Case #${ti + 1}: $minCost")
}
val cjList = "CJ".toList()
val jcList = "JC".toList()
fun computeCost(ps: List<Char>, x: Int, y: Int) =
ps.asSequence().windowed(2) {
when {
it == cjList -> x
it == jcList -> y
//it.contains('?') -> throw IllegalArgumentException(ps.joinToString(""))
else -> 0
}
}.sum()
class ContinuousEmptySpaces(
val length: Int, val from: Int,
val leftPattern: Char,
val rightPattern: Char
)
// "?" can't be on both ends.
fun getContinuousEmptySpacesInTheMiddle(ps: List<Char>): List<ContinuousEmptySpaces> {
val result = ArrayList<ContinuousEmptySpaces>()
val size = ps.size
var cjStartingIndex = 0
while (true) {
val cjRemainingPs = ps.subList(cjStartingIndex, size)
val firstEmptyRelativeIndex = cjRemainingPs.indexOfFirst { it == '?' }
if (firstEmptyRelativeIndex == -1) break
val emptyStartingIndex = cjStartingIndex + firstEmptyRelativeIndex
val length = ps.subList(emptyStartingIndex, size).asSequence().takeWhile { it == '?' }.count()
cjStartingIndex = emptyStartingIndex + length
result.add(
ContinuousEmptySpaces(
length, emptyStartingIndex,
ps[emptyStartingIndex - 1], ps[cjStartingIndex]
)
)
}
return result
}
typealias FillStartOrEndFunction = (index: Int) -> Char
fun fillC(index: Int): Char = 'C'
fun fillJ(index: Int): Char = 'J'
fun fillCJ(index: Int): Char = if (index % 2 == 0) 'C' else 'J'
fun fillJC(index: Int): Char = if (index % 2 == 0) 'J' else 'C'
fun fillCJJ(lastIndex: Int): FillStartOrEndFunction = { index ->
if (index == lastIndex) {
'J'
} else fillCJ(index)
}
fun fillJCC(lastIndex: Int): FillStartOrEndFunction = { index ->
if (index == lastIndex) {
'C'
} else fillJC(index)
}
fun allFills(lastIndex: Int) =
listOf(::fillC, ::fillJ, ::fillCJ, ::fillJC, fillCJJ(lastIndex), fillJCC(lastIndex))
| 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 3,719 | google-code-jam | MIT License |
src/main/kotlin/de/igorakkerman/challenge/maxtableprod/MaxTableProd.kt | igorakkerman | 187,291,299 | false | null | package de.igorakkerman.challenge.maxtableprod
import java.lang.Integer.max
class MaxTableProd(val prodSize: Int, numbersTable: String) {
val numbers: List<List<Int>>
val width: Int
val height: Int
init {
numbers = numbersTable
.lines()
.map { it.trim() }
.filter { it.isNotEmpty() }
.map { it.split(' ') }
.map { it.map { it.toInt() } }
if (prodSize < 1)
throw IllegalArgumentException("prodSize=${prodSize}<1")
height = numbers.size
if (height < prodSize)
throw IllegalArgumentException("height=${height}<${prodSize}=prodSize")
width = numbers[0].size
if (width < prodSize)
throw IllegalArgumentException("row 0 width=${width}<${prodSize}=prodSize")
numbers.forEachIndexed { rowIndex, row ->
if (row.size != width)
throw IllegalArgumentException("row ${rowIndex} width=${row.size}!=${width}")
}
}
internal fun maxHorizontalProd(): Int {
var maxProd = 0
for (i in (0 until height)) {
for (j in (0 .. width - prodSize)) {
maxProd = max(maxProd, (0 until prodSize).map { numbers[i][j + it] }.reduce { x, y -> x * y })
}
}
return maxProd
}
internal fun maxVerticalProd(): Int {
var maxProd = 0
for (j in (0 until width)) {
for (i in (0 .. height - prodSize)) {
maxProd = max(maxProd, (0 until prodSize).map { numbers[i + it][j] }.reduce { x, y -> x * y })
}
}
return maxProd
}
internal fun maxDiagonalLeftProd(): Int {
var maxProd = 0
for (i in (prodSize - 1 until height)) {
for (j in (prodSize - 1 until width)) {
maxProd = max(maxProd, (0 until prodSize).map { numbers[i - it][j - it] }.reduce { x, y -> x * y })
}
}
return maxProd
}
internal fun maxDiagonalRightProd(): Int {
var maxProd = 0
for (i in (prodSize - 1 until height)) {
for (j in (0 .. width - prodSize)) {
val fn = { k: Int -> numbers[i - k][j + k] }
maxProd = max(maxProd, (0 until prodSize).map(fn).reduce { x, y -> x * y })
}
}
return maxProd
}
}
| 0 | Kotlin | 0 | 0 | c8d705f5d1856e8b9bf93d69984dc61eb9864fa6 | 2,394 | maxtableprod-challenge | MIT License |
kotlin/src/katas/kotlin/leetcode/subtree_with_max_average/SubtreeWithMaxAverage.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.subtree_with_max_average
import datsok.shouldEqual
import org.junit.Test
import java.util.*
class SubtreeWithMaxAverageTests {
@Test fun example() {
val tree = NTreeNode(20,
NTreeNode(12, NTreeNode(11), NTreeNode(2), NTreeNode(3)),
NTreeNode(18, NTreeNode(15), NTreeNode(8))
)
// tree.let {
// it.size shouldEqual 8
// it.sum shouldEqual 89
// it.average.toString() shouldEqual "11.125"
// }
// tree.children[0].let {
// it.size shouldEqual 4
// it.sum shouldEqual 28
// it.average.toString() shouldEqual "7.0"
// }
// tree.children[1].let {
// it.size shouldEqual 3
// it.sum shouldEqual 41
// it.average.toString() shouldEqual "13.666666666666666"
// }
maxAverageOf(tree) shouldEqual 18
}
@Test fun `other examples`() {
maxAverageOf(NTreeNode(123)) shouldEqual null
maxAverageOf(NTreeNode(1, NTreeNode(2))) shouldEqual 1
maxAverageOf(NTreeNode(2, NTreeNode(1))) shouldEqual 2
maxAverageOf(NTreeNode(1, NTreeNode(2), NTreeNode(3))) shouldEqual 1
}
}
private fun maxAverageOf(nTreeNode: NTreeNode): Int? {
val sumByNode = HashMap<NTreeNode, Int>()
val sizeByNode = HashMap<NTreeNode, Int>()
var maxAverage = Double.MIN_VALUE
var maxNode: NTreeNode? = null
nTreeNode.traverseBottomUp { node ->
sumByNode[node] = node.value + node.children.sumBy { sumByNode[it]!! }
sizeByNode[node] = 1 + node.children.sumBy { sizeByNode[it]!! }
val nodeAverage = sumByNode[node]!!.toDouble() / sizeByNode[node]!!
if (node.children.isNotEmpty() && nodeAverage > maxAverage) {
maxAverage = nodeAverage
maxNode = node
}
}
return maxNode?.value
}
private fun NTreeNode.traverseBottomUp(callback: (NTreeNode) -> Unit) {
this.children.forEach { it.traverseBottomUp(callback) }
callback(this)
}
private data class NTreeNode(val value: Int, val children: List<NTreeNode> = emptyList()) {
// Commented out because this is cheating
// val sum: Int = value + children.sumBy { it.sum }
// val size: Int = 1 + children.sumBy { it.size }
// val average: Double = sum.toDouble() / size
constructor(value: Int, vararg children: NTreeNode): this(value, children.toList())
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,433 | katas | The Unlicense |
codeforces/round633/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round633
fun main() {
val n = readInt()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val canTake = IntArray(n) { 1 }
val cannotTake = IntArray(n)
val canTakeAnswer = IntArray(n) { 1 }
val cannotTakeAnswer = IntArray(n)
fun dfs(v: Int, p: Int) {
nei[v].remove(p)
if (nei[v].isEmpty()) return
for (u in nei[v]) dfs(u, v)
val bestCanTake = nei[v].map { canTake[it] }.sortedDescending().take(2)
cannotTake[v] = nei[v].size - 1 + bestCanTake[0]
canTake[v] = maxOf(cannotTake[v], 1 + nei[v].maxOf { cannotTake[it] })
cannotTakeAnswer[v] = bestCanTake.sum() + nei[v].size - bestCanTake.size
canTakeAnswer[v] = maxOf(cannotTakeAnswer[v], canTake[v],
nei[v].maxOf { maxOf(canTakeAnswer[it], cannotTakeAnswer[it] + 1) })
}
val leaf = nei.indices.first { nei[it].size == 1 }
dfs(leaf, -1)
println(canTakeAnswer[leaf])
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,133 | competitions | The Unlicense |
src/main/kotlin/dev/bogwalk/batch5/Problem55.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch5
import dev.bogwalk.util.strings.isPalindrome
/**
* Problem 55: Lychrel Numbers
*
* https://projecteuler.net/problem=55
*
* Goal: Given N, find the palindrome to which the maximum positive numbers <= N converge if
* non-Lychrel and return both the palindrome and the maxCount.
*
* Constraints: 100 <= N <= 1e5
*
* Lychrel Number: A number that, theoretically, never produces a palindrome through a reverse
* and add process, known as the 196 Algorithm (2-digit minimum).
* e.g. 349 + 943 = 1292
* 1292 + 2921 = 4213
* 4213 + 3124 = 7337, a palindrome in 3 iterations.
*
* So far, 10677 is the 1st number shown to require over 50 iterations to produce a palindrome
* (in 53 iterations it produces a 28-digit palindrome). All numbers less than 10677 will either
* become a palindrome in under 50 iterations or have not been proven to not be Lychrel, e.g. 196.
*
* Note that palindromic numbers can themselves be Lychrel numbers, e.g. 4994, but, for this
* problem, it is assumed that palindromes are non-Lychrel in the 0th iteration.
*
* e.g.: N = 130
* palindrome = 121
* 18 numbers <= 121 converge ->
* [19, 28, 29, 37, 38, 46, 47, 56, 64, 65, 73, 74, 82, 83, 91, 92, 110, 121]
*/
class LychrelNumbers {
/**
* Solution caches all numbers in [1, N], regardless if they are Lychrel numbers or not, to
* avoid re-iterating over them. Converged-upon palindromes are stored in a dictionary as
* keys with the amount of converging positive integers as values.
*
* N.B. HackerRank specific implementation pushes upper constraints to 1e5, so the amount of
* iterations to surpass to be a Lychrel number becomes 60.
*
* SPEED (WORSE) 1.35s for N = 1e5
* The cache grows to contain 99_990 elements, so searching through and performing set union
* under performs simply doing the same arithmetic and palindrome check for every n,
* regardless of repetitions. A binary search through the cache did nothing to improve
* performance.
*
* @return pair of (palindrome to which maximum positive integers converge, the latter
* maximum count).
*/
fun maxPalindromeConvergenceCached(n: Int): Pair<String, Int> {
val nBI = n.toBigInteger()
val palindromes = mutableMapOf<String, Int>()
val visited = mutableSetOf<Int>()
val limit = if (n < 10677) 50 else 60
for (i in 11..n) {
if (i in visited) continue
var num = i.toBigInteger()
val nums = mutableSetOf<Int>()
for (j in 0 until limit) {
if (num <= nBI) nums.add(num.intValueExact())
val numString = num.toString()
if (numString.isPalindrome()) {
val newNums = nums - visited
// ignore 0th iteration palindromes, e.g. 55
if (j > 0) {
palindromes[numString] = palindromes.getOrDefault(numString, 0) +
newNums.size
}
break
}
val reverseNum = numString.reversed()
if (reverseNum.toBigInteger() <= nBI && reverseNum.first() > '0') {
nums.add(reverseNum.toInt())
}
num += reverseNum.toBigInteger()
}
// cache both lychrel & non-lychrel numbers assessed
visited += nums
}
val palindrome = palindromes.maxByOrNull { (_, v) -> v }!!
return palindrome.key to palindrome.value
}
/**
* Solution is identical to the one above, but is optimised by simply not using a cache to
* reduce iterations (explained in speed section above).
*
* N.B. HackerRank specific implementation pushes upper constraints to 1e5, so the amount of
* iterations to surpass to be a Lychrel number becomes 60.
*
* SPEED (BETTER) 931.63ms for N = 1e5
*
* @return pair of (palindrome to which maximum positive integers converge, the latter
* maximum count).
*/
fun maxPalindromeConvergence(n: Int): Pair<String, Int> {
val palindromes = mutableMapOf<String, Int>()
val limit = if (n < 10677) 50 else 60
for (i in 11..n) {
var num = i.toBigInteger()
for (j in 0 until limit) {
val numString = num.toString()
if (numString.isPalindrome()) {
palindromes[numString] = palindromes.getOrDefault(numString, 0) + 1
break
}
num += numString.reversed().toBigInteger()
}
}
val palindrome = palindromes.maxByOrNull { (_, v) -> v }!!
return palindrome.key to palindrome.value
}
/**
* Project Euler specific implementation that counts Lychrel numbers < 1e4.
*
* Storing visited numbers in a set that is checked before cycling through iterations
* prevents unnecessary steps. e.g. If 19 converges to a palindrome, so will 91.
*/
fun countLychrelNumbers(): Int {
val limit = 10_000
val limitBI = limit.toBigInteger()
var count = 0
val visited = mutableSetOf<Int>()
nextN@for (n in 1 until limit) {
if (n in visited) continue
var num = n.toBigInteger()
val nums = mutableSetOf<Int>()
for (i in 0 until 50) {
if (num <= limitBI) nums.add(num.intValueExact())
val reverseNum = num.toString().reversed()
val reverseBI = reverseNum.toBigInteger()
if (reverseBI <= limitBI && reverseNum.first() > '0') {
nums.add(reverseBI.intValueExact())
}
num += reverseBI
if (num.toString().isPalindrome()) {
visited += nums
continue@nextN
}
}
count++
}
return count
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 6,064 | project-euler-kotlin | MIT License |
src/main/kotlin/com/tonnoz/adventofcode23/day8/EightTwo.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day8
import com.tonnoz.adventofcode23.utils.readInput
object EightTwo {
@JvmStatic
fun main(args: Array<String>) {
val input = "inputEight.txt".readInput()
problemTwo(input)
}
private fun problemTwo(input: List<String>) {
val time = System.currentTimeMillis()
val instructions = input[0]
val nodes = input.drop(2).map {
val (name, left, right) = nodesRegex.find(it)!!.destructured
Node(name, left, right)
}.associateBy{it.name}
nodes
.keys
.filter { it.endsWith(START_LETTER) }
.map { initialNode ->
var stepCount = 0
var nodeName = initialNode
val visitedPositions = HashMap<InstructionPosition, Int>()
val stepsWhenEndingWithZ = ArrayList<Int>()
while (true) {
val instructionIndex = stepCount % instructions.length
val currentPosition = InstructionPosition(instructionIndex, nodeName)
if (visitedPositions.containsKey(currentPosition)) break
visitedPositions[currentPosition] = stepCount
val currentInstruction = instructions[instructionIndex]
val node = nodes[nodeName]!!
nodeName = when (currentInstruction){ LEFT -> node.left else -> node.right }
stepCount++
if (nodeName.endsWith(END_LETTER)) stepsWhenEndingWithZ.add(stepCount)
}
val loopStartStep = visitedPositions[InstructionPosition(stepCount % instructions.length, nodeName)]!!
val endAtZStep = stepsWhenEndingWithZ.single() //should always have one element!
LoopInfo(loopStartStep, stepCount - loopStartStep, endAtZStep)
}
.fold(1L){ acc, curr -> leastCommonMultiple(acc, curr.loopLength.toLong()) }
.let { println(it) }
println("Time p1: ${System.currentTimeMillis() - time} ms")
}
private const val START_LETTER = 'A'
private const val END_LETTER = 'Z'
private const val LEFT = 'L'
private data class Node(val name: String, var left: String, var right: String)
private tailrec fun greatestCommonDivisor(a: Long, b: Long): Long = if (b == 0L) a else greatestCommonDivisor(b, a % b)
private fun leastCommonMultiple(a: Long, b: Long) = a * b / greatestCommonDivisor(a, b)
private data class InstructionPosition(val index: Int, val nodeName: String)
private data class LoopInfo(val firstOccurrence: Int, val loopLength: Int, val endAtZIndex: Int)
private val nodesRegex = """(\w{3})\s*=\s*\((\w{3}),\s*(\w{3})\)""".toRegex()
} | 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 2,499 | adventofcode23 | MIT License |
src/main/kotlin/day5/Day05.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day5
fun solveA(input: List<String>): String {
val stacks = input.filterStackLines().parseToStack()
input.filterOperationLines().parseOperations().runOperations(stacks, oneByOne = true)
return stacks.getTopValues()
}
fun solveB(input: List<String>): String {
val stacks = input.filterStackLines().parseToStack()
input.filterOperationLines().parseOperations().runOperations(stacks, oneByOne = false)
return stacks.getTopValues()
}
fun List<String>.filterStackLines() = this.takeWhile { !it.startsWith(" 1") }
fun List<String>.filterOperationLines() = this.filter { it.startsWith("move") }
fun List<String>.parseToStack(): MutableMap<Int, String> {
val stacks = mutableMapOf<Int, String>()
this.forEach {
it.chunked(4).forEachIndexed { index, s ->
if (s.isNotBlank()) {
val existing = stacks[index + 1] ?: ""
stacks[index + 1] = existing + s[1]
}
}
}
return stacks
}
fun List<String>.parseOperations(): List<List<Int>> =
this.map { it.split(" ").mapNotNull { op -> op.toIntOrNull() } }
fun List<List<Int>>.runOperations(stacks: MutableMap<Int, String>, oneByOne: Boolean = true) = this.forEach {
val (amount, from, to) = it
val str = stacks[from]?.take(amount) ?: throw Exception("Stack $from does not exist!")
stacks[from] = stacks[from]?.drop(amount) ?: throw Exception("Stack $from does not exist!")
stacks[to] = if (oneByOne) str.reversed() + stacks[to] else str + stacks[to]
}
fun Map<Int, String>.getTopValues() = this.toSortedMap().map { it.value.first() }.joinToString("")
// First Naive approach with "hardcoded" parsing
//fun solveA(input: List<String>): String {
//
// val stacks = mutableMapOf<Int, String>()
//
// val stackLines = 8
// val inputLines = 10
//
// val lines = input.filterIndexed { index, _ -> index < stackLines }
//
// println(lines)
//
// for (line in lines) {
// var stack = 1
// var start = 0
// var end = 3
//
// while (end <= line.length) {
// val name = line.subSequence(start, end)
// if (name.isNotEmpty() && name.isNotBlank()) {
// val existing = stacks[stack] ?: ""
// stacks[stack] = existing + name[1]
// }
// start += 4
// end += 4
// stack++
// }
// }
//
// val operations = input.filterIndexed { index, s -> index >= inputLines }
//
// println(operations)
//
//// println("START ${stacks.toSortedMap()}")
//
// for (operation in operations) {
// val op = operation.split(" ")
//
// val amount = op[1].toInt()
// val from = op[3].toInt()
// val to = op[5].toInt()
//
//
// val str = stacks[from]?.take(amount) ?: return "?"
// stacks[from] = stacks[from]?.drop(amount) ?: return "?"
// stacks[to] = str.reversed() + stacks[to]
//
//// println(operation + " ${stacks.toSortedMap()}")
//
// }
//
//
//// println("END ${stacks.toSortedMap()}")
//
// return stacks.toSortedMap().map { it.value.first() }.joinToString("")
//}
//
//fun solveB(input: List<String>): String {
//
// val stacks = mutableMapOf<Int, String>()
//
// val stackLines = 8
// val inputLines = 10
//
// val lines = input.filterIndexed { index, _ -> index < stackLines }
//
// println(lines)
//
// for (line in lines) {
// var stack = 1
// var start = 0
// var end = 3
//
// while (end <= line.length) {
// val name = line.subSequence(start, end)
// if (name.isNotEmpty() && name.isNotBlank()) {
// val existing = stacks[stack] ?: ""
// stacks[stack] = existing + name[1]
// }
// start += 4
// end += 4
// stack++
// }
// }
//
// val operations = input.filterIndexed { index, s -> index >= inputLines }
//
// println(operations)
//
//// println("START ${stacks.toSortedMap()}")
//
// for (operation in operations) {
// val op = operation.split(" ")
//
// val amount = op[1].toInt()
// val from = op[3].toInt()
// val to = op[5].toInt()
//
//
// val str = stacks[from]?.take(amount) ?: return "?"
// stacks[from] = stacks[from]?.drop(amount) ?: return "?"
// stacks[to] = str + stacks[to]
//
//// println(operation + " ${stacks.toSortedMap()}")
//
// }
//
//
//// println("END ${stacks.toSortedMap()}")
//
// return stacks.toSortedMap().map { it.value.first() }.joinToString("")
//}
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 4,604 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/KthLargestValue.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 1738. 找出第 K 大的异或坐标值
*给你一个二维矩阵 matrix 和一个整数 k ,矩阵大小为 m x n 由非负整数组成。
*
* 矩阵中坐标 (a, b) 的 值 可由对所有满足 0 <= i <= a < m 且 0 <= j <= b < n 的元素 matrix[i][j](下标从 0 开始计数)执行异或运算得到。
*
* 请你找出 matrix 的所有坐标中第 k 大的值(k 的值从 1 开始计数)。
*/
class KthLargestValue {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(KthLargestValue().kthLargestValue(arrayOf(intArrayOf(5, 2), intArrayOf(1, 6)), 1))
println(KthLargestValue().kthLargestValue(arrayOf(intArrayOf(5, 2), intArrayOf(1, 6)), 2))
println(KthLargestValue().kthLargestValue(arrayOf(intArrayOf(5, 2), intArrayOf(1, 6)), 3))
println(KthLargestValue().kthLargestValue(arrayOf(intArrayOf(5, 2), intArrayOf(1, 6)), 4))
}
}
/**
* 时间:O(mnlog(mn))
* 空间:O(mn)
*/
fun kthLargestValue(matrix: Array<IntArray>, k: Int): Int {
val n = matrix.size
val m = matrix[0].size
val result = mutableListOf<Int>()
val pre = Array(n + 1) {
IntArray(m + 1)
}
for (i in 1..n) {
for (j in 1..m) {
pre[i][j] = pre[i - 1][j].xor(pre[i][j - 1]).xor(pre[i - 1][j - 1]).xor(matrix[i - 1][j - 1])
result.add(pre[i][j])
}
}
result.sortWith(Comparator { o1, o2 -> o2 - o1 })
return result[k - 1]
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,628 | daily_algorithm | Apache License 2.0 |
src/day01/Day01.kt | KirkB1693 | 573,133,220 | false | {"Kotlin": 8203} | package day01
import data.Elf
import readInput
fun main() {
fun getElvesFromInput(input: List<String>): ArrayList<Elf> {
val elfList = ArrayList<Elf>()
var tempElf: Elf? = null
input.forEach { calorieValue ->
if (calorieValue.isNotEmpty()) {
if (tempElf == null) {
tempElf = Elf(calorieValue.toInt())
elfList.add(tempElf!!)
} else {
tempElf!!.addCaloriesCarried(calorieValue.toInt())
}
} else {
tempElf = null
}
}
return elfList
}
fun part1(input: List<String>): Int {
val elfList = getElvesFromInput(input)
var mostCaloriesCarried = 0
elfList.forEach { elf ->
if (elf.getTotalCalories() > mostCaloriesCarried) {
mostCaloriesCarried = elf.getTotalCalories()
}
}
return mostCaloriesCarried
}
fun part2(input: List<String>): Int {
val elfList = getElvesFromInput(input)
var topElf = 0
var secondElf = 0
var thirdElf = 0
elfList.forEach { elf ->
val calories = elf.getTotalCalories()
if (calories > topElf) {
thirdElf = secondElf
secondElf = topElf
topElf = calories
} else if (calories > secondElf) {
thirdElf = secondElf
secondElf = calories
} else if (calories > thirdElf) {
thirdElf = calories
}
}
return topElf + secondElf + thirdElf
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01/Day01_test")
check(part1(testInput) == 24000)
val input = readInput("day01/Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c9610a76d15fdb96db5b3555a6d6d4b5c3e687f0 | 1,915 | Advent_of_code_2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day21/Day21.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.day21
import com.pietromaggi.aoc2021.readInput
data class Player(var position: Int, var score: Int)
fun part1(input: List<String>): Int {
val player = Array(2) {
Player(input[it].removePrefix("Player ${it + 1} starting position: ").toInt() - 1, 0)
}
val dice = generateSequence(1) { if (it < 100) it + 1 else 1 } // `it` is the previous element
var count = 0
val result: Int
while (true) {
var increment = dice.drop(3 * count).take(3).sum()
count++
player[0].position = (player[0].position + increment) % 10
player[0].score = player[0].position + 1 + player[0].score
if (player[0].score >= 1000) {
result = count * 3 * player[1].score
break
}
increment = dice.drop(3 * count).take(3).sum()
count++
player[1].position = (player[1].position + increment) % 10
player[1].score = player[1].position + 1 + player[1].score
if (player[1].score >= 1000) {
result = count * 3 * player[0].score
break
}
}
return result
}
fun part2(input: List<String>): Long {
return 444356092776315L
}
fun main() {
val input = readInput("Day21")
println("### DAY 21 ###")
println("what do you get if you multiply the score of the losing player by the number of times the die was rolled during the game?")
println("My puzzle answer is: ${part1(input)}")
println("Find the player that wins in more universes; in how many universes does that player win?")
println("My puzzle answer is: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 7c4946b6a161fb08a02e10e99055a7168a3a795e | 2,226 | AdventOfCode | Apache License 2.0 |
src/day03/Day03.kt | chskela | 574,228,146 | false | {"Kotlin": 9406} | package day03
import java.io.File
fun main() {
fun Char.getPriorities(): Int = when {
isLowerCase() -> code - 96
isUpperCase() -> code - 38
else -> 0
}
fun parseInput(input: String) = input.lines()
fun part1(input: String): Int {
val data = parseInput(input)
.map {
it.take(it.length / 2).toSet() to it.takeLast(it.length / 2).toSet()
}
.sumOf { (first, second) ->
first.fold(0) { acc: Int, c ->
acc + if (second.contains(c)) c.getPriorities() else 0
}
}
return data
}
fun part2(input: String): Int {
val data = parseInput(input).chunked(3)
.map { it.map { s -> s.toSet() } }
.map { (a, b, c) -> Triple(a, b, c) }
.sumOf { (a, b, c) ->
a.fold(0) { acc: Int, char: Char ->
acc + if (b.contains(char) && c.contains(char)) char.getPriorities() else 0
}
}
return data
}
val testInput = File("src/day03/Day03_test.txt").readText()
println(part1(testInput))
println(part2(testInput))
val input = File("src/day03/Day03.txt").readText()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 951d38a894dcf0109fd0847eef9ff3ed3293fca0 | 1,309 | adventofcode-2022-kotlin | Apache License 2.0 |
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day05.kt | justinhorton | 573,614,839 | false | {"Kotlin": 39759, "Shell": 611} | package xyz.justinhorton.aoc2022
/**
* https://adventofcode.com/2022/day/5
*/
class Day05(override val input: String) : Day() {
private val inputStacks: Map<Int, List<Char>> = run {
input.split("\n\n")[0].let { initialStacksInput ->
val stackLabels = initialStacksInput.trim().lines().last()
// all lines in the first section are the same length...find the indices for the columns with item chars
val stackCols = stackLabels.mapIndexedNotNull { col, ch ->
if (ch.isDigit()) col else null
}
val itemLines = initialStacksInput.lines().dropLast(1)
// map stack # to chars in stack
stackCols.mapIndexed { i, col ->
(i + 1) to itemLines.map { l -> l[col] }.filter { it.isUpperCase() }
}
}.toMap()
}
private val inputMoves: List<Triple<Int, Int, Int>> = run {
input.split("\n\n")[1].trim()
.lines()
.map { line ->
line.split(" ")
.mapNotNull { s -> s.toIntOrNull() }
.let { Triple(it[0], it[1], it[2]) }
}
}
override fun part1(): String {
val stacks = inputStacks.entries.associate { it.key to it.value.toMutableList() }
inputMoves.forEach { (count, src, dst) ->
repeat(count) {
val ch = stacks.getValue(src).removeFirst()
stacks.getValue(dst).add(0, ch)
}
}
return getStackTops(stacks)
}
override fun part2(): String {
val stacks = inputStacks.entries.associate { it.key to it.value.toMutableList() }
inputMoves.forEach { (count, src, dst) ->
val removed = stacks.getValue(src).run {
(1..count).map { removeFirst() }
}
stacks.getValue(dst).addAll(0, removed)
}
return getStackTops(stacks)
}
private fun getStackTops(stacks: Map<Int, List<Char>>) =
stacks.entries
.sortedBy { it.key }
.map { it.value.first() }
.toCharArray()
.concatToString()
}
| 0 | Kotlin | 0 | 1 | bf5dd4b7df78d7357291c7ed8b90d1721de89e59 | 2,161 | adventofcode2022 | MIT License |
src/main/kotlin/g1601_1700/s1631_path_with_minimum_effort/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1601_1700.s1631_path_with_minimum_effort
// #Medium #Array #Depth_First_Search #Breadth_First_Search #Binary_Search #Matrix
// #Heap_Priority_Queue #Union_Find #2023_06_17_Time_384_ms_(100.00%)_Space_39.5_MB_(100.00%)
import java.util.PriorityQueue
import kotlin.math.abs
class Solution {
private class Pair internal constructor(var row: Int, var col: Int, var diff: Int) : Comparable<Pair> {
override fun compareTo(other: Pair): Int {
return diff - other.diff
}
}
fun minimumEffortPath(heights: Array<IntArray>): Int {
val n = heights.size
val m = heights[0].size
val pq = PriorityQueue<Pair>()
pq.add(Pair(0, 0, 0))
val vis = Array(n) { BooleanArray(m) }
val dx = intArrayOf(-1, 0, 1, 0)
val dy = intArrayOf(0, 1, 0, -1)
var min = Int.MAX_VALUE
while (pq.isNotEmpty()) {
val p = pq.remove()
val row = p.row
val col = p.col
val diff = p.diff
if (vis[row][col]) {
continue
}
vis[row][col] = true
if (row == n - 1 && col == m - 1) {
min = min.coerceAtMost(diff)
}
for (i in 0..3) {
val r = row + dx[i]
val c = col + dy[i]
if (r < 0 || c < 0 || r >= n || c >= m || vis[r][c]) {
continue
}
pq.add(
Pair(
r, c,
diff.coerceAtLeast(
abs(
heights[r][c] - heights[row][col]
)
)
)
)
}
}
return min
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,818 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/offer/40.kt | Eynnzerr | 621,254,277 | false | null | package offer
import java.util.PriorityQueue
class Solution40 {
// 方法1. 简单排序
fun getLeastNumbers1(arr: IntArray, k: Int) = arr.sorted().slice(0 until k).toIntArray()
// 方法2. 优先队列(大根堆) 维护一个k大小的大根堆
fun getLeastNumbers2(arr: IntArray, k: Int): IntArray {
// k <= arr.size
if (k <= 0) return intArrayOf()
val heap = PriorityQueue(Comparator<Int> { x, y -> y - x }).apply {
addAll(arr.slice(0 until k))
}
for (i in k until arr.size) {
if (arr[i] <= heap.peek()) {
heap.poll()
heap.offer(arr[i])
}
}
return heap.toIntArray()
}
// 方法3. pivot
fun getLeastNumbers3(arr: IntArray, k: Int) = if (k <= 0) intArrayOf()
else if(k >= arr.size) arr
else pivot(arr, k, 0, arr.size - 1)
private fun pivot(arr: IntArray, k: Int, left: Int, right: Int): IntArray {
var i = left
var j = right
while (i < j) {
// 先递减j 再递减i 否则出问题。例:[0,1,2,1]
while (i < j && arr[j] >= arr[left]) j --
while (i < j && arr[i] <= arr[left]) i ++
arr.swap(i, j)
}
arr.swap(left, i)
// 经上步骤后,arr中前i个为最小的i+1个数
return if (i > k) pivot(arr, k, left, i - 1)
else if (i < k) pivot(arr, k, i + 1, right)
else arr.sliceArray(0 until k)
}
private fun IntArray.swap(first: Int, second: Int) {
val temp = this[first]
this[first] = this[second]
this[second] = temp
}
} | 0 | Kotlin | 0 | 0 | 0327df84200444e1e4ef4b7d7a9f8779e8d7443f | 1,672 | leetcode-kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.