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/ru/timakden/aoc/year2016/Day01.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2016
import ru.timakden.aoc.util.Point
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
import ru.timakden.aoc.year2016.Day01.Direction.*
import kotlin.math.abs
/**
* [Day 1: No Time for a Taxicab](https://adventofcode.com/2016/day/1).
*/
object Day01 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2016/Day01").single()
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: String): Int {
var x = 0
var y = 0
var direction = NORTH
input.split(", ").forEach { instruction ->
val numberOfBlocks = instruction.substring(1).toInt()
direction = direction.turn(instruction.first())
when (direction) {
NORTH -> x += numberOfBlocks
SOUTH -> x -= numberOfBlocks
EAST -> y -= numberOfBlocks
WEST -> y += numberOfBlocks
}
}
return abs(x) + abs(y)
}
fun part2(input: String): Int {
var x = 0
var y = 0
var direction = NORTH
val coordinates = mutableListOf<Point>()
input.split(", ").forEach { instruction ->
val numberOfBlocks = instruction.substring(1).toInt()
direction = direction.turn(instruction.first())
repeat(numberOfBlocks) {
when (direction) {
NORTH -> x++
SOUTH -> x--
EAST -> y--
WEST -> y++
}
if (Point(x, y) in coordinates) return abs(x) + abs(y)
coordinates += Point(x, y)
}
}
return 0
}
private enum class Direction {
NORTH, SOUTH, EAST, WEST;
fun turn(turnTo: Char) = when (turnTo) {
'L' -> {
when (this) {
NORTH -> WEST
SOUTH -> EAST
EAST -> NORTH
WEST -> SOUTH
}
}
'R' -> {
when (this) {
NORTH -> EAST
SOUTH -> WEST
EAST -> SOUTH
WEST -> NORTH
}
}
else -> error("Unsupported direction")
}
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,453 | advent-of-code | MIT License |
app/src/main/kotlin/co/netguru/android/carrecognition/common/MultimapExt.kt | netguru | 135,276,208 | false | null | typealias Multimap<K, V> = Map<K, List<V>>
fun <K, V> Multimap<K, V>.partition(
predicate: (V) -> Boolean
): Pair<Multimap<K, V>, Multimap<K, V>> {
val first = mutableMapOf<K, List<V>>()
val second = mutableMapOf<K, List<V>>()
for (k in this.keys) {
val (firstValuePartition, secondValuePartition) = this[k]!!.partition(predicate)
first[k] = firstValuePartition
second[k] = secondValuePartition
}
return Pair(first, second)
}
fun <K, V> Multimap<K, V>.toPairsList(): List<Pair<K, V>> = this.flatMap { (k, v) ->
v.map { k to it }
}
fun <K, V> Multimap<K, V>.flattenValues() = this.values.flatten()
operator fun <K, V> Multimap<K, V>.plus(pair: Pair<K, V>): Multimap<K, V> = if (this.isEmpty()) {
mapOf(pair.first to listOf(pair.second))
} else {
val mutableMap = this.toMutableMap()
val keyValues = mutableMap[pair.first]
if (keyValues == null) {
mutableMap[pair.first] = listOf(pair.second)
} else {
mutableMap[pair.first] = keyValues + listOf(pair.second)
}
mutableMap.toMap()
}
operator fun <K, V> Multimap<K, V>.minus(pair: Pair<K, V>): Multimap<K, V> = if (this.isEmpty()) {
emptyMap()
} else {
val valuesForKey = this[pair.first]
?.filter { it != pair.second }
?.let { if (it.isEmpty()) null else it }
if (valuesForKey == null) {
this.filterKeys { it == pair.first }
} else {
this.toMutableMap().apply {
this[pair.first] = valuesForKey - pair.second
}
.toMap()
}
}
fun <K, V> List<Pair<K, V>>.toMultiMap(): Multimap<K, V> {
var result = mapOf<K, List<V>>()
forEach {
result += it
}
return result
}
fun <K, V, I> List<I>.toMultiMap(mapper: (I) -> Pair<K, V>): Multimap<K, V> {
var result = mapOf<K, List<V>>()
forEach {
result += mapper(it)
}
return result
}
| 0 | Kotlin | 8 | 24 | 321fa52c5cc0a339b27737b626163f8f72348cd9 | 1,898 | CarLens-Android | Apache License 2.0 |
src/main/kotlin/_2022/Day22.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readGroupedInput
import kotlin.math.absoluteValue
fun main() {
val directions = listOf(
Pair(0, 1), //right
Pair(1, 0), // bottom
Pair(0, -1), // left
Pair(-1, 0), // top
)
fun getNextDirection(currentDirection: Pair<Int, Int>, rotate: Char): Pair<Int, Int> {
return when (rotate) {
'R' -> directions[(directions.indexOf(currentDirection) + 1).mod(4)]
'L' -> directions[(directions.indexOf(currentDirection) - 1).mod(4).absoluteValue]
else -> currentDirection
}
}
fun isWall(map: List<String>, position: Pair<Int, Int>): Boolean {
return map[position.first][position.second] == '#'
}
fun isAir(map: List<String>, position: Pair<Int, Int>): Boolean {
return position.first < 0 || map.size <= position.first
|| position.second < 0 || map[position.first].length <= position.second
|| map[position.first][position.second] == ' '
}
fun part1(input: List<List<String>>): Int {
val (map, movementList) = input
var movementStr = movementList.first()
var position = Pair(0, map.first().indexOf('.'))
var direction = directions.first()
while (movementStr.isNotEmpty()) {
var indexOfRotation = movementStr.indexOfFirst { !it.isDigit() }
if (indexOfRotation == -1) {
indexOfRotation = movementStr.length - 1
}
val currentMovement = movementStr.substring(0, indexOfRotation + 1)
val steps = currentMovement.takeWhile { it.isDigit() }.toInt()
repeat(steps) {
var nextPosition = Pair(
(position.first + direction.first).mod(map.size),
(position.second + direction.second).mod(map[position.first].length)
)
while (isAir(map, nextPosition)) {
nextPosition = Pair(
(nextPosition.first + direction.first).mod(map.size),
(nextPosition.second + direction.second).mod(map[position.first].length)
)
}
if (!isWall(map, nextPosition)) {
position = nextPosition
}
}
if (!currentMovement.last().isDigit()) {
direction = getNextDirection(direction, currentMovement.last())
}
movementStr = movementStr.drop(indexOfRotation + 1)
}
return 1000 * (position.first + 1) + 4 * (position.second + 1) + directions.indexOf(direction)
}
// value - top left corner of zone
fun buildZonesFromMap(map: List<String>, step: Int): Map<Char, Pair<Int, Int>> {
var key = 'a'
val zones = mutableMapOf<Char, Pair<Int, Int>>()
for (i in map.indices step step) {
for (j in 0 until map[i].length step step) {
if (!isAir(map, Pair(i, j))) {
zones[key] = Pair(i, j)
key++
}
}
}
return zones;
}
// todo hardcoded
fun buildTeleports(
zones: Map<Char, Pair<Int, Int>>,
test: Boolean
): Map<Pair<Char, Pair<Int, Int>>, Pair<Char, Pair<Int, Int>>> {
var right = directions[0]
var bottom = directions[1]
var left = directions[2]
var top = directions[3]
// aaaa
// aaaa
// aaaa
// aaaa
//bbbbccccdddd
//bbbbccccdddd
//bbbbccccdddd
//bbbbccccdddd
// eeeeffff
// eeeeffff
// eeeeffff
// eeeeffff
val teleports = mutableMapOf<Pair<Char, Pair<Int, Int>>, Pair<Char, Pair<Int, Int>>>()
if (test) {
teleports[Pair('a', right)] = Pair('f', left)
teleports[Pair('a', top)] = Pair('b', bottom)
teleports[Pair('a', left)] = Pair('c', bottom)
teleports[Pair('b', top)] = Pair('a', bottom)
teleports[Pair('b', left)] = Pair('f', top)
teleports[Pair('b', bottom)] = Pair('e', top)
teleports[Pair('c', top)] = Pair('a', right)
teleports[Pair('c', bottom)] = Pair('f', right)
teleports[Pair('d', right)] = Pair('f', bottom)
teleports[Pair('e', left)] = Pair('c', top)
teleports[Pair('e', bottom)] = Pair('b', top)
teleports[Pair('f', top)] = Pair('d', left)
teleports[Pair('f', right)] = Pair('a', left)
teleports[Pair('f', bottom)] = Pair('b', right)
} else {
teleports[Pair('a', left)] = Pair('d', right)
teleports[Pair('a', top)] = Pair('f', right)
teleports[Pair('b', top)] = Pair('f', top)
teleports[Pair('b', right)] = Pair('e', left)
teleports[Pair('b', bottom)] = Pair('c', left)
teleports[Pair('c', left)] = Pair('d', bottom)
teleports[Pair('c', right)] = Pair('b', top)
teleports[Pair('d', left)] = Pair('a', right)
teleports[Pair('d', top)] = Pair('c', right)
teleports[Pair('e', right)] = Pair('b', left)
teleports[Pair('e', bottom)] = Pair('f', left)
teleports[Pair('f', right)] = Pair('e', top)
teleports[Pair('f', left)] = Pair('a', bottom)
teleports[Pair('f', bottom)] = Pair('b', bottom)
}
return teleports
}
fun getZone(zones: Map<Char, Pair<Int, Int>>, position: Pair<Int, Int>, step: Int): Char {
for (zone in zones) {
val startPosition = zone.value
if ((startPosition.first until startPosition.first + step).contains(position.first)
&& (startPosition.second until startPosition.second + step).contains(position.second)
) {
return zone.key
}
}
throw RuntimeException("zone not found")
}
fun part2(input: List<List<String>>, isTest: Boolean): Int {
val (map, movementList) = input
val step = if (isTest) {
4
} else {
50
}
val zones = buildZonesFromMap(map, step)
var teleports = buildTeleports(zones, isTest)
var movementStr = movementList.first()
var position = Pair(0, map.first().indexOf('.'))
var direction = directions.first()
var currentZone = 'a'
val right = directions[0]
val bottom = directions[1]
val left = directions[2]
val top = directions[3]
while (movementStr.isNotEmpty()) {
var indexOfRotation = movementStr.indexOfFirst { !it.isDigit() }
if (indexOfRotation == -1) {
indexOfRotation = movementStr.length - 1
}
val currentMovement = movementStr.substring(0, indexOfRotation + 1)
val steps = currentMovement.takeWhile { it.isDigit() }.toInt()
repeat(steps) {
var nextPosition = Pair(
(position.first + direction.first),
(position.second + direction.second)
)
var nextDirection: Pair<Int, Int>? = null
if (isAir(map, nextPosition)) {
val teleport = teleports[Pair(currentZone, direction)]!!
val currentPositionInZone = when (direction) {
top -> position.second
bottom -> step - position.second.mod(step) - 1
left -> step - position.first.mod(step) - 1
right -> position.first
else -> throw RuntimeException("unknown direction")
}.mod(step)
val nextZone = zones[teleport.first]!!
nextPosition = when (teleport.second) {
top -> Pair(nextZone.first + step - 1, nextZone.second + currentPositionInZone)
bottom -> Pair(nextZone.first, nextZone.second + (step - currentPositionInZone - 1))
left -> Pair(nextZone.first + (step - currentPositionInZone - 1), nextZone.second + step - 1)
right -> Pair(nextZone.first + currentPositionInZone, nextZone.second)
else -> throw RuntimeException("unknown direction")
}
nextDirection = teleport.second
}
if (!isWall(map, nextPosition)) {
position = nextPosition
currentZone = getZone(zones, position, step)
if (nextDirection != null) {
direction = nextDirection
}
}
}
if (!currentMovement.last().isDigit()) {
direction = getNextDirection(direction, currentMovement.last())
}
movementStr = movementStr.drop(indexOfRotation + 1)
}
return 1000 * (position.first + 1) + 4 * (position.second + 1) + directions.indexOf(direction)
}
// test if implementation meets criteria from the description, like:
val testInput = readGroupedInput("Day22_test")
println(part1(testInput))
println(part2(testInput, true))
val input = readGroupedInput("Day22")
println(part1(input))
println(part2(input, false))
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 9,522 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day9.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.getText
import kotlin.math.abs
fun main(){
val input = getText("day9.txt")
println(day9A(input))
println(day9B(input))
}
fun day9A(input: String): Int {
val motions = input.lines()
val head = Knot(0, 0)
val tail = Knot(0, 0)
val tailBeen = mutableSetOf(tail.copy())
motions.forEach {
val (dir, steps) = it.split(" ")
repeat(steps.toInt()) {
head.moveMotion(dir)
tail.follow(head)
tailBeen.add(tail.copy())
}
}
return tailBeen.size
}
fun day9B(input: String): Int {
val motions = input.lines()
val head = Knot(0, 0)
val tails = List(9){ Knot(0, 0) }
val tailBeen = mutableSetOf(tails.last().copy())
motions.forEach {
val (dir, steps) = it.split(" ")
repeat(steps.toInt()) {
head.moveMotion(dir)
(listOf(head) + tails).windowed(2).forEach {(follow, move) ->
move.follow(follow)
}
tailBeen.add(tails.last().copy())
}
}
return tailBeen.size
}
private data class Knot(var x: Int, var y: Int) {
fun follow(other: Knot) {
val distX = other.x - x
val distY = other.y - y
if(abs(distX) > 1) {
x += if(distX > 0) 1 else -1
y += if(distY > 0) 1 else if(distY < 0) -1 else 0
} else if (abs(distY) > 1) {
y += if(distY > 0) 1 else -1
x += if(distX > 0) 1 else if(distX < 0) -1 else 0
}
}
fun moveMotion(dir: String) {
when(dir) {
"R" -> x++
"L" -> x--
"U" -> y--
"D" -> y++
}
}
}
| 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 1,671 | AdventOfCode2022 | MIT License |
src/main/kotlin/adventofcode/PuzzleDay07.kt | MariusSchmidt | 435,574,170 | false | {"Kotlin": 28290} | package adventofcode
import java.io.File
import kotlin.math.*
/**
*
* PART I
* Interestingly enough, for any series of numbers in R^1 the central point that minimizes the sum of distances to each
* other point is the median. In fact "The median minimizes the sum of absolute deviations". Until AoC 2021 I did not
* realize that and wanted to see proof:
*
* A explanatory and a formal proof can be found here https://math.stackexchange.com/questions/113270/the-median-minimizes-the-sum-of-absolute-deviations-the-ell-1-norm
* Also this paper https://tommasorigon.github.io/StatI/approfondimenti/Schwertman1990.pdf gives a similar proof
*
*
* PART II
* Mainly since the answer the first riddle was the median, I guessed, that the second might be the arithmetic average.
* I still search for an explanation why this works and why we need to introduce the +.0.5 variance and why for some
* it works without that adjustment. It might the difference between float and double based calculation
*
*/
class PuzzleDay07 {
fun findMostCentralPointForCrabsToRally(file: File, constantCost: Boolean): Pair<Int, Int> = file.useLines { seq ->
return if (constantCost) findForConstantCostPerDistance(seq)
else findForLinearIncreasingCostPerDistance(seq)
}
private fun findForConstantCostPerDistance(seq: Sequence<String>): Pair<Int, Int> {
val crabPositions = seq.first().split(",").map { it.toInt() }.sorted()
val medianIndex = crabPositions.size / 2
val median = crabPositions[medianIndex]
val sumOfDistances = crabPositions.fold(0) { sum, position -> sum + abs(position - median) }
return median to sumOfDistances
}
private fun findForLinearIncreasingCostPerDistance(seq: Sequence<String>): Pair<Int, Int> {
val crabPositions = seq.first().split(",").map { it.toInt() }
val arithmeticAverage = crabPositions.average()
val lowerBound = (arithmeticAverage - 0.5).roundToInt()
val upperBound = (arithmeticAverage + 0.5).roundToInt()
val resultLowerBound = calculateFuelUsage(crabPositions, lowerBound)
val resultUpperBound = calculateFuelUsage(crabPositions, upperBound)
return if (resultLowerBound.second < resultUpperBound.second) resultLowerBound else resultUpperBound
}
private fun calculateFuelUsage(crabPositions: List<Int>, rallyPoint: Int): Pair<Int, Int> {
val fuelUsed = crabPositions.fold(0) { fuelAggregator, position ->
val distance = abs(position - rallyPoint)
val fuelConsumption = (0..distance).sum()
fuelAggregator + fuelConsumption
}
return rallyPoint to fuelUsed
}
} | 0 | Kotlin | 0 | 0 | 2b7099350fa612cb69c2a70d9e57a94747447790 | 2,696 | adventofcode2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/aoc22/Day10.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc22
import readInput
fun Map<Int, Int>.getSignalStrengthAtCycles(cycles: List<Int>): Int {
var sum = 0
for (cycle in cycles) {
sum += this[cycle]!! * cycle
}
return sum
}
data class Sprite(
var position: Int = 1
) {
fun move(steps: Int) = run {
position += steps
}
fun pixelToRender(cycle: Int): Char {
val pixelPosition = (cycle - 1)
return if (pixelPosition in position - 1..position + 1) '#' else '.'
}
}
data class CRT(
val size: Int = 40,
val sprite: Sprite
) {
val lines = mutableListOf<String>()
private var cycle = 1
private var currentLine = ""
fun draw() {
currentLine += sprite.pixelToRender(cycle)
if (currentLine.length == size) {
lines.add(currentLine)
currentLine = ""
}
cycle = (cycle + 1) % size
}
}
fun day10part1(input: List<String>): Int {
var cycle = 0
var registerX = 1
val valuesAtCycle: MutableMap<Int, Int> = mutableMapOf()
input.forEach {
val ops = it.split(" ")
cycle ++
valuesAtCycle[cycle] = registerX
if (ops[0] == "addx") {
cycle ++
valuesAtCycle[cycle] = registerX
registerX += ops[1].toInt()
}
}
return valuesAtCycle.getSignalStrengthAtCycles(listOf(20, 60, 100, 140, 180, 220))
}
fun day10part2(input: List<String>) {
val sprite = Sprite()
val crt = CRT(sprite = sprite)
input.forEach {
crt.draw()
val ops = it.split(" ")
if (ops[0] == "addx") {
crt.draw()
sprite.move(ops[1].toInt())
}
}
crt.lines.forEach {
println(it)
}
}
fun main() {
val input = readInput("Day10")
println(day10part1(input))
println(day10part2(input))
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 1,835 | advent-of-code | Apache License 2.0 |
aoc-2023/src/main/kotlin/aoc/aoc12.kts | triathematician | 576,590,518 | false | {"Kotlin": 615974} | import aoc.AocParser.Companion.parselines
import aoc.AocRunner
import aoc.chunk
import aoc.print
import aoc.util.getDayInput
val testInput = """
???.### 1,1,3
.??..??...?##. 1,1,3
?#?#?#?#?#?#?#? 1,3,1,6
????.#...#... 4,1,1
????.######..#####. 1,6,5
?###???????? 3,2,1
""".parselines
class Springs(_line: String, val nums: SpringLengths) {
val max = nums.maxOrNull()!!
val line = _line
// small optimization - require . on either side of max run of #s
.replace("?" + "#".repeat(max), "." + "#".repeat(max))
.replace("#".repeat(max) + "?", "#".repeat(max) + ".")
// small optimization - remove redundant .'s
.replace("[.]+".toRegex(), ".")
var print = false
/**
* Track the number of matches for a subset of springs,
* where the first spring in the subset starts at the given column,
* and the remainder have valid locations after that.
*/
val matchTable = (0..nums.size).map { line.map { -1L }.toMutableList() }
/** Easy getter for the table. */
fun matchesOf(springIndex: Int, mustBeAt: Int) = matchTable[springIndex][mustBeAt]
/** Updates the match table. */
fun updateMatchTable(springIndex: Int, mustBeAt: Int, count: Long) = count.also {
if (print && count > 0)
println("There are $count arrangements with Spring${springIndex} occurring at $mustBeAt")
matchTable[springIndex][mustBeAt] = count
}
/** Global number of arrangements. */
fun arrangements(): Long {
if (print) println("Calculating arrangements for $line")
val firstHash = line.indexOf('#').let { if (it < 0) line.length else it }
val res = (0..minOf(firstHash, maxLocsPerSpring[0])).sumOf {
calcMatchesOf(springIndex = 0, mustBeAt = it)
}
if (print)
println("There are $res arrangements for $line")
return res
}
fun calcMatchesOf(springIndex: Int, mustBeAt: Int): Long {
// use cached value if possible
if (matchesOf(springIndex, mustBeAt) >= 0)
return matchesOf(springIndex, mustBeAt)
else if (!validSpringLocation(mustBeAt, nums[springIndex]))
return updateMatchTable(springIndex, mustBeAt, 0)
else if (springIndex == nums.size - 1) {
// if we're looking at the last spring, validity depends on whether or not there are more #s after
val remainingHashes = line.substring(mustBeAt+nums[springIndex]).count { it == '#' }
return updateMatchTable(springIndex, mustBeAt, if (remainingHashes == 0) 1 else 0)
}
// walk through all valid locations of the next spring
// minimum must occur after the current spring
val minNextLoc = mustBeAt + nums[springIndex] + 1
// maximum must be no further than the max loc, but can't skip any #'s
val nextHash = line.indexOf('#', minNextLoc).let { if (it < 0) line.length else it }
val maxNextLoc = minOf(nextHash, maxLocsPerSpring[springIndex+1])
val possibleLocationsOfNext = minNextLoc..maxNextLoc
val count = possibleLocationsOfNext.sumOf { loc ->
calcMatchesOf(springIndex+1, loc)
}
return updateMatchTable(springIndex, mustBeAt, count)
}
val maxLocsPerSpring: SpringLocs
init {
val maxes = mutableListOf<Int>()
var i = line.length
nums.reversed().forEach {
maxes += i - it
i -= it + 1
}
maxLocsPerSpring = maxes.reversed()
}
/** Test if a spring could exist at the given target location. */
fun validSpringLocation(loc: Int, num: Int) =
loc + num <= line.length &&
'.' !in line.substring(loc, loc + num) &&
line.getOrNull(loc-1) != '#' &&
line.getOrNull(loc+num) != '#'
}
typealias SpringLocs = List<Int>
typealias SpringLengths = List<Int>
fun String.parse() = Springs(chunk(0), chunk(1).split(",").map { it.toInt() })
// part 1
fun List<String>.part1(): Long = sumOf {
print(".")
it.parse().arrangements()
}.also { println() }
// part 2
fun List<String>.part2(): Long = withIndex().sumOf {
val mod = (size / 100).coerceAtLeast(1)
print(if (it.index % mod == 0) "x" else ".")
val str = it.value.chunk(0)
val nums = it.value.chunk(1).split(",").map { it.toInt() }
val unfolded = ("$str?").repeat(4)+str
val unfoldedNums = (1..5).flatMap { nums }
val spr = Springs(unfolded, unfoldedNums)
spr.print = false
spr.arrangements()
}.also { println() }
// calculate answers
val day = 12
val input = getDayInput(day, 2023)
val testResult = testInput.part1().also { it.print }
val answer1 = input.part1().also { it.print }
val testResult2 = testInput.part2().also { it.print }
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 4,969 | advent-of-code | Apache License 2.0 |
src/main/kotlin/kt/kotlinalgs/app/graph/MinSpanningTreePrim.ws.kts | sjaindl | 384,471,324 | false | null | package com.sjaindl.kotlinalgsandroid.graph
/*
MinSpanningTreePrim - MST weighted undirected graph
O(V^2) runtime (adj. matrix)
*/
//https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/
class MinSpanningTreePrim {
fun minSpanningTree(graph: Array<IntArray>): IntArray {
val mstSet: MutableSet<Int> = mutableSetOf() //vertices already included in mst
// min edges adjacent to current mst
val min = IntArray(graph.size) { Int.MAX_VALUE }
min[0] = 0 //start vertice to pick first
//parent edge (from vertice) of (to) vertice
val parents = IntArray(graph.size) { -1 }
while (mstSet.size < graph.size) {
val nextMin = findMin(min, mstSet)
mstSet.add(nextMin)
for (vertice in graph.indices) {
if (!mstSet.contains(vertice) && graph[nextMin][vertice] != 0 && graph[nextMin][vertice] < min[vertice]) {
min[vertice] = graph[nextMin][vertice]
parents[vertice] = nextMin
}
}
}
return parents
}
private fun findMin(min: IntArray, mstSet: MutableSet<Int>): Int {
var minVal = Int.MAX_VALUE
var minIndex = -1
min.forEachIndexed { index, value ->
if (value < minVal && !mstSet.contains(index)) {
minVal = value
minIndex = index
}
}
return minIndex
}
}
val graph = arrayOf(
intArrayOf(0, 4, 0, 0, 0, 0, 0, 8, 0),
intArrayOf(4, 0, 8, 0, 0, 0, 0, 11, 0),
intArrayOf(0, 8, 0, 7, 0, 0, 0, 0, 2),
intArrayOf(0, 0, 7, 0, 9, 0, 0, 0, 0),
intArrayOf(0, 0, 0, 9, 0, 10, 0, 0, 0),
intArrayOf(0, 0, 4, 14, 10, 0, 2, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 2, 0, 1, 6),
intArrayOf(8, 11, 0, 0, 0, 0, 1, 0, 7),
intArrayOf(0, 0, 2, 0, 0, 0, 6, 7, 0)
)
val mst = MinSpanningTreePrim().minSpanningTree(graph)
mst.forEachIndexed { from, to ->
println("$from-$to")
}
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 2,016 | KotlinAlgs | MIT License |
fibonacci/src/main/kotlin/com/nickperov/stud/algorithms/fibonacci/FibonacciLargeGenerator.kt | nickperov | 327,780,009 | false | null | package com.nickperov.stud.algorithms.fibonacci
import java.math.BigInteger
fun main() {
println("Hello, large Fibonacci numbers")
println(FibonacciLargeTailRecursiveOptimisedGenerator().calculate(1000000))
/*for (number in 93..150) {
println("====================>$number<==================")
println(FibonacciLargeTailRecursiveOptimisedGenerator().calculate(number))
println(FibonacciLargeIterativeGenerator02().calculate(number))
println(FibonacciLargeMatrixGenerator().calculate(number))
}*/
}
/**
* Generator to calculate fibonacci number greater than 7540113804746346429 (92nd number)
*/
abstract class FibonacciLargeGenerator {
abstract fun calculate(number: Int): BigInteger
}
class FibonacciLargeTailRecursiveOptimisedGenerator : FibonacciLargeGenerator() {
override fun calculate(number: Int): BigInteger {
return if (number == 0)
BigInteger.ZERO
else if (number == 1 || number == 2)
BigInteger.ONE
else calculate(BigInteger.ONE, BigInteger.ONE, 3, number)
}
private tailrec fun calculate(antePenultimate: BigInteger, penultimate: BigInteger, current: Int, target: Int): BigInteger {
return if (current == target) antePenultimate.add(penultimate)
else calculate(penultimate, antePenultimate.add(penultimate), current + 1, target)
}
}
class FibonacciLargeIterativeGenerator02 : FibonacciLargeGenerator() {
override fun calculate(number: Int): BigInteger {
val numberPair = arrayOf(BigInteger.ZERO, BigInteger.ZERO)
for (i in 0..number) {
calculate(i, numberPair)
}
return numberPair[1]
}
private fun calculate(number: Int, prev: Array<BigInteger>) {
when (number) {
0 -> {
prev[1] = BigInteger.ZERO
}
1 -> {
prev[1] = BigInteger.ONE
}
2 -> {
prev[0] = BigInteger.ONE
}
else -> {
val next = prev[0].add(prev[1])
prev[0] = prev[1]
prev[1] = next
}
}
}
}
class FibonacciLargeMatrixGenerator : FibonacciLargeGenerator() {
/**
* Matrix:
| 0 1 |
| 1 1 |
*/
private val matrix = arrayOf(arrayOf(BigInteger.ZERO, BigInteger.ONE), arrayOf(BigInteger.ONE, BigInteger.ONE))
override fun calculate(number: Int): BigInteger {
if (number == 0 || number == 1) {
return BigInteger.valueOf(number.toLong())
} else if (number == 2) {
return BigInteger.ONE
} else {
var currMatrix = matrix
val power = number - 1
currMatrix = powerOf(currMatrix, power)
return currMatrix[1][1]
}
}
private fun powerOf(m: Array<Array<BigInteger>>, n: Int): Array<Array<BigInteger>> {
return when {
n == 1 -> {
m
}
n % 2 == 0 -> {
val mP = powerOf(m, n / 2)
multiply(mP, mP)
}
else -> {
val mP = powerOf(m, n - 1)
multiply(mP, m)
}
}
}
private fun multiply(m1: Array<Array<BigInteger>>, m2: Array<Array<BigInteger>>): Array<Array<BigInteger>> {
val l = m1.size
val n = m2.size
val result = Array(l) { Array(n) { BigInteger.ZERO } }
for (i in 0 until l) {
for (k in 0 until n) {
var sum = BigInteger.ZERO
for (j in 0 until m1[i].size) {
sum = sum.add(m1[i][j].multiply(m2[k][j]))
}
result[i][k] = sum
}
}
return result
}
} | 0 | Kotlin | 0 | 0 | 6696f5d8bd73ce3a8dfd4200f902e2efe726cc5a | 3,795 | Algorithms | MIT License |
src/Day13.kt | adrianforsius | 573,044,406 | false | {"Kotlin": 68131} | import org.assertj.core.api.Assertions.assertThat
fun order(a: List<Any>, b: List<Any>): Int {
for ((index, _) in a.withIndex()) {
val r = b.getOrNull(index) ?: return -1
val l = a.get(index)
if (l is Int && r is Int) {
if (l == r) continue
return if (l < r) 1 else -1
}
if (l is List<*> && r is Int) {
val v = order(l as List<Any>, listOf(r))
if (v == 0) continue
return v
}
if (l is Int && r is List<*>) {
val v = order(listOf(l), r as List<Any>)
if (v == 0) continue
return v
}
if (l is List<*> && r is List<*>) {
val v = order(l as List<Any>, r as List<Any>)
if (v == 0) continue
return v
}
}
if (b.size == a.size) return 0
return 1
}
fun parse(s: MutableList<String>, n: MutableList<Any>): MutableList<Any> {
if (s.isEmpty()) return mutableListOf()
do {
when (val next = s.removeFirst()) {
"[" -> {
val nn = parse(s, mutableListOf())
n.add(nn)
}
"]" -> return n
"," -> {}
"" -> {}
else -> n.add(next.toInt())
}
} while (s.size > 0)
return n
}
fun ordered(left: MutableList<Any>, right: MutableList<Any>): Boolean? {
while (left.size > 0) {
val r = right.removeFirstOrNull() ?: return false
val l = left.removeFirst()
if (l is Int && r is Int) {
if (l == r) continue
return l < r
}
if (l is List<*> && r is Int) return ordered(l as MutableList<Any>, mutableListOf(r)) ?: continue
if (l is Int && r is List<*>) return ordered(mutableListOf(l), r as MutableList<Any>) ?: continue
if (l is List<*> && r is List<*>) {
return ordered(l as MutableList<Any>, r as MutableList<Any>) ?: continue
}
}
if (right.size == 0) return null
return true
}
fun main() {
fun part1(input: String): Int {
val packets = input
.split("\n\n")
.map {
val (left, right) = it
.split("\n")
.map{
var s = it
var new: MutableList<String> = mutableListOf()
for ((index, c) in it.withIndex()) {
when {
c in "0123456789".toCharArray() -> {
val rest = s.slice(index..s.length-1)
val numEnd = rest.indexOfFirst { it in "[],".toCharArray() }
val num = s.slice(index..index+numEnd-1)
new.add(num)
}
else -> new.add(c.toString())
}
}
new
}
Pair(parse(left, mutableListOf()), parse(right, mutableListOf()))
}
var count = 0
var indice = mutableListOf<Int>()
var index = 1
packets.map { (left, right) ->
if (ordered(left, right)!!) {
count += index
}
index++
}
println(indice)
return count
}
fun part2(input: String): Int {
val inputWithDelim = input + "[[2]]\n" + "[[6]]\n"
val packets = inputWithDelim
.replace("\n\n", "\n")
.split("\n")
.map {
var s = it
var new: MutableList<String> = mutableListOf()
for ((index, c) in s.withIndex()) {
when {
c in "0123456789".toCharArray() -> {
val rest = s.slice(index..s.length-1)
val numEnd = rest.indexOfFirst { it in "[],".toCharArray() }
val num = s.slice(index..index+numEnd-1)
new.add(num)
}
else -> new.add(c.toString())
}
}
parse(new, mutableListOf())
}.filter{ it.isNotEmpty() }.map{
it.first()
}
val s = packets.sortedWith{a, b -> order(b as List<Any> , a as List<Any>) }
// for (ss in s) {
// println(ss.toString())
// }
val divider = Pair("[[2]]","[[6]]")
val index = Pair(s.indexOfFirst { it.toString() == divider.first }+1, s.indexOfFirst { it.toString() == divider.second }+1)
return index.first*index.second
}
// test if implementation meets criteria from the description, like:
// Test
val testInput = readText("Day13_test")
val output1 = part1(testInput)
assertThat(output1).isEqualTo(13)
// Answer
val input = readText("Day13")
val outputAnswer1 = part1(input)
assertThat(outputAnswer1).isEqualTo(6187)
// Test
val output2 = part2(testInput)
assertThat(output2).isEqualTo(140)
// Answer
// too high - 24720
val outputAnswer2 = part2(input)
assertThat(outputAnswer2).isEqualTo(23520)
}
| 0 | Kotlin | 0 | 0 | f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb | 5,299 | kotlin-2022 | Apache License 2.0 |
year2016/src/main/kotlin/net/olegg/aoc/year2016/day8/Day8.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2016.day8
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2016.DayOf2016
/**
* See [Year 2016, Day 8](https://adventofcode.com/2016/day/8)
*/
object Day8 : DayOf2016(8) {
private val PATTERN = "(\\D*)(\\d+)\\D*(\\d+)\\D*".toRegex()
override fun first(): Any? {
return applyOperations()
.sumOf { row -> row.count { it } }
}
override fun second(): Any? {
return applyOperations()
.joinToString(separator = "\n", prefix = "\n") { row ->
row.joinToString(separator = "") { if (it) "██" else ".." }
}
}
private fun applyOperations(): Array<BooleanArray> {
val width = 50
val height = 6
val screen = Array(height) { BooleanArray(width) }
lines
.mapNotNull { line ->
PATTERN.matchEntire(line)?.let { match ->
val (command, first, second) = match.destructured
Triple(command, first.toInt(), second.toInt())
}
}
.forEach { (command, first, second) ->
when (command) {
"rect " ->
(0..<second).forEach { y -> screen[y].fill(true, 0, first) }
"rotate row y=" -> {
val row = BooleanArray(width)
(0..<width).forEach { row[(it + second) % width] = screen[first][it] }
(0..<width).forEach { screen[first][it] = row[it] }
}
"rotate column x=" -> {
val column = BooleanArray(height)
(0..<height).forEach { column[(it + second) % height] = screen[it][first] }
(0..<height).forEach { screen[it][first] = column[it] }
}
}
}
return screen
}
}
fun main() = SomeDay.mainify(Day8)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,687 | adventofcode | MIT License |
src/Day19.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | enum class ResType {
GEODE,
OBSIDIAN,
CLAY,
ORE,
}
typealias NumItem = Map<ResType, Int>
typealias Blueprint = Map<ResType, NumItem>
fun main() {
fun matchRes(res: String): ResType? {
return when (res) {
"ore" -> ResType.ORE
"clay" -> ResType.CLAY
"obsidian" -> ResType.OBSIDIAN
"geode" -> ResType.GEODE
else -> null
}
}
fun parse(input: List<String>): List<Blueprint> {
val res = mutableListOf<Blueprint>()
val curBlueprint = mutableMapOf<ResType, NumItem>()
for (line in input) {
curBlueprint.clear()
val blueprint = line.split(":").last().split(".")
for (robot in blueprint.filterNot(String::isEmpty)) {
val xs = robot.trim().split(" ")
curBlueprint[matchRes(xs[1])!!] =
xs.subList(4, xs.size).zipWithNext().filter { (a, b) -> a != "and" && b != "and" }
.associate { (a, b) -> Pair(matchRes(b)!!, a.toInt()) }
}
res.add(HashMap(curBlueprint))
}
return res
}
fun canProduce(have: Map<ResType, Int>, required: NumItem): Pair<Boolean, MutableMap<ResType, Int>> {
val resLeft = HashMap(have)
for ((reqRes, reqCount) in required) {
if (have.containsKey(reqRes)) {
if (have[reqRes]!! < reqCount) {
return Pair(false, resLeft)
} else {
resLeft[reqRes] = have[reqRes]!! - reqCount
}
} else {
return Pair(false, resLeft)
}
}
return Pair(true, resLeft)
}
fun compute(blueprint: Blueprint, totalMinutes: Int): Int {
val table = HashMap<String, Int>()
val maxOre = blueprint.values.maxOfOrNull { it[ResType.ORE]!! }!!
fun inner(curRes: MutableMap<ResType, Int>, curRobots: MutableMap<ResType, Int>, newRobot: ResType?, minute: Int): Int {
var maxGeodes = 0
// produce resources
for ((robotType, robotCount) in curRobots) {
curRes[robotType] = curRes.getOrDefault(robotType, 0) + robotCount
}
if (minute >= totalMinutes) {
return curRes.getOrDefault(ResType.GEODE, 0)
}
val minutesLeft = totalMinutes - minute
// no need to build more robots than resource of the type required
curRobots[ResType.ORE] = minOf(curRobots.getOrDefault(ResType.ORE, 0), maxOre)
curRobots[ResType.CLAY] = minOf(
curRobots.getOrDefault(ResType.CLAY, 0),
blueprint[ResType.OBSIDIAN]!![ResType.CLAY]!!
)
curRobots[ResType.OBSIDIAN] = minOf(
curRobots.getOrDefault(ResType.OBSIDIAN, 0),
blueprint[ResType.GEODE]!![ResType.OBSIDIAN]!!
)
// restrain max resources
curRes[ResType.ORE] = minOf(curRes.getOrDefault(ResType.ORE, 0),
(minutesLeft * maxOre) - curRobots[ResType.ORE]!! * (minutesLeft - 1))
curRes[ResType.CLAY] = minOf(curRes.getOrDefault(ResType.CLAY, 0),
(minutesLeft * blueprint[ResType.OBSIDIAN]!![ResType.CLAY]!!) -
curRobots[ResType.CLAY]!! * (minutesLeft - 1))
curRes[ResType.OBSIDIAN] = minOf(curRes.getOrDefault(ResType.OBSIDIAN, 0),
(minutesLeft * blueprint[ResType.GEODE]!![ResType.OBSIDIAN]!!) -
curRobots[ResType.OBSIDIAN]!! * (minutesLeft - 1))
var key = "$curRes$curRobots$newRobot$minute"
if (table.containsKey(key)) {
return table[key]!!
}
// produce new robot
if (newRobot != null) {
curRobots[newRobot] = curRobots.getOrDefault(newRobot, 0) + 1
}
var robotTypes = ResType.values()
if (minutesLeft <= 4) {
robotTypes = arrayOf(ResType.GEODE)
} else if (minutesLeft <= 7) {
robotTypes = arrayOf(ResType.GEODE, ResType.OBSIDIAN)
} else if (minutesLeft <= 15) {
robotTypes = arrayOf(ResType.GEODE, ResType.OBSIDIAN, ResType.CLAY)
}
var lastProducedRobot: ResType? = null
// see what is it possible to produce at the moment
for (robotType in robotTypes) {
val requiredRes = blueprint[robotType]!!
val (ok, resLeft) = canProduce(curRes, requiredRes)
if (!ok)
continue
lastProducedRobot = robotType
maxGeodes =
maxOf(maxGeodes, inner(HashMap(resLeft), HashMap(curRobots), robotType, minute + 1))
if (robotType == ResType.GEODE)
break
}
if (lastProducedRobot != ResType.GEODE) {
maxGeodes = maxOf(maxGeodes, inner(HashMap(curRes), HashMap(curRobots), null, minute + 1))
}
table[key] = maxGeodes
return maxGeodes
}
return inner(mutableMapOf(), mutableMapOf(ResType.ORE to 1), null, 1)
}
fun part1(input: List<String>): Int {
return parse(input)
.withIndex()
.sumOf {
(i, blueprint) -> compute(blueprint, 24) * (i + 1)
}
}
fun part2(input: List<String>): Int {
val parsed = parse(input)
return parsed.subList(0, minOf(parsed.size, 3))
.parallelStream()
.map{bp -> compute(bp, 32)}
.reduce { acc, i -> acc * i }
.get()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
check(part1(testInput) == 33)
check(part2(testInput) == 3472)
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 6,046 | aoc2022 | Apache License 2.0 |
leetcode/src/sort/Q414.kt | zhangweizhe | 387,808,774 | false | null | package sort
fun main() {
// 414. 第三大的数
// https://leetcode-cn.com/problems/third-maximum-number/
val intArrayOf = intArrayOf(1,1,1)
println(thirdMax(intArrayOf))
}
fun thirdMax(nums: IntArray): Int {
var a = Long.MIN_VALUE
var b = Long.MIN_VALUE
var c = Long.MIN_VALUE
for (i in nums) {
if (i > a) {
c = b
b = a
a = i.toLong()
}else if (i < a && i > b) {
c = b
b = i.toLong()
}else if (i < b && i > c) {
c = i.toLong()
}
}
return if (c == Long.MIN_VALUE) {
a.toInt()
}else {
c.toInt()
}
}
fun thirdMax1(nums: IntArray): Int {
val set:Set<Int> = HashSet<Int>(nums.toList())
val setNums = set.toIntArray()
if (setNums.size == 2) {
return if (setNums[0] > setNums[1]) {
setNums[0]
}else {
setNums[1]
}
}else if (setNums.size == 1) {
return setNums[0]
}
val quickSort = quickSort(setNums, 0, setNums.size - 1)
println("find index $quickSort")
println("nums ${setNums.contentToString()}")
println("find num ${setNums[quickSort]}")
return setNums[quickSort]
}
private fun quickSort(nums: IntArray, start: Int, end: Int):Int {
if (start >= end) {
return end
}
val pivot = nums[end]
var i = start
for (j in start until end) {
if (nums[j] > pivot) {
val tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
i++
}
}
nums[end] = nums[i]
nums[i] = pivot
if (i == 2) {
println(pivot)
return i
}else if (i > 2) {
return quickSort(nums, start, i-1)
}else {
return quickSort(nums, i+1, end)
}
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,813 | kotlin-study | MIT License |
src/Day11.kt | cornz | 572,867,092 | false | {"Kotlin": 35639} | import java.math.BigInteger
data class Monkey(
var id: Int, var items: MutableList<Int>, var operation: Pair<String, String>, var divisor: Int,
var throwTo: Pair<Int, Int>, var numberOfInspections: Int
)
data class LongMonkey(
var id: Int, var items: MutableList<BigInteger>, var operation: Pair<String, String>,
var divisor: Int, var throwTo: Pair<Int, Int>, var numberOfInspections: BigInteger
)
fun main() {
fun processMonkeys(input: List<String>): List<Monkey> {
val monkeys = input.filter { x -> x.isNotEmpty() }.chunked(6)
val processedMonkeys = mutableListOf<Monkey>()
for (monkeyText in monkeys) {
val id = monkeyText[0].filter { x -> x.isDigit() }.toInt()
val items = monkeyText[1].split(": ")[1].split(", ").map { x -> x.toInt() }
val operation = monkeyText[2].split("old ")[1].split(" ")
val divisor = monkeyText[3].filter { x -> x.isDigit() }.toInt()
val throwTo = Pair(
monkeyText[4].filter { x -> x.isDigit() }.toInt(),
monkeyText[5].filter { x -> x.isDigit() }.toInt()
)
val monkey = Monkey(id, items.toMutableList(), Pair(operation[0], operation[1]), divisor, throwTo, 0)
processedMonkeys.add(monkey)
}
return processedMonkeys
}
fun processLongMonkeys(input: List<String>): List<LongMonkey> {
val monkeys = input.filter { x -> x.isNotEmpty() }.chunked(6)
val processedMonkeys = mutableListOf<LongMonkey>()
for (monkeyText in monkeys) {
val id = monkeyText[0].filter { x -> x.isDigit() }.toInt()
val items = monkeyText[1].split(": ")[1].split(", ").map { x -> x.toBigInteger() }
val operation = monkeyText[2].split("old ")[1].split(" ")
val divisor = monkeyText[3].filter { x -> x.isDigit() }.toInt()
val throwTo = Pair(
monkeyText[4].filter { x -> x.isDigit() }.toInt(),
monkeyText[5].filter { x -> x.isDigit() }.toInt()
)
val monkey = LongMonkey(
id, items.toMutableList(), Pair(operation[0], operation[1]), divisor, throwTo,
BigInteger.ZERO
)
processedMonkeys.add(monkey)
}
return processedMonkeys
}
fun processItem(item: Int, monkey: Monkey): Int {
var worryLevel = item
var actionActor = monkey.operation.second
if (monkey.operation.second == "old") {
actionActor = worryLevel.toString()
}
if (monkey.operation.first == "+") {
worryLevel += actionActor.toInt()
} else if (monkey.operation.first == "*") {
worryLevel *= actionActor.toInt()
}
return worryLevel
}
fun processItem(item: BigInteger, monkey: LongMonkey): BigInteger {
var worryLevel = item
var actionActor = monkey.operation.second
if (monkey.operation.second == "old") {
actionActor = worryLevel.toString()
}
if (monkey.operation.first == "+") {
worryLevel = worryLevel.plus(actionActor.toBigInteger())
} else if (monkey.operation.first == "*") {
worryLevel = worryLevel.multiply(actionActor.toBigInteger())
}
return worryLevel
}
fun floorWorryLevel(worryLevel: Int): Int {
var worryLevel1 = worryLevel
worryLevel1 = worryLevel1.floorDiv(3)
return worryLevel1
}
fun throwItemToMonkey(worryLevel: Int, monkey: Monkey, monkeys: List<Monkey>) {
if (worryLevel.mod(monkey.divisor) == 0) {
monkeys[monkey.throwTo.first].items.add(worryLevel)
} else {
monkeys[monkey.throwTo.second].items.add(worryLevel)
}
monkey.numberOfInspections++
}
fun throwItemToMonkey(worryLevel: BigInteger, monkey: LongMonkey, monkeys: List<LongMonkey>) {
if (worryLevel.mod(BigInteger.valueOf(monkey.divisor.toLong())).equals(BigInteger.ZERO)) {
monkeys[monkey.throwTo.first].items.add(worryLevel)
} else {
monkeys[monkey.throwTo.second].items.add(worryLevel)
}
monkey.numberOfInspections++
}
fun monkeyBusiness(input: List<Monkey>): Int {
return input.map { x -> x.numberOfInspections }.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
fun monkeyBusiness(input: List<LongMonkey>): BigInteger {
return input.map { x -> x.numberOfInspections }.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
fun part1(input: List<String>): Int {
val monkeys = processMonkeys(input)
repeat(20) {
for (monkey in monkeys) {
for (item in monkey.items) {
var worryLevel = processItem(item, monkey)
worryLevel = floorWorryLevel(worryLevel)
throwItemToMonkey(worryLevel, monkey, monkeys)
}
monkey.items.clear()
}
}
return monkeyBusiness(monkeys)
}
fun part2(input: List<String>): BigInteger {
val monkeys = processLongMonkeys(input)
val lcm = monkeys.map { it.divisor }.reduce { acc, i -> acc * i }
var i = 0
repeat(10000) {
for (monkey in monkeys) {
for (item in monkey.items) {
var worryLevel = processItem(item, monkey)
worryLevel = worryLevel.mod(BigInteger.valueOf(lcm.toLong()))
throwItemToMonkey(worryLevel, monkey, monkeys)
}
monkey.items.clear()
}
i++
print(i)
print("\r")
}
return monkeyBusiness(monkeys)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("input/Day11_test")
check(part1(testInput) == 10605)
check(part2(testInput).compareTo(BigInteger.valueOf(2713310158)) == 0)
val input = readInput("input/Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2800416ddccabc45ba8940fbff998ec777168551 | 6,132 | aoc2022 | Apache License 2.0 |
kotlin/numbertheory/Euclid.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package numbertheory
import java.math.BigInteger
object Euclid {
fun gcd(a: Int, b: Int): Int {
return if (b == 0) Math.abs(a) else gcd(b, a % b)
}
fun gcd2(a: Int, b: Int): Int {
var a = a
var b = b
while (b != 0) {
val t = b
b = a % b
a = t
}
return Math.abs(a)
}
fun lcm(a: Int, b: Int): Int {
return Math.abs(a / gcd(a, b) * b)
}
// returns { gcd(a,b), x, y } such that gcd(a,b) = a*x + b*y
fun euclid(a: Long, b: Long): LongArray {
var a = a
var b = b
var x: Long = 1
var y: Long = 0
var x1: Long = 0
var y1: Long = 1
// invariant: a=a_orig*x+b_orig*y, b=a_orig*x1+b_orig*y1
while (b != 0L) {
val q = a / b
val _x1 = x1
val _y1 = y1
val _b = b
x1 = x - q * x1
y1 = y - q * y1
b = a - q * b
x = _x1
y = _y1
a = _b
}
return if (a > 0) longArrayOf(a, x, y) else longArrayOf(-a, -x, -y)
}
fun euclid2(a: Long, b: Long): LongArray {
if (b == 0L) return if (a > 0) longArrayOf(a, 1, 0) else longArrayOf(-a, -1, 0)
val r = euclid2(b, a % b)
return longArrayOf(r[0], r[2], r[1] - a / b * r[2])
}
fun mod(a: Int, m: Int): Int {
var a = a
a %= m
return if (a >= 0) a else a + m
}
fun mod(a: Long, m: Int): Int {
var a = a
a %= m.toLong()
return (if (a >= 0) a else a + m).toInt()
}
// precondition: m > 1 && gcd(a, m) = 1
fun modInverse(a: Int, m: Int): Int {
var a = a
a = mod(a, m)
return if (a == 0) 0 else mod(
((1 - modInverse(m, a).toLong() * m) / a).toInt(), m
)
}
// precondition: m > 0 && gcd(a, m) = 1
fun modInverse2(a: Int, m: Int): Int {
return mod(euclid(a.toLong(), m.toLong())[1].toInt(), m)
}
// precondition: p is prime
fun generateInverses(p: Int): IntArray {
val res = IntArray(p)
res[1] = 1
for (i in 2 until p) res[i] = ((p - p / i) as Long * res[p % i] % p).toInt()
return res
}
// returns x ≡ a[i] (mod p[i]), where gcd(p[i], p[j]) == 1
fun garnerRestore(a: IntArray, p: IntArray): BigInteger {
val x: IntArray = a.clone()
for (i in x.indices) for (j in 0 until i) x[i] = mod(
BigInteger.valueOf(p[j]).modInverse(BigInteger.valueOf(p[i])).longValue() * (x[i] - x[j]), p[i]
)
var res: BigInteger = BigInteger.valueOf(x[0])
var m: BigInteger = BigInteger.ONE
for (i in 1 until x.size) {
m = m.multiply(BigInteger.valueOf(p[i - 1]))
res = res.add(m.multiply(BigInteger.valueOf(x[i])))
}
return res
}
// returns x ≡ a[i] (mod p[i]), where gcd(p[i], p[j]) == 1
fun simpleRestore(a: IntArray, p: IntArray): Int {
var res = 0
var i = 0
var m = 1
while (i < a.size) {
while (res % p[i] != a[i]) res += m
i++
m *= p[i]
}
return res
}
// Usage example
fun main(args: Array<String?>?) {
val rnd = Random(1)
for (steps in 0..9999) {
val a: Int = rnd.nextInt(20) - 10
val b: Int = rnd.nextInt(20) - 10
val xa: BigInteger = BigInteger.valueOf(a)
val xb: BigInteger = BigInteger.valueOf(b)
val gcd1 = gcd(a, b).toLong()
val gcd2 = gcd2(a, b).toLong()
val gcd: Long = xa.gcd(xb).longValue()
val euclid1 = euclid(a.toLong(), b.toLong())
val euclid2 = euclid2(a.toLong(), b.toLong())
var inv1 = 0
var inv2 = 0
var inv = 0
if (gcd == 1L && b > 0) {
inv1 = modInverse(a, b)
inv2 = modInverse2(a, b)
inv = xa.modInverse(xb).intValue()
}
if (gcd1 != gcd || gcd2 != gcd || !Arrays.equals(
euclid1,
euclid2
) || euclid1[0] != gcd || inv1 != inv || inv2 != inv
) {
System.err.println("$a $b")
}
}
val a: Long = 6
val b: Long = 9
val res = euclid(a, b)
System.out.println(
res[1].toString() + " * (" + a + ") "
+ " + " + res[2] + " * (" + b + ") = gcd(" + a + "," + b + ") = " + res[0]
)
System.out.println(Arrays.toString(generateInverses(7)))
System.out.println(garnerRestore(intArrayOf(200000125, 300000333), intArrayOf(1000000007, 1000000009)))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 4,764 | codelibrary | The Unlicense |
src/day21/Expressions.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day21
// NOT 9879574614298
fun Jobs.simplify (e: Expression.Calculation): Pair<Expression.Calculation, Boolean> {
// We only solve expressions expressed as equalities
if (e.operation != Operation.EQUALS) {
throw IllegalArgumentException ("Can only solve equality expressions.")
}
// Make sure we're working with a number and an expression
val l = eval (e.left)
val r = eval (e.right)
if (l is Expression.Number) {
if (r is Expression.Calculation) {
return simplify (Expression.Calculation (r, Operation.EQUALS, l))
} else {
throw IllegalArgumentException ("We're not Wolfram alpha; keep it simple.")
}
}
// Exit if we've done all of the reducing that can be done
if (l is Expression.Symbol) {
return Pair(e, true)
}
// Deal with number on the left
l as Expression.Calculation
r as Expression.Number
if (l.left is Expression.Number) {
val result = when (l.operation) {
Operation.PLUS -> {
r.value - l.left.value
}
Operation.MINUS -> {
l.left.value - r.value
}
Operation.DIVIDE -> {
l.left.value / r.value
}
Operation.MULTIPLY -> {
r.value / l.left.value
}
else -> throw Exception ()
}
val simpler = Expression.Calculation (l.right, Operation.EQUALS, Expression.Number (result))
return Pair (simpler, false)
}
// Deal with number on the right
if (l.right is Expression.Number) {
val result = when (l.operation) {
Operation.PLUS -> {
r.value - l.right.value
}
Operation.MINUS -> {
r.value + l.right.value
}
Operation.DIVIDE -> {
r.value * l.right.value
}
Operation.MULTIPLY -> {
r.value / l.right.value
}
else -> throw Exception ()
}
val simpler = Expression.Calculation (l.left, Operation.EQUALS, Expression.Number (result))
return Pair (simpler, false)
}
return Pair (e, true)
}
fun main (args: Array<String>) {
val example = false
val jobs = loadJobs(example)
// calculate root
val root = jobs.eval ("root")
println (root)
// uncertain humn
val expr = jobs.map["root"] as Expression.Calculation
expr.left as Expression.Symbol
expr.right as Expression.Symbol
println (jobs.evalInputs (expr.left.symbol))
println (jobs.evalInputs (expr.right.symbol))
println (jobs.eval (expr.left))
println (jobs.eval (expr.right))
// remove humn
jobs.map.remove ("humn")
val left = jobs.eval (expr.left)
val right = jobs.eval (expr.right)
// solution
var solve = Expression.Calculation (left, Operation.EQUALS, right)
var solved = false
while (! solved) {
val result = jobs.simplify (solve)
println ("\n")
solve = result.first
solved = result.second
}
println (solve)
return
}
// EOF
| 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 3,176 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2021/calendar/day20/Day20.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2021.calendar.day20
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import javax.inject.Inject
class Day20 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
companion object {
const val OUTPUT_LIT = '#'
const val OUTPUT_DIM = ' '
const val INPUT_LIT = '#'
const val INPUT_DIM = '.'
private fun conversion(c: Char): Char {
return when (c) {
INPUT_DIM -> OUTPUT_DIM
INPUT_LIT -> OUTPUT_LIT
else -> throw IllegalArgumentException()
}
}
}
fun partOne(fileName: String) = generatorFactory.forFile(fileName).read { input ->
val (algorithm, image) = parse(input)
val imageArray = runEnhancement(algorithm, image.map { it.toList() }, 2)
imageArray.sumOf { it.count { c -> c == OUTPUT_LIT } }
}
fun partTwo(fileName: String) = generatorFactory.forFile(fileName).read { input ->
val (algorithm, image) = parse(input)
val imageArray = runEnhancement(algorithm, image.map { it.toList() }, 50)
imageArray.sumOf { it.count { c -> c == OUTPUT_LIT } }
}
private fun runEnhancement(algorithm: Algorithm, input: List<List<Char>>, times: Int): List<List<Char>> {
var imageArray = input
repeat(times) {
imageArray = enhance(algorithm, imageArray)
}
return imageArray
}
private fun enhance(algorithm: Algorithm, imageArray: List<List<Char>>): List<List<Char>> {
algorithm.incrementEnhance()
val borderSizeIncrease = 2
val result = MutableList(imageArray.size + borderSizeIncrease) {
MutableList(imageArray[0].size + borderSizeIncrease) {
OUTPUT_DIM
}
}
result.indices.forEach { resultY ->
result[resultY].indices.forEach { resultX ->
val imageYFromResultY = resultY - (borderSizeIncrease / 2)
val imageXFromResultY = resultX - (borderSizeIncrease / 2)
val encoding = (imageYFromResultY - 1..imageYFromResultY + 1).flatMap { imageY ->
(imageXFromResultY - 1..imageXFromResultY + 1).map { imageX ->
imageArray.find(imageY, imageX, algorithm)
}
}
val code = encoding.map { if (it == OUTPUT_DIM) 0 else 1 }
.joinToString("")
.toInt(2)
result[resultY][resultX] = conversion(algorithm.fromCode(code))
}
}
return result
}
private fun List<List<Char>>.find(y: Int, x: Int, algorithm: Algorithm) : Char {
return this.getOrNull(y)?.getOrNull(x)?: conversion(algorithm.getInfinity())
}
private fun parse(input: Sequence<String>): Pair<Algorithm, List<String>> {
val data = input.toList()
val algorithm = Algorithm.fromData(data.first())
val image = data.drop(2)
return algorithm to image.map { it.replace(INPUT_LIT, OUTPUT_LIT).replace(INPUT_DIM, OUTPUT_DIM) }
}
class Algorithm private constructor(private val enhancement: String, private var infiniteMarker: Char) {
companion object {
fun fromData(enhancement: String) = Algorithm(enhancement, enhancement[0])
}
fun fromCode(code: Int): Char = enhancement[code]
fun incrementEnhance() {
val num = if (infiniteMarker == INPUT_LIT) 1 else 0
infiniteMarker = fromCode(num.toString().repeat(9).toInt(2))
}
fun getInfinity() = infiniteMarker
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 3,312 | advent-of-code | MIT License |
src/leetcodeProblem/leetcode/editor/en/SumOfBeautyInTheArray.kt | faniabdullah | 382,893,751 | false | null | //You are given a 0-indexed integer array nums. For each index i (1 <= i <=
//nums.length - 2) the beauty of nums[i] equals:
//
//
// 2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <=
//nums.length - 1.
// 1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not
//satisfied.
// 0, if none of the previous conditions holds.
//
//
// Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.
//
//
// Example 1:
//
//
//Input: nums = [1,2,3]
//Output: 2
//Explanation: For each index i in the range 1 <= i <= 1:
//- The beauty of nums[1] equals 2.
//
//
// Example 2:
//
//
//Input: nums = [2,4,6,4]
//Output: 1
//Explanation: For each index i in the range 1 <= i <= 2:
//- The beauty of nums[1] equals 1.
//- The beauty of nums[2] equals 0.
//
//
// Example 3:
//
//
//Input: nums = [3,2,1]
//Output: 0
//Explanation: For each index i in the range 1 <= i <= 1:
//- The beauty of nums[1] equals 0.
//
//
//
// Constraints:
//
//
// 3 <= nums.length <= 10⁵
// 1 <= nums[i] <= 10⁵
//
// Related Topics Array 👍 191 👎 19
package leetcodeProblem.leetcode.editor.en
class SumOfBeautyInTheArray {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun sumOfBeauties(nums: IntArray): Int {
var sumOfBeauties = 0
for (i in nums.indices) {
if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) {
sumOfBeauties++
}
}
return 0
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 1,774 | dsa-kotlin | MIT License |
src/Day03RucksackReorganization.kt | zizoh | 573,932,084 | false | {"Kotlin": 13370} | fun main() {
val priorities = mapOf(
'a' to 1,
'b' to 2,
'c' to 3,
'd' to 4,
'e' to 5,
'f' to 6,
'g' to 7,
'h' to 8,
'i' to 9,
'j' to 10,
'k' to 11,
'l' to 12,
'm' to 13,
'n' to 14,
'o' to 15,
'p' to 16,
'q' to 17,
'r' to 18,
's' to 19,
't' to 20,
'u' to 21,
'v' to 22,
'w' to 23,
'x' to 24,
'y' to 25,
'z' to 26,
'A' to 27,
'B' to 28,
'C' to 29,
'D' to 30,
'E' to 31,
'F' to 32,
'G' to 33,
'H' to 34,
'I' to 35,
'J' to 36,
'K' to 37,
'L' to 38,
'M' to 39,
'N' to 40,
'O' to 41,
'P' to 42,
'Q' to 43,
'R' to 44,
'S' to 45,
'T' to 46,
'U' to 47,
'V' to 48,
'W' to 49,
'X' to 50,
'Y' to 51,
'Z' to 52
)
println('a'.code)
println('c'.code)
println('z'.code)
println('A'.code)
val input: List<String> = readInput("input/day03")
println("part one: ${partOneSum(input, priorities)}")
println("part two: ${partTwoSum(input, priorities)}")
}
private fun partOneSum(
input: List<String>, priorities: Map<Char, Int>
) = input.sumOf { items ->
val length = items.length
val firstCompartment = arrayOfNulls<Unit>(52)
val secondCompartment = arrayOfNulls<Unit>(52)
items.forEachIndexed { index, item ->
val currentItemPriority = priorities[item]!!
if (index < length / 2) {
firstCompartment[currentItemPriority - 1] = Unit
} else secondCompartment[currentItemPriority - 1] = Unit
}
var selectedItemPriority = 0
for (index in 0..51) {
if (firstCompartment[index] != null && secondCompartment[index] != null) {
selectedItemPriority = index + 1
break
}
}
selectedItemPriority
}
fun partTwoSum(input: List<String>, priorities: Map<Char, Int>) =
input.windowed(3, 3).map { group ->
val firstElfSack = arrayOfNulls<Unit>(52)
group[0].forEach { item ->
val currentItemPriority = priorities[item]!!
firstElfSack[currentItemPriority - 1] = Unit
}
val secondElfSack = arrayOfNulls<Unit>(52)
group[1].forEach { item ->
val currentItemPriority = priorities[item]!!
secondElfSack[currentItemPriority - 1] = Unit
}
val thirdElfSack = arrayOfNulls<Unit>(52)
group[2].forEach { item ->
val currentItemPriority = priorities[item]!!
thirdElfSack[currentItemPriority - 1] = Unit
}
var selectedItemPriority = 0
for (index in 0..51) {
if (firstElfSack[index] != null && secondElfSack[index] != null && thirdElfSack[index] != null) {
selectedItemPriority = index + 1
break
}
}
selectedItemPriority
}.sumOf { it } | 0 | Kotlin | 0 | 0 | 817017369d257cca648974234f1e4137cdcd3138 | 3,087 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | georgiizorabov | 573,050,504 | false | {"Kotlin": 10501} | import java.util.concurrent.ConcurrentHashMap
val RPCUnitsToInt = hashMapOf(
'A' to 1,
'B' to 2,
'C' to 3,
'X' to 1,
'Y' to 2,
'Z' to 3
)
val IntToRPCUnits = hashMapOf(
0 to 'Z',
1 to 'X',
2 to 'Y',
3 to 'Z'
)
fun compare1(unit1: Char, unit2: Char): Int {
val realUnit2: Char = if (unit2 == 'Z') {
IntToRPCUnits[RPCUnitsToInt[unit1]?.plus(1)?.rem(3)]!!
} else if (unit2 == 'Y') {
IntToRPCUnits[RPCUnitsToInt[unit1]]!!
} else {
IntToRPCUnits[RPCUnitsToInt[unit1]?.minus(1)?.rem(3)]!!
}
return compare(unit1, realUnit2)
}
fun compare(unit1: Char, unit2: Char): Int {
val res = RPCUnitsToInt[unit2]
return if (RPCUnitsToInt[unit1] == RPCUnitsToInt[unit2]) {
res!! + 3
} else if (RPCUnitsToInt[unit1]?.plus(1)?.rem(3) == RPCUnitsToInt[unit2]?.rem(3)) {
res!! + 6
} else {
res!!
}
}
fun main() {
fun read(input: List<String>): List<Pair<Char, Char>> {
return input.map { str -> Pair(str[0], str[2]) }
}
fun part1(input: List<String>): Int {
return read(input).sumOf { pair -> compare(pair.first, pair.second) }
}
fun part2(input: List<String>): Int {
return read(input).sumOf { pair -> compare1(pair.first, pair.second) }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | bf84e55fe052c9c5f3121c245a7ae7c18a70c699 | 1,393 | aoc2022 | Apache License 2.0 |
src/commonMain/kotlin/com/jeffpdavidson/kotwords/model/DownsOnly.kt | jpd236 | 143,651,464 | false | {"Kotlin": 4390419, "HTML": 41919, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618} | package com.jeffpdavidson.kotwords.model
/** Extension functions to make crosswords downs-only. */
object DownsOnly {
/**
* Return a copy of this puzzle with only the down clues (usually).
*
* Solving with down clues generally works because all the theme answers, which are typically
* the longest answers in the grid, run across the grid. Thus, it's generally possible to infer
* their answers from a few of the crossing letters, even without knowing the clue. However,
* some themes have more theme material running down the grid, in which case it is "fairer" to
* solve with only the across clues.
*
* Thus, we use a rough heuristic to decide which direction of clues is more useful: if one
* direction's max word length is longer than the other's, we clear the clues in that direction;
* otherwise, we use the number of words of that max length in each direction as a tiebreaker.
* If there are an equal number of max-length words in both directions, we return the puzzle
* with only the down clues.
*/
fun Puzzle.withDownsOnly(): Puzzle {
val acrossClues = getClues("Across")
val downClues = getClues("Down")
require(acrossClues != downClues && acrossClues != null && downClues != null && clues.size == 2) {
"Cannot convert puzzle with non-standard clue lists to Downs Only"
}
val directionToClear = getDirectionToClearForDownsOnly()
return copy(
clues = when (directionToClear) {
ClueDirection.ACROSS -> listOf(clearClues(acrossClues), downClues)
ClueDirection.DOWN -> listOf(acrossClues, clearClues(downClues))
}
)
}
internal enum class ClueDirection { ACROSS, DOWN }
internal fun Puzzle.getDirectionToClearForDownsOnly(): ClueDirection {
data class WordStats(
var maxWordLength: Int = 0,
var wordsAtMaxLength: Int = 0
)
val acrossWordStats = WordStats()
val downWordStats = WordStats()
var curWordLength = 0
fun WordStats.onWordFinished() {
if (curWordLength > maxWordLength) {
maxWordLength = curWordLength
wordsAtMaxLength = 1
} else if (curWordLength == maxWordLength) {
wordsAtMaxLength++
}
curWordLength = 0
}
for (y in grid.indices) {
for (x in grid[y].indices) {
if (grid[y][x].cellType.isBlack()) {
if (curWordLength > 0) {
acrossWordStats.onWordFinished()
}
} else {
curWordLength++
}
}
if (curWordLength > 0) {
acrossWordStats.onWordFinished()
}
}
for (x in grid[0].indices) {
for (y in grid.indices) {
if (grid[y][x].cellType.isBlack()) {
if (curWordLength > 0) {
downWordStats.onWordFinished()
}
} else {
curWordLength++
}
}
if (curWordLength > 0) {
downWordStats.onWordFinished()
}
}
if (acrossWordStats.maxWordLength > downWordStats.maxWordLength) {
return ClueDirection.ACROSS
}
if (acrossWordStats.maxWordLength < downWordStats.maxWordLength
|| acrossWordStats.wordsAtMaxLength < downWordStats.wordsAtMaxLength
) {
return ClueDirection.DOWN
}
return ClueDirection.ACROSS
}
private fun clearClues(clueList: Puzzle.ClueList): Puzzle.ClueList =
clueList.copy(clues = clueList.clues.map { clue -> clue.copy(text = "-", format = "") })
} | 5 | Kotlin | 5 | 19 | c2dc23bafc7236ba076a63060e08e6dc134c8e24 | 3,879 | kotwords | Apache License 2.0 |
src/Day18.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | const val OFFSET_DAY_18 = 1
data class Cube(val x: Int, val y: Int, val z: Int)
fun getNeighbours(cube: Cube): List<Cube> {
return listOf(
Cube(cube.x - 1, cube.y, cube.z),
Cube(cube.x + 1, cube.y, cube.z),
Cube(cube.x, cube.y - 1, cube.z),
Cube(cube.x, cube.y + 1, cube.z),
Cube(cube.x, cube.y, cube.z - 1),
Cube(cube.x, cube.y, cube.z + 1)
)
}
// Breadth-first search
fun hasPathToBorder(grid:Array<Array<BooleanArray>>, startNode: Cube): Boolean {
val visitedNodes = mutableListOf<Cube>()
val queue = ArrayDeque<Cube>()
queue.add(startNode)
while (queue.isNotEmpty()) {
val currentNode = queue.removeFirst()
if (currentNode == Cube(0,0,0)) {
// There is a path to one of the corners of the grid, which means that startNode isn't in an air pocket.
return true
} else {
val neighbours = getNeighbours(currentNode)
for (neighbour in neighbours) {
if (neighbour.x + OFFSET_DAY_18 <= 0 || neighbour.y + OFFSET_DAY_18 <= 0 || neighbour.z + OFFSET_DAY_18 <= 0 ||
neighbour.x + OFFSET_DAY_18 >= grid.size - 1 || neighbour.y + OFFSET_DAY_18 >= grid[0].size - 1 || neighbour.z + OFFSET_DAY_18 >= grid[0][0].size - 1) {
// There is a path to the border, which means that startNode isn't in an air pocket.
return true
}
if (!visitedNodes.contains(neighbour) && !grid[neighbour.x + OFFSET_DAY_18][neighbour.y + OFFSET_DAY_18][neighbour.z + OFFSET_DAY_18]) {
queue.addFirst(neighbour)
}
}
visitedNodes.add(currentNode)
}
}
// There is no path found, which means that startNode is in an air pocket.
return false
}
fun main() {
fun part1(input: List<Cube>): Int {
var totalExposedSides = 0
for (cube in input) {
var exposedSides = 6
if (input.any{it.x == cube.x && it.y == cube.y && it.z - cube.z == 1}) {
exposedSides--
}
if (input.any{it.x == cube.x && it.y == cube.y && it.z - cube.z == -1}) {
exposedSides--
}
if (input.any{it.x == cube.x && it.z == cube.z && it.y - cube.y == 1}) {
exposedSides--
}
if (input.any{it.x == cube.x && it.z == cube.z && it.y - cube.y == -1}) {
exposedSides--
}
if (input.any{it.y == cube.y && it.z == cube.z && it.x - cube.x == 1}) {
exposedSides--
}
if (input.any{it.y == cube.y && it.z == cube.z && it.x - cube.x == -1}) {
exposedSides--
}
totalExposedSides += exposedSides
}
return totalExposedSides
}
fun part2(input: List<Cube>, debug: Boolean = false): Int {
var totalExposedSides = 0
val maxX = input.maxOf{it.x}
val maxY = input.maxOf{it.y}
val maxZ = input.maxOf{it.z}
val grid = Array(maxX + 1 + (2 * OFFSET_DAY_18)) {
Array(maxY + 1 + (2 * OFFSET_DAY_18)) {
BooleanArray(maxZ + 1 + (2 * OFFSET_DAY_18))}}
for (cube in input) {
grid[cube.x + OFFSET_DAY_18][cube.y + OFFSET_DAY_18][cube.z + OFFSET_DAY_18] = true
}
for ((i, cube) in input.withIndex()) {
if (debug) println("Cube number: ${i + 1}/${input.size}")
val neighbours = getNeighbours(cube)
for (neighbour in neighbours) {
if (!grid[neighbour.x + OFFSET_DAY_18][neighbour.y + OFFSET_DAY_18][neighbour.z + OFFSET_DAY_18] &&
hasPathToBorder(grid, Cube(neighbour.x, neighbour.y, neighbour.z))) {
totalExposedSides += 1
}
}
}
return totalExposedSides
}
val input = readInputAsStrings("Day18")
.map{it.split(",")}
.map{Cube(it[0].toInt(), it[1].toInt(), it[2].toInt())}
println(part1(input))
println(part2(input, true))
} | 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 4,123 | AoC2022 | Apache License 2.0 |
src/main/kotlin/Day4.kt | amitdev | 574,336,754 | false | {"Kotlin": 21489} | import java.io.File
fun main() {
val result = File("inputs/day_4.txt").useLines { computeOverlaps(it) }
println(result)
}
fun computeFullOverlaps(lines: Sequence<String>) =
lines.map { toPairs(it) }
.count { it.first.contains(it.second) || it.second.contains(it.first)}
fun computeOverlaps(lines: Sequence<String>) =
lines.map { toPairs(it) }
.count { it.first.overlaps(it.second) || it.second.overlaps(it.first)}
fun toPairs(it: String) =
it.split(",")
.map { it.split("-").map { it.toInt() } }
.map { it.toPair() }
.toPair()
fun <T> List<T>.toPair() = Pair(this[0], this[1])
fun Pair<Int, Int>.contains(that: Pair<Int, Int>) =
this.first <= that.first && this.second >= that.second
fun Pair<Int, Int>.overlaps(that: Pair<Int, Int>) =
this.first <= that.first && this.second >= that.first ||
this.first >= that.first && this.first <= that.second
| 0 | Kotlin | 0 | 0 | b2cb4ecac94fdbf8f71547465b2d6543710adbb9 | 891 | advent_2022 | MIT License |
src/main/kotlin/days/Day04.kt | Kebaan | 573,069,009 | false | null | package days
import utils.Day
import utils.asIntRange
fun main() {
Day04.solve()
}
object Day04 : Day<Int>(2022, 4) {
private fun parseGroups(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map { group ->
group.substringBefore(",").asIntRange() to group.substringAfter(",").asIntRange()
}
}
operator fun IntRange.contains(other: IntRange): Boolean {
return other.first >= first && other.last <= last
}
override fun part1(input: List<String>): Int {
val groupRanges = parseGroups(input)
return groupRanges.count { (first, second) ->
(first in second) || (second in first)
}
}
override fun part2(input: List<String>): Int {
val groupRanges = parseGroups(input)
return groupRanges.count { (first, second) -> (first intersect second).isNotEmpty() }
}
override fun doSolve() {
part1(input).let {
println(it)
check(it == 305)
}
part2(input).let {
println(it)
check(it == 811)
}
}
override val testInput = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8""".trimIndent().lines()
}
| 0 | Kotlin | 0 | 0 | ef8bba36fedbcc93698f3335fbb5a69074b40da2 | 1,294 | Advent-of-Code-2022 | Apache License 2.0 |
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/combinations.kt | ca-r0-l | 258,232,982 | true | {"Kotlin": 2272378, "HTML": 423, "Java": 153} | package io.kotest.property.arbitrary
import io.kotest.property.Arb
import io.kotest.property.Gen
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" }
// 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
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))
}
return arb {
generateSequence {
val total = weights.sum()
val n = it.random.nextInt(1, total + 1)
pick(n, allPairs.asSequence())
}
}
}
/**
* Generates random permutations of a list.
*/
fun <A> Arb.Companion.shuffle(list: List<A>) = arb {
generateSequence {
list.shuffled(it.random)
}
}
/**
* Generates a random subsequence of the input list, including the empty list.
* The returned list has the same order as the input list.
*/
fun <A> Arb.Companion.subsequence(list: List<A>) = arb {
generateSequence {
val size = it.random.nextInt(0, list.size + 1)
list.take(size)
}
}
/**
* Randomly selects one of the given gens to generate the next element.
* The input must be non-empty.
* The input gens must be infinite.
*/
fun <A> Arb.Companion.choice(vararg gens: Gen<A>): Arb<A> = arb { rs ->
val iters = gens.map { it.generate(rs).iterator() }
fun next(): Sample<A>? {
val iter = iters.shuffled(rs.random).first()
return if (iter.hasNext()) iter.next() else null
}
sequence {
while (true) {
var next: Sample<A>? = null
while (next == null)
next = next()
yield(next.value)
}
}
}
| 0 | null | 0 | 1 | e176cc3e14364d74ee593533b50eb9b08df1f5d1 | 2,336 | kotest | Apache License 2.0 |
src/day04/Day04.kt | Raibaz | 571,997,684 | false | {"Kotlin": 9423} | package day04
import readInput
fun main() {
fun String.parseLine() : Pair<IntRange, IntRange> {
val pairs = this.split(",")
val first = pairs[0].split("-")
val second = pairs[1].split("-")
return first[0].toInt() ..first[1].toInt() to second[0].toInt() .. second[1].toInt()
}
fun Pair<IntRange, IntRange>.fullyContains(): Boolean =
(this.first.contains(this.second.first) && this.first.contains(this.second.last)) ||
(this.second.contains(this.first.first) && this.second.contains(this.first.last))
fun Pair<IntRange, IntRange>.partiallyContains(): Boolean =
this.first.contains(this.second.first) || this.first.contains(this.second.last) ||
this.second.contains(this.first.first) || this.second.contains(this.first.last)
fun part1(input: List<String>): Int = input.map { it.parseLine() }.count { it.fullyContains() }
fun part2(input: List<String>): Int = input.map { it.parseLine() }.count { it.partiallyContains() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("day04/input_test")
println(part1(testInput))
val input = readInput("day04/input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 99d912f661bd3545ca9ff222ac7d93c12682f42d | 1,267 | aoc-22 | Apache License 2.0 |
src/twentytwentytwo/day4/Day04.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | package twentytwentytwo.day4
import readInput
fun main() {
fun part1(input: List<String>): Int = input.count { pair ->
val ranges = pair.split(",")
val first = ranges[0].split("-").map { it.toInt() }
val second = ranges[1].split("-").map { it.toInt() }
((first[0] <= second[0] && second[1] <= first[1]) || (second[0] <= first[0] && first[1] <= second[1]))
}
fun part2(input: List<String>): Int = input.count { pair ->
val ranges = pair.split(",")
val first = ranges[0].split("-").map { it.toInt() }
val second = ranges[1].split("-").map { it.toInt() }
if (first[0] < second[0]) {
second[0] <= first[1]
} else {
first[0] <= second[1]
}
}
val input = readInput("day4", "Day04_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 865 | advent-of-code | Apache License 2.0 |
src/questions/MajorityElement.kt | realpacific | 234,499,820 | false | null | package questions
import kotlin.test.assertEquals
/**
* Given an array nums of size n, return the majority element.
* The majority element is the element that appears more than ⌊n / 2⌋ times.
* You may assume that the majority element always exists in the array.
*
* [Source](https://leetcode.com/problems/majority-element/)
*/
private fun majorityElement(nums: IntArray): Int {
val majorityCondition = nums.size / 2
val map = mutableMapOf<Int, Int>()
for (i in 0..nums.lastIndex) {
val element = nums[i]
map[element] = (map[element] ?: 0) + 1
if (map[element]!! > majorityCondition) {
return element
}
}
return -1
}
// Source: https://leetcode.com/problems/majority-element/discuss/51613/O(n)-time-O(1)-space-fastest-solution
private fun majorityElementOptimal(nums: IntArray): Int {
// IF majority element occurs more than n/2 times and there's only one of it
var majority = nums[0]
var count = 1
for (i in 1..nums.lastIndex) { // first element is already considered, so start from 1
val elem = nums[i]
if (count == 0) {
// It wasn't the majority element
majority = elem
count++
} else if (elem == majority) {
count++
} else {
count--
}
}
return majority
}
fun main() {
assertEquals(1, majorityElementOptimal(intArrayOf(1, 1, 1, 1, 2, 3, 4, 5)))
assertEquals(5, majorityElementOptimal(intArrayOf(6, 5, 5)))
assertEquals(3, majorityElementOptimal(intArrayOf(3, 2, 3)))
assertEquals(2, majorityElementOptimal(intArrayOf(2, 2, 1, 1, 1, 2, 2)))
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 1,662 | algorithms | MIT License |
src/main/kotlin/com/github/michaelbull/advent2021/day23/Burrow.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day23
import java.util.PriorityQueue
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun Sequence<String>.toBurrow(): Burrow {
val lines = toList().dropWhile(String::isEmpty)
val hallway = lines[1].filter { it == Cell.OPEN_SPACE }.toCharArray()
val roomCapacity = lines.sumOf { line -> line.count { it == Cell.AMBER } }
return Burrow(
roomCapacity = roomCapacity,
hallway = hallway,
rooms = arrayOf(
charArrayOf(lines[3][3], lines[2][3]),
charArrayOf(lines[3][5], lines[2][5]),
charArrayOf(lines[3][7], lines[2][7]),
charArrayOf(lines[3][9], lines[2][9]),
)
)
}
data class Burrow(
val roomCapacity: Int,
val hallway: CharArray,
val rooms: Array<CharArray>,
) {
private val roomXValues = rooms.indices.map { it.toHallwayX() }
fun withExtra(extra: List<CharArray>): Burrow {
require(extra.size == 2)
require(roomCapacity == 2)
val newCapacity = roomCapacity + extra.size
val newRooms = Array(rooms.size) { roomIndex ->
CharArray(newCapacity) { i ->
when (i) {
0 -> rooms[roomIndex][0]
1 -> extra[1][roomIndex]
2 -> extra[0][roomIndex]
3 -> rooms[roomIndex][1]
else -> throw IllegalStateException()
}
}
}
return copy(
roomCapacity = newCapacity,
rooms = newRooms
)
}
fun shortestPath(): Int {
val costs = mutableMapOf<Burrow, Int>()
val queue = PriorityQueue(compareBy(costs::get))
costs[this] = 0
queue += this
while (queue.isNotEmpty()) {
val current = queue.poll()
val lowestCost = costs.getValue(current)
if (current.isComplete()) {
return lowestCost
}
for ((cost, burrow) in current.potentialBurrows()) {
val lowestPotentialCost = costs[burrow]
val cumulativeCost = lowestCost + cost
if (lowestPotentialCost == null || cumulativeCost < lowestPotentialCost) {
costs[burrow] = cumulativeCost
queue += burrow
}
}
}
throw IllegalArgumentException()
}
private fun potentialBurrows() = sequence {
roomToHallway()
hallwayToRoom()
}
private suspend fun SequenceScope<PotentialBurrow>.hallwayToRoom() {
for ((hallwayX, cell) in hallway.withIndex()) {
if (cell == Cell.OPEN_SPACE) {
continue
}
val roomIndex = roomForAmphipod(cell)
val roomX = roomIndex.toHallwayX()
val xRange = (min(hallwayX, roomX)..max(hallwayX, roomX)) - hallwayX
if (xRange.any(::isHallwayOccupied)) {
continue
}
val room = rooms[roomIndex]
if (room hasSpaceFor cell) {
val newHallway = hallway.copyOf()
val newRoom = room.copyOf(room.size + 1)
val newRooms = rooms.copyOf()
newHallway[hallwayX] = Cell.OPEN_SPACE
newRoom[newRoom.size - 1] = cell
newRooms[roomIndex] = newRoom
val newBurrow = copy(
hallway = newHallway,
rooms = newRooms
)
val stepsOut = (roomCapacity - newRoom.size) + 1
val stepsAcross = abs(roomX - hallwayX)
val steps = stepsOut + stepsAcross
val cost = steps * cell.energy()
val node = PotentialBurrow(cost, newBurrow)
yield(node)
}
}
}
private suspend fun SequenceScope<PotentialBurrow>.roomToHallway() {
for ((roomIndex, room) in rooms.withIndex()) {
if (isComplete(roomIndex, room)) {
continue
}
val amphipod = room.lastOrNull() ?: continue
for ((hallwayX, cell) in hallway.withIndex()) {
if (cell != Cell.OPEN_SPACE) {
continue
}
if (isOutsideRoom(hallwayX)) {
continue
}
val roomX = roomIndex.toHallwayX()
val xRange = min(hallwayX, roomX)..max(hallwayX, roomX)
if (xRange.any(::isHallwayOccupied)) {
continue
}
val newHallway = hallway.copyOf()
val newRoom = room.copyOf(room.size - 1)
val newRooms = rooms.copyOf()
newHallway[hallwayX] = amphipod
newRooms[roomIndex] = newRoom
val newBurrow = copy(
hallway = newHallway,
rooms = newRooms
)
val stepsAcross = abs(roomX - hallwayX)
val stepsIn = (roomCapacity - room.size) + 1
val totalSteps = stepsAcross + stepsIn
val cost = totalSteps * amphipod.energy()
yield(PotentialBurrow(cost, newBurrow))
}
}
}
private fun isComplete(): Boolean {
return rooms.withIndex().all { (roomIndex, room) ->
isComplete(roomIndex, room)
}
}
private fun isHallwayOccupied(x: Int): Boolean {
return hallway[x] != Cell.OPEN_SPACE
}
private fun Int.toHallwayX(): Int {
return (this * 2) + 2
}
private fun isComplete(roomIndex: Int, room: CharArray): Boolean {
return room.size == roomCapacity && room.all { it == amphipodForRoom(roomIndex) }
}
private fun isOutsideRoom(hallwayX: Int): Boolean {
return hallwayX in roomXValues
}
private infix fun CharArray.hasSpaceFor(amphipod: Char): Boolean {
return size < roomCapacity && all { it == amphipod }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Burrow
if (roomCapacity != other.roomCapacity) return false
if (!hallway.contentEquals(other.hallway)) return false
if (!rooms.contentDeepEquals(other.rooms)) return false
return true
}
override fun hashCode(): Int {
var result = roomCapacity
result = 31 * result + hallway.contentHashCode()
result = 31 * result + rooms.contentDeepHashCode()
return result
}
private fun Char.energy(): Int {
return when (this) {
Cell.AMBER -> 1
Cell.BRONZE -> 10
Cell.COPPER -> 100
Cell.DESERT -> 1000
else -> throw IllegalArgumentException()
}
}
private fun amphipodForRoom(roomIndex: Int): Char {
return when (roomIndex) {
0 -> Cell.AMBER
1 -> Cell.BRONZE
2 -> Cell.COPPER
3 -> Cell.DESERT
else -> throw IllegalArgumentException()
}
}
private fun roomForAmphipod(amphipod: Char): Int {
return when (amphipod) {
Cell.AMBER -> 0
Cell.BRONZE -> 1
Cell.COPPER -> 2
Cell.DESERT -> 3
else -> throw IllegalArgumentException()
}
}
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 7,502 | advent-2021 | ISC License |
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_70128.kt | boris920308 | 618,428,844 | false | {"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407} | package main.kotlin.programmers.lv01
/**
*
* https://school.programmers.co.kr/learn/courses/30/lessons/70128
*
* 문제 설명
* 길이가 같은 두 1차원 정수 배열 a, b가 매개변수로 주어집니다.
* a와 b의 내적을 return 하도록 solution 함수를 완성해주세요.
*
* 이때, a와 b의 내적은 a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1] 입니다. (n은 a, b의 길이)
*
* 제한사항
* a, b의 길이는 1 이상 1,000 이하입니다.
* a, b의 모든 수는 -1,000 이상 1,000 이하입니다.
* 입출력 예
* a b result
* [1,2,3,4] [-3,-1,0,2] 3
* [-1,0,1] [1,0,-1] -2
*
* 입출력 예 설명
* 입출력 예 #1
* a와 b의 내적은 1*(-3) + 2*(-1) + 3*0 + 4*2 = 3 입니다.
*
* 입출력 예 #2
* a와 b의 내적은 (-1)*1 + 0*0 + 1*(-1) = -2 입니다.
*/
fun main() {
solution(intArrayOf(1,2,3,4), intArrayOf(-3,-1,0,2))
}
private fun solution(a: IntArray, b: IntArray): Int {
var answer: Int = 0
for (i in a.indices) {
answer += a[i] * b[i]
}
return answer
} | 1 | Kotlin | 1 | 2 | 88814681f7ded76e8aa0fa7b85fe472769e760b4 | 1,092 | HoOne | Apache License 2.0 |
src/day16/Day16.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day16
import java.io.File
fun main() {
val data = parse("src/day16/Day16.txt")
println("🎄 Day 16 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private fun parse(path: String): List<List<Char>> =
File(path)
.readLines()
.map(String::toList)
private data class Vec2(
val x: Int,
val y: Int,
)
private data class Beam(
val position: Vec2,
val direction: Vec2,
)
private fun Beam.advance(): Beam =
copy(position = Vec2(position.x + direction.x, position.y + direction.y))
private val List<List<Char>>.w get() = this[0].size
private val List<List<Char>>.h get() = this.size
private fun List<List<Char>>.contains(beam: Beam): Boolean =
beam.position.let { (x, y) -> x >= 0 && y >= 0 && x < w && y < h }
private fun List<List<Char>>.at(beam: Beam): Char =
beam.position.let { (x, y) -> this[y][x] }
private fun solve(grid: List<List<Char>>, initialBeam: Beam): Int {
val pool = ArrayDeque<Beam>().apply { add(initialBeam) }
val cache = mutableSetOf<Beam>()
val trace = mutableSetOf<Vec2>()
while (pool.isNotEmpty()) {
var beam = pool.removeFirst()
while (grid.contains(beam) && beam !in cache) {
cache += beam
trace += beam.position
when (grid.at(beam)) {
'-' -> if (beam.direction.y != 0) {
pool += beam.copy(direction = Vec2(+1, 0))
pool += beam.copy(direction = Vec2(-1, 0))
break
}
'|' -> if (beam.direction.x != 0) {
pool += beam.copy(direction = Vec2(0, +1))
pool += beam.copy(direction = Vec2(0, -1))
break
}
'/' -> {
val (dx, dy) = beam.direction
beam = if (dx == 0) {
beam.copy(direction = Vec2(-dy, 0))
} else {
beam.copy(direction = Vec2(0, -dx))
}
}
'\\' -> {
val (dx, dy) = beam.direction
beam = if (dx == 0) {
beam.copy(direction = Vec2(dy, 0))
} else {
beam.copy(direction = Vec2(0, dx))
}
}
}
beam = beam.advance()
}
}
return trace.size
}
private fun part1(data: List<List<Char>>): Int {
return solve(data, initialBeam = Beam(Vec2(0, 0), Vec2(1, 0)))
}
private fun part2(data: List<List<Char>>): Int {
val (x0, x1) = (0 to data.w - 1)
val (y0, y1) = (0 to data.h - 1)
return maxOf(
(x0..x1).maxOf { x -> solve(data, initialBeam = Beam(Vec2(x, y0), Vec2(0, +1))) },
(x0..x1).maxOf { x -> solve(data, initialBeam = Beam(Vec2(x, y1), Vec2(0, -1))) },
(y0..y1).maxOf { y -> solve(data, initialBeam = Beam(Vec2(x0, y), Vec2(+1, 0))) },
(y0..y1).maxOf { y -> solve(data, initialBeam = Beam(Vec2(x1, y), Vec2(-1, 0))) },
)
}
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 3,304 | advent-of-code-2023 | MIT License |
src/main/kotlin/dev/tasso/adventofcode/_2021/day06/Day06.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2021.day06
import dev.tasso.adventofcode.Solution
import java.math.BigInteger
class Day06 : Solution<BigInteger> {
override fun part1(input: List<String>): BigInteger {
return(simulatePopulation(input, 80))
}
override fun part2(input: List<String>): BigInteger {
return(simulatePopulation(input, 256))
}
}
fun simulatePopulation(populationInput: List<String>, numberOfDays : Int) : BigInteger{
val population = IntRange(0, 8).map{ BigInteger.valueOf(0)}.toTypedArray()
populationInput[0].split(",").map{ it.toInt() }.forEach{ population[it] += BigInteger.valueOf(1) }
for(day in 1 .. numberOfDays ) {
val numBred = population[0]
for(position in 0 .. population.size - 2) {
population[position] = population[position+1]
if(position == 6) {
population[6] += numBred
}
}
population[population.size - 1] = numBred
}
return population.toList().sum()
}
fun Iterable<BigInteger>.sum(): BigInteger {
var sum: BigInteger = BigInteger.ZERO
for (element in this) {
sum += element
}
return sum
}
| 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 1,199 | advent-of-code | MIT License |
src/Day09.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | import kotlin.math.abs
private enum class HeadDirection(val x: Int, val y: Int) {
Up(0, 1),
UpRight(1, 1),
Right(1, 0),
DownRight(1, -1),
Down(0, -1),
DownLeft(-1, -1),
Left(-1, 0),
UpLeft(-1, 1),
}
private data class RopePosition(val x: Int, val y: Int)
private operator fun RopePosition.plus(direction: HeadDirection) = RopePosition(x = x + direction.x, y = y + direction.y)
private infix fun RopePosition.touches(other: RopePosition) = abs(x - other.x) <= 1 && abs(y - other.y) <= 1
private infix fun RopePosition.sameColumnAs(other: RopePosition) = x == other.x
private infix fun RopePosition.sameRowAs(other: RopePosition) = y == other.y
private infix fun RopePosition.leftOf(other: RopePosition) = x < other.x
private infix fun RopePosition.bottomOf(other: RopePosition) = y < other.y
private infix fun RopePosition.directionTowards(other: RopePosition) = when {
this touches other -> null
this sameColumnAs other -> when {
this bottomOf other -> HeadDirection.Up
else -> HeadDirection.Down
}
this sameRowAs other -> when {
this leftOf other -> HeadDirection.Right
else -> HeadDirection.Left
}
else -> when {
this leftOf other -> when {
this bottomOf other -> HeadDirection.UpRight
else -> HeadDirection.DownRight
}
else -> when {
this bottomOf other -> HeadDirection.UpLeft
else -> HeadDirection.DownLeft
}
}
}
private data class HeadMove(val direction: HeadDirection, val amount: Int)
private class RopeSimulator(length: Int) {
private var rope = (1..length).map { RopePosition(x = 0, y = 0) }
private val visitedByTail = mutableSetOf(rope.last())
val numberOfTouchedByTail get() = visitedByTail.size
fun moveHead(move: HeadMove) {
repeat(move.amount) { moveHead(move.direction) }
}
private fun moveHead(direction: HeadDirection) {
rope = buildList {
for (i in rope.indices) {
if (i == 0) {
// Head
add(rope.first() + direction)
} else {
// Tail
val currentTail = rope[i]
val successor = get(i - 1)
val adjustDirection = currentTail directionTowards successor
if (adjustDirection != null) {
add(currentTail + adjustDirection)
} else {
add(currentTail)
}
}
}
}
visitedByTail += rope.last()
}
}
fun main() {
fun String.toHeadDirection() = when (this) {
"U" -> HeadDirection.Up
"R" -> HeadDirection.Right
"D" -> HeadDirection.Down
"L" -> HeadDirection.Left
else -> error("Couldn't parse $this")
}
fun String.toHeadMove() =
split(' ').let { (direction, amount) -> HeadMove(direction.toHeadDirection(), amount.toInt()) }
fun part1(input: List<String>): Int {
val moves = input.map { it.toHeadMove() }
val simulator = RopeSimulator(length = 2)
moves.forEach { simulator.moveHead(it) }
return simulator.numberOfTouchedByTail
}
fun part2(input: List<String>): Int {
val moves = input.map { it.toHeadMove() }
val simulator = RopeSimulator(length = 10)
moves.forEach { simulator.moveHead(it) }
return simulator.numberOfTouchedByTail
}
check(part1(readInput("Day09_test")) == 13)
check(part2(readInput("Day09_test2")) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 3,708 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | matheusfinatti | 572,935,471 | false | {"Kotlin": 12612} | fun main() {
val input = readInput("Day08").replace("\r", "").split("\n")
input
.map(String::toList)
.map { row -> row.map(Char::digitToInt).toTypedArray() }.toTypedArray()
.also { matrix ->
matrix.map2dIndexed { i, j, _ ->
if (i == 0 || j == 0 || i == matrix.count() - 1 || j == matrix[i].count() - 1) {
1
} else {
matrix.isVisible(i, j)
}
}.sumOf { row ->
row.sumOf { it ?: 0 }
}.also(::println)
}.also { matrix ->
matrix.map2dIndexed { i, j, _ ->
matrix.scenicScore(i, j)
}.maxOf { row ->
row.maxOf { it ?: 0 }
}.also(::println)
}
}
fun Array<Array<Int>>.isVisible(x: Int, y: Int): Int {
var left = 1
val h = this[y][x]
for (i in x - 1 downTo 0) {
if (this[y][i] >= h) left = 0
}
var right = 1
for (i in x + 1 until this[y].count()) {
if (this[y][i] >= h) right = 0
}
var up = 1
for (i in y - 1 downTo 0) {
if (this[i][x] >= h) up = 0
}
var down = 1
for (i in y + 1 until count()) {
if (this[i][x] >= h) down = 0
}
return up or down or left or right
}
fun Array<Array<Int>>.scenicScore(x: Int, y: Int): Int {
val h = this[y][x]
var left = 0
for (i in x - 1 downTo 0) {
left++
if (this[y][i] >= h) break
}
var right = 0
for (i in x + 1 until this[y].count()) {
right++
if (this[y][i] >= h) break
}
var up = 0
for (i in y - 1 downTo 0) {
up++
if (this[i][x] >= h) break
}
var down = 0
for (i in y + 1 until count()) {
down++
if (this[i][x] >= h) break
}
return up * down * left * right
} | 0 | Kotlin | 0 | 0 | a914994a19261d1d81c80e0ef8e196422e3cd508 | 1,865 | adventofcode2022 | Apache License 2.0 |
src/day5/fr/Day05_2.kt | BrunoKrantzy | 433,844,189 | false | {"Kotlin": 63580} | package day5.fr
fun main() {
val testInput = day2.fr.readInputInt("input5")
// val testInput = day2.fr.readInputInt("test5")
val regex = "^(\\d+),(\\d+)\\s->\\s(\\d+),(\\d+)".toRegex()
var x1 = 0
var x2 = 0
var y1 = 0
var y2 = 0
var maxX = 0
var maxY = 0
var lstH = mutableListOf<Triple<Int, Int, Int>>()
var lstV = mutableListOf<Triple<Int, Int, Int>>()
var lstD = mutableListOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>()
testInput.forEach {
val match = regex.find(it)
x1 = match!!.groups[1]!!.value.toInt()
y1 = match.groups[2]!!.value.toInt()
x2 = match.groups[3]!!.value.toInt()
y2 = match.groups[4]!!.value.toInt()
maxX = maxOf(maxX, x1)
maxX = maxOf(maxX, x2)
maxY = maxOf(maxY, y1)
maxY = maxOf(maxY, y2)
if (x1 == x2) {
val yy1 = minOf(y1, y2)
val yy2 = maxOf(y1, y2)
val v = Triple(x1, yy1, yy2)
lstV.add(v)
}
else if (y1 == y2) {
val xx1 = minOf(x1, x2)
val xx2 = maxOf(x1, x2)
val h = Triple(y1, xx1, xx2)
lstH.add(h)
}
else {
val d: Pair<Pair<Int, Int>, Pair<Int, Int>>
if (x1 < x2) {
d = Pair(Pair(x1, y1), Pair(x2, y2))
}
else {
d = Pair(Pair(x2, y2), Pair(x1, y1))
}
lstD.add(d)
}
}
var tabVents = Array (maxY+1) { Array(maxX+1) { 0 } }
lstH.forEach {
for (i in it.second ..it.third) {
tabVents[it.first][i]++
}
}
lstV.forEach {
for (i in it.second ..it.third) {
tabVents[i][it.first]++
}
}
lstD.forEach {
var dx1 = it.first.first
var dx2 = it.second.first
var dy1 = it.first.second
var dy2 = it.second.second
var difXY = dx2 - dx1
for (i in 0..difXY) {
if (dy1 < dy2) {
tabVents[dy1+i][dx1+i]++
}
else {
tabVents[dy1-i][dx1+i]++
}
}
}
var rep = 0
tabVents.forEach {
it.forEach { it2 ->
if (it2 > 1)
rep++
}
}
println(rep)
}
| 0 | Kotlin | 0 | 0 | 0d460afc81fddb9875e6634ee08165e63c76cf3a | 2,314 | Advent-of-Code-2021 | Apache License 2.0 |
src/main/kotlin/Problem18.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | /**
* By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from
* top to bottom is 23.
*
* 3
* 7 4
* 2 4 6
* 8 5 9 3
*
* That is, 3 + 7 + 4 + 9 = 23.
*
* Find the maximum total from top to bottom of the triangle below:
*
* 75
* 95 64
* 17 47 82
* 18 35 87 10
* 20 04 82 47 65
* 19 01 23 75 03 34
* 88 02 77 73 07 63 67
* 99 65 04 28 06 16 70 92
* 41 41 26 56 83 40 80 70 33
* 41 48 72 33 47 32 37 16 94 29
* 53 71 44 65 25 43 91 52 97 51 14
* 70 11 33 28 77 73 17 78 39 68 17 57
* 91 71 52 38 17 14 91 43 58 50 27 29 48
* 63 66 04 68 89 53 67 30 73 16 69 87 40 31
* 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
*
* NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route.
* However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute
* force, and requires a clever method! ;o)
*
* https://projecteuler.net/problem=18
*/
fun main() {
println(maxSum(smallTriangle, level = 0, pos = 0))
cache.clear()
println(maxSum(triangle, level = 0, pos = 0))
}
private val cache = mutableMapOf<Pair<Int, Int>, Long>()
fun maxSum(triangle: List<List<Int>>, level: Int, pos: Int): Long {
if (level == triangle.size || pos == triangle[level].size) {
return 0
}
if (cache.containsKey(level to pos)) {
return cache[level to pos]!!
}
val sum = maxOf(
maxSum(triangle, level = level + 1, pos),
maxSum(triangle, level = level + 1, pos + 1)
) + triangle[level][pos]
cache[level to pos] = sum
return sum
}
private val smallTriangle = listOf(
listOf(3),
listOf(7, 4),
listOf(2, 4, 6),
listOf(8, 5, 9, 3),
)
private val triangle = listOf(
listOf(75),
listOf(95, 64),
listOf(17, 47, 82),
listOf(18, 35, 87, 10),
listOf(20, 4, 82, 47, 65),
listOf(19, 1, 23, 75, 3, 34),
listOf(88, 2, 77, 73, 7, 63, 67),
listOf(99, 65, 4, 28, 6, 16, 70, 92),
listOf(41, 41, 26, 56, 83, 40, 80, 70, 33),
listOf(41, 48, 72, 33, 47, 32, 37, 16, 94, 29),
listOf(53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14),
listOf(70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57),
listOf(91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48),
listOf(63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31),
listOf(4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23),
) | 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 2,666 | project-euler | MIT License |
src/main/Day05.kt | lifeofchrome | 574,709,665 | false | {"Kotlin": 19233} | package main
import readInput
fun main() {
val input = readInput("Day05")
val day5 = Day05(input)
print("Part 1: ${day5.part1()}\n")
print("Part 2: ${day5.part2()}")
}
class Day05(input: List<String>) {
private val numStacks = input[input.indexOf("") - 1].split(" ").last().toInt()
private val stacksRaw: List<List<Char>> = input.slice(0 until input.indexOf("") - 1).map { row ->
val newRow = mutableListOf<Char>()
for(i in 1 until row.length step 4) {
newRow.add(row[i])
}
for(slot in 0 until numStacks) {
if(slot > newRow.size - 1) {
newRow.add(' ')
}
}
return@map newRow
}
private var stacksInput = mutableListOf<ArrayDeque<Char>>()
private val instructions: List<String> = input.drop(input.indexOf("") + 1)
init {
for(col in 0 until numStacks) {
stacksInput.add(ArrayDeque())
for(row in stacksRaw.indices) {
stacksInput[col].addLast(stacksRaw[row][col])
}
}
stacksInput = stacksInput.map { stack -> ArrayDeque(stack.filterNot { it == ' ' }) }.toMutableList()
}
private fun makeStackCopy(input: MutableList<ArrayDeque<Char>>): MutableList<ArrayDeque<Char>> {
val out = mutableListOf<ArrayDeque<Char>>()
for(stack in input) {
val tmp = ArrayDeque<Char>()
for(item in stack) {
tmp.addLast(item)
}
out.add(tmp)
}
return out
}
private fun interpretInstruction(input: String) =
Regex("(\\d+)").findAll(input).map { it.groupValues[1].toInt() }.toList()
private fun computeFirstCrates(input: MutableList<ArrayDeque<Char>>) =
input.map { it.first() }.joinToString("")
fun part1(): String {
val stacks = makeStackCopy(stacksInput)
for(instr in instructions) {
val (qty, from, to) = interpretInstruction(instr)
for(i in 0 until qty) {
val tmp = stacks[from - 1].removeFirst()
stacks[to - 1].addFirst(tmp)
}
}
return computeFirstCrates(stacks)
}
fun part2(): String {
val stacks = makeStackCopy(stacksInput)
for(instr in instructions) {
val (qty, from, to) = interpretInstruction(instr)
val slice = stacks[from - 1].slice(0 until qty)
stacks[from - 1] = ArrayDeque(stacks[from - 1].drop(qty))
stacks[to - 1].addAll(0, slice)
}
return computeFirstCrates(stacks)
}
}
| 0 | Kotlin | 0 | 0 | 6c50ea2ed47ec6e4ff8f6f65690b261a37c00f1e | 2,608 | aoc2022 | Apache License 2.0 |
src/main/kotlin/aoc22/Day18.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc22
import aoc22.Day18Domain.CubeRange
import aoc22.Day18Runner.countExposedSides
import aoc22.Day18Runner.countExposedSidesOutside
import aoc22.Day18Solution.part1Day18
import aoc22.Day18Solution.part2Day18
import common.Space3D.Parser.toPoint3D
import common.Space3D.Point3D
import common.Year22
object Day18: Year22 {
fun List<String>.part1(): Int = part1Day18()
fun List<String>.part2(): Int = part2Day18()
}
object Day18Solution {
fun List<String>.part1Day18(): Int =
map { it.toPoint3D() }
.countExposedSides()
fun List<String>.part2Day18(): Int =
map { it.toPoint3D() }
.countExposedSidesOutside()
}
object Day18Runner {
fun List<Point3D>.countExposedSides(): Int =
sumOf { point ->
point.neighbors().count { it !in this }
}
fun List<Point3D>.countExposedSidesOutside(): Int {
val cubeRange = this.toCubeRange()
val seen = mutableSetOf<Point3D>()
fun countExposedOutside(point3D: Point3D): Int =
when {
!cubeRange.contains(point3D) || point3D in seen -> 0
point3D in this -> 1
else -> {
seen += point3D
point3D.neighbors().sumOf { next ->
countExposedOutside(next)
}
}
}
return countExposedOutside(cubeRange.firstPoint())
}
private fun List<Point3D>.toCubeRange() =
CubeRange(
x = this.toRangeWithOutside { it.x },
y = this.toRangeWithOutside { it.y },
z = this.toRangeWithOutside { it.z }
)
private fun List<Point3D>.toRangeWithOutside(fn: (Point3D) -> Int): IntRange =
this.minOf(fn) - 1..this.maxOf(fn) + 1
}
object Day18Domain {
class CubeRange(
val x: IntRange,
val y: IntRange,
val z: IntRange,
) {
fun contains(point3D: Point3D): Boolean =
point3D.x in x && point3D.y in y && point3D.z in z
fun firstPoint(): Point3D =
Point3D(
x = x.first,
y = y.first,
z = z.first
)
}
} | 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 2,212 | aoc | Apache License 2.0 |
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/problems/FB_problems.kt | nalinchhajer1 | 534,780,196 | false | {"Kotlin": 86359, "Ruby": 1605} | package com.nalin.datastructurealgorithm.problems
import com.nalin.datastructurealgorithm.ds.LinkedListNode
/**
* Find minimum value from sorted array. Note that array is shifted by some amount.
*/
fun findMinimum_shiftedSortedArray(array: Array<Int>): Int {
println(array.joinToString());
var start = 0
var end = array.size - 1
var index = -1
while (start <= end) {
val mid = start + ((end - start) shr 1)
println("mid-${mid}, start-${start}, end-${end}")
if (array[mid] <= array[end]) {
index = start
end = mid - 1
} else {
index = mid
start = mid + 1
}
}
return index
}
/**
* Insert a number in circlular linked list where elements are inserted in sorted order
*/
fun insertCircularLinkedList(
rootNode: LinkedListNode<Int>?,
value: Int,
directionAsc: Boolean = true
): LinkedListNode<Int> {
if (rootNode === null) {
return createCircularListNode(value)
}
var traverseNode: LinkedListNode<Int> = rootNode;
while (traverseNode.nextNode !== rootNode) {
val foundNode = if (traverseNode.value <= traverseNode.nextNode!!.value) {
traverseNode.value <= value && value <= traverseNode.nextNode!!.value
} else {
traverseNode.value <= value || value <= traverseNode.nextNode!!.value
}
if (foundNode) {
insertAsCircularNode(traverseNode, value)
return rootNode;
} else {
traverseNode = traverseNode.nextNode!!
}
}
insertAsCircularNode(traverseNode, value)
return rootNode;
}
private fun createCircularListNode(value: Int): LinkedListNode<Int> {
val listNode = LinkedListNode(value)
listNode.nextNode = listNode;
return listNode
}
private fun insertAsCircularNode(node: LinkedListNode<Int>, value: Int) {
val temp = node.nextNode
val newNode = createCircularListNode(value);
node.nextNode = newNode
newNode.nextNode = temp
}
/**
* Rotational Cipher : Rotate alphabet / number by k digit
*/
fun rotateCipher(text: String, digit: Int): String {
var output = StringBuilder()
for (ch in text) {
if ('a' >= ch && ch <= 'z') {
output.append(ch + digit)
} else if ('A' >= ch && ch <= 'Z') {
output.append(ch + digit)
} else if ('0' >= ch && ch <= '9') {
output.append(ch + digit)
} else {
output.append(ch + digit)
}
}
return output.toString()
}
/**
Note: arrayTo have arrayFrom.size empty space at last
We have two sorted arrays of integers
A has empty slots at the end of it. It has exactly as many empty slots as there are elements in B.
Your goal is to merge the elements from B to A that array contains all of the elements in sorted order. Optimise for speed and memory usage.
**/
fun mergeSortedArray(arrayTo: Array<Int?>, arrayFrom: Array<Int>): Array<Int?> {
// TODO: check for em
if (arrayFrom.size == 0) {
// then nothing to merge
return arrayTo
}
var pointer = arrayTo.size - 1 // 2
var pointerTo = arrayTo.size - arrayFrom.size - 1 // -1
var pointerFrom = arrayFrom.size - 1 // 2
while (pointer >= 0) {
if (pointerFrom < 0) {
break;
}
if (pointerTo >= 0 && arrayTo[pointerTo]!! > arrayFrom[pointerFrom]) {
arrayTo[pointer] = arrayTo[pointerTo]
pointerTo--
} else {
arrayTo[pointer] = arrayFrom[pointerFrom]
pointerFrom--
}
pointer--
// fast forward
if (pointerTo < 0 && pointerFrom > 0) {
while (pointerFrom >= 0) {
arrayTo[pointer] = arrayFrom[pointerFrom]
pointerFrom--
pointer--
}
}
}
return arrayTo
}
/*
We have a game in which consecutive duplicate pieces of the same type cancel each other out and remaining pieces slide in, until no more pieces can be removed.
Given a board, represented by a string, return the final state of the board after playing the game.
Example 1:
Input: "abbba"
Output: "" ("abbba" => "aa" => "")
Example 2:
Input: "ab"
Output: "ab"
*/
fun mergeDuplicateChar(str: String): String {
val stack = ArrayDeque<Char>()
var foundDuplicate = false
var pointer = 0
while (pointer < str.length) {
if (stack.lastOrNull() == str[pointer]) {
foundDuplicate = true
} else {
if (foundDuplicate == true) {
stack.removeLast()
foundDuplicate = false
continue
}
stack.addLast(str[pointer])
}
if (foundDuplicate && pointer == str.length - 1) {
stack.removeLast()
break
}
pointer++
}
return stack.joinToString("")
}
/**
Given a string S consisting of lowercase English characters, determine if you can make it a palindrome by removing at most 1 character.
tacocats --> True # tacocats --> tacocat
racercar --> True # racercar --> racecar, racrcar
kbayak --> True # kbayak --> kayak
acbccba --> True # acbccba --> abccba
abccbca --> True # abccbca --> abccba
abcd --> False
btnnure --> False
*/
fun findPalindomeWithErrorProbabaility1(
str: String,
startPos: Int? = null,
endPos: Int? = null,
isForced: Boolean = false
): Boolean {
var startPointer = startPos ?: 0
var endPointer = endPos ?: (str.length - 1)
while (startPointer <= endPointer) {
if (str[startPointer] == str[endPointer]) {
if (startPointer == endPointer || startPointer == endPointer + 1) {
return true
}
startPointer++
endPointer--
} else {
// break into 2
if (isForced) {
return false
} else if (findPalindomeWithErrorProbabaility1(
str,
startPointer + 1,
endPointer,
true
)
) {
return true
} else return findPalindomeWithErrorProbabaility1(
str,
startPointer,
endPointer - 1,
true
)
}
}
return true;
}
/**
Given a sequence of non-negative integers and an integer total target, return whether a continuous sequence of integers sums up to target.
[1, 3, 1, 4, 23], 8 : True (because 3 + 1 + 4 = 8)
[1, 3, 1, 4, 23], 7 : False
*/
// [1, 3, 1, 4, 23, 5, 6], 11
// [1,2, 10, 23]
// windowing ->
// if element to add > target else try sink the window
// if window size < taget move to next element
// if next element > target -> ignore the windo
// [1, 3, 1, 4, 23, 5, 6], 11
fun sumOfConsecutiveElement(array: List<Int>, target: Int): Boolean {
var windowSum = 0 // 9
var windowStart = 0 // 0
var windowEnd = 0 // 4
while (windowStart < array.size) {
val nextElement = array[windowEnd]
if (nextElement > target) {
// moving to next set
windowStart = windowEnd + 1
windowEnd = windowStart
windowSum = 0
if (windowEnd >= array.size) {
break;
}
}
if (windowSum + array[windowEnd] == target) {
return true;
}
if (windowSum + array[windowEnd] < target) {
// increase
windowSum += array[windowEnd]
windowEnd++
if (windowEnd >= array.size) {
break;
}
} else {
// sink
if (windowStart + 1 < windowEnd) {
windowSum -= array[windowStart]
windowStart++
}
}
}
return false
}
| 0 | Kotlin | 0 | 0 | eca60301dab981d0139788f61149d091c2c557fd | 7,866 | kotlin-ds-algo | MIT License |
src/main/kotlin/nl/kelpin/fleur/advent2018/Day07.kt | fdlk | 159,925,533 | false | null | package nl.kelpin.fleur.advent2018
import java.util.*
class Day07(val input: List<String>, val baseTimeToCompletion: Int = 60, val workers: Int = 5) {
companion object {
private val dependencyRE = Regex("""Step (\w) must be finished before step (\w) can begin\.""")
}
private fun parse(): Map<Char, Set<Char>> {
val dependencies: Map<Char, Set<Char>> = input
.mapNotNull(dependencyRE::matchEntire)
.map { it.destructured.let { (a, b) -> b[0] to a[0] } }
.groupBy { it.first }
.mapValues { it.value.fold(setOf<Char>()) { acc, dependency -> acc + dependency.second } }
val steps = dependencies.values.flatten().union(dependencies.keys)
return steps
.map { it to (dependencies[it] ?: emptySet()) }
.toMap()
}
val dependencies: Map<Char, Set<Char>> = parse()
fun nextStep(completed: String, current: List<Char> = emptyList()): Char? =
dependencies
.filterKeys { !completed.contains(it) }
.filterKeys { !current.contains(it) }
.filterValues { it.all { dependency -> completed.contains(dependency) } }
.keys
.min()
tailrec fun part1(completed: String = ""): String {
val next = nextStep(completed) ?: return completed
return part1(completed + next)
}
data class Assignment(val step: Char, val started: Int)
private fun Assignment.done(): Int = started + (step - 'A') + baseTimeToCompletion + 1
data class State(val completed: String = "", val currentTime: Int = 0, val assignments: Set<Assignment> = emptySet())
private fun State.nextStep(): Char? = nextStep(completed, assignments.map(Assignment::step))
private fun State.done(): Boolean = assignments.isEmpty() && nextStep() == null
private fun State.assignWorker(): State? = Optional.ofNullable(nextStep())
.filter { assignments.size < workers }
.map { Assignment(it, currentTime) }
.map { copy(assignments = assignments + it) }
.orElse(null)
private fun State.wait(): State {
val firstDone = assignments.minBy { it.done() }!!
return copy(assignments = assignments - firstDone,
currentTime = firstDone.done(),
completed = completed + firstDone.step)
}
tailrec fun part2(state: State = State()): Int =
if (state.done()) state.currentTime
else part2(state.assignWorker() ?: state.wait())
} | 0 | Kotlin | 0 | 3 | a089dbae93ee520bf7a8861c9f90731eabd6eba3 | 2,590 | advent-2018 | MIT License |
src/day04/Day04.kt | skokovic | 573,361,100 | false | {"Kotlin": 12166} | package day04
import readInput
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
val pairRegex = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex()
input.forEach {
val (sx, ex, sy, ey) = pairRegex.matchEntire(it)!!.destructured
val (startX, endX) = sx.toInt() to ex.toInt()
val (startY, endY) = sy.toInt() to ey.toInt()
if (startX <= startY && endX >= endY) sum++
else if (startY <= startX && endY >= endX) sum ++
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
val pairRegex = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex()
input.forEach {
val (sx, ex, sy, ey) = pairRegex.matchEntire(it)!!.destructured
val (startX, endX) = sx.toInt() to ex.toInt()
val (startY, endY) = sy.toInt() to ey.toInt()
if (startX <= startY && endX >= endY) sum++
else if (startY <= startX && endY >= endX) sum ++
else if (startY > startX && startY <= endX) sum++
else if (startX > startY && startX <= endY) sum++
}
return sum
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fa9aee3b5dd09b06bfd5c232272682ede9263970 | 1,257 | advent-of-code-2022 | Apache License 2.0 |
src/cn/leetcode/codes/simple144/Simple144.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple144
import cn.leetcode.codes.common.TreeNode
import cn.leetcode.codes.createTreeNode
import cn.leetcode.codes.out
import cn.leetcode.codes.outTreeNote
import java.util.*
import kotlin.collections.ArrayList
fun main() {
val nums = arrayOf<Int?>(1, 4, 3, 2)
val treeNode = createTreeNode(nums)
outTreeNote(treeNode)
val re = preorderTraversal(treeNode)
val re2 = preorderTraversal2(treeNode)
out("re = $re")
out("re2 = $re2")
}
/*
144. 二叉树的前序遍历
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[1,2]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶:递归算法很简单,你可以通过迭代算法完成吗?
*/
//递归解法
//前序遍历 根节点 -> 左子树 -> 右子树
fun preorderTraversal(root: TreeNode?): List<Int> {
val list = ArrayList<Int>()
if (root == null) return list
traversal(root, list)
return list
}
fun traversal(root: TreeNode?, list: ArrayList<Int>) {
if (root == null) return
list.add(root.`val`)
traversal(root.left, list)
traversal(root.right, list)
}
//迭代解法
fun preorderTraversal2(root: TreeNode?): List<Int> {
val list = ArrayList<Int>()
if (root == null) return list
//使用队列存放树
val deque = LinkedList<TreeNode>()
var node = root
while (!deque.isEmpty() || node != null) {
while (node != null){
//加入当前根节点数据
list.add(node.`val`)
//将当前节点 压入栈内
deque.push(node)
//继续遍历左子树
node = node.left
}
//从底部弹出节点
node = deque.pop()
//遍历右子树
node = node.right
}
return list
} | 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 2,083 | LeetCodeSimple | Apache License 2.0 |
src/main/kotlin/0017.kts | ktgw0316 | 373,665,309 | false | null | // http://www.odz.sakura.ne.jp/projecteuler/?Problem+17
// ISBN978-4-04-893053-6 の 1.4 節を参照
val units = listOf("zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine")
val teens = listOf("ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen")
val tens = listOf("twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety")
fun convert1(n: Int): String = units[n]
//fun digit2(n: Int): Pair<Int, Int> = pairOf(n / 10, n % 10)
//fun convert2(n: Int): String = convine2(digit2(n))
//fun conbine2(p: Pair<Int, Int>): String = conbine2(p.first, p.second)
//fun conbine2(t: Int, u: Int): String = when {
// t == 0 -> units[u]
// t == 1 -> teens[u]
// u == 0 -> tens[t]
// else -> tens[t] + "-" + units[u]
//}
fun convert2(n: Int): String {
val t = n / 10
val u = n % 10
return when {
t == 0 -> units[u]
t == 1 -> teens[u]
u == 0 -> tens[t - 2]
else -> tens[t - 2] + "-" + units[u]
}
}
fun convert3(n: Int): String {
val h = n / 100
val t = n % 100
return when {
h == 0 -> convert2(t)
t == 0 -> units[h] + " handred"
else -> units[h] + " handred and " + convert2(t)
}
}
fun convert(n: Int): String {
val k = n / 1000
val h = n % 1000
return when {
k == 0 -> convert3(h)
h == 0 -> convert3(k) + " thausand"
else -> convert3(k) + " thausand" + link(h) + convert3(h)
}
}
fun link(h: Int): String = if (h < 100) " and " else " "
fun write(n: Int): String = convert(n)
// println(write(342))
// println(write(115))
println((1..1000)
.map(::write)
// .onEach { println(it) } // test
.map { it.count { it != ' ' && it != '-' }}
.sum()
.also { assert(it == 21124) }
) | 0 | Kotlin | 0 | 0 | 1dc3b1bbb647a0541393eedf12be798e5b0ef84a | 1,872 | EulerKotlin | Creative Commons Zero v1.0 Universal |
src/Day01.kt | mpylypovych | 572,998,434 | false | {"Kotlin": 6455} | fun main() {
fun split(input: List<String>) = input
.flatMapIndexed { index, x ->
when {
index == 0 || index == input.lastIndex -> listOf(index)
x.isEmpty() -> listOf(index - 1, index + 1)
else -> emptyList()
}
}
.windowed(size = 2, step = 2) { (from, to) -> input.slice(from..to) }
fun part1(input: List<String>) = split(input)
.maxOfOrNull { it.sumOf { it.toInt() } }
fun part2(input: List<String>) = split(input)
.map { it.sumOf { it.toInt() } }
.sorted()
.takeLast(3)
.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 733b35c3f4eea777a5f666c804f3c92d0cc9854b | 874 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinSpeedToArriveOnTime.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.ceil
/**
* 1870. Minimum Speed to Arrive on Time
* @see <a href="https://leetcode.com/problems/minimum-speed-to-arrive-on-time/">Source</a>
*/
fun interface MinSpeedToArriveOnTime {
operator fun invoke(dist: IntArray, hour: Double): Int
}
/**
* Approach: Binary Search
*/
class MinSpeedToArriveOnTimeBS : MinSpeedToArriveOnTime {
companion object {
private const val UPPER_BOUND = 10000000
}
override operator fun invoke(dist: IntArray, hour: Double): Int {
var left = 1
var right = UPPER_BOUND
var minSpeed = -1
while (left <= right) {
val mid = (left + right) / 2
// Move to the left half.
if (calculateRequiredTime(dist, mid) <= hour) {
minSpeed = mid
right = mid - 1
} else {
// Move to the right half.
left = mid + 1
}
}
return minSpeed
}
private fun calculateRequiredTime(dist: IntArray, speed: Int): Double {
var time = 0.0
for (i in dist.indices) {
val t = dist[i].toDouble() / speed.toDouble()
// Round off to the next integer, if not the last ride.
time += if (i == dist.size - 1) t else ceil(t)
}
return time
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,973 | kotlab | Apache License 2.0 |
src/Day03.kt | 0xBuro | 572,308,139 | false | {"Kotlin": 4929} | fun main() {
fun part1(input: List<String>): Int {
return input.map {
it.substring(0..it.length / 2) to it.substring(it.length / 2 until it.length) }
.map { (firstHalf, secondHalf) ->
firstHalf.toSet().intersect(secondHalf.toSet()).first() }
.map { 1 + if (it.isUpperCase()) it - 'A' + 26 else it - 'a' }
.sumOf { it }
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3) { (r1, r2, r3) ->
r1.toSet().intersect(r2.toSet()).intersect(r3.toSet()).first() }
.map { 1 + if(it.isUpperCase()) it - 'A' + 26 else it - 'a' }
.sumOf { it }
}
//val testInput = readInputAsListOfString("rucksack")
//check(part1(testInput) == 157)
//check(part2(testInput) == 70)
val input = readInputAsListOfString("rucksack")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c05c4db78e24fc36f6f112bc1e8cf24ad5fd7698 | 915 | Advent-of-Kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestPathLength.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Queue
/**
* 847. Shortest Path Visiting All Nodes
* @see <a href="https://leetcode.com/problems/shortest-path-visiting-all-nodes">Source</a>
*/
fun interface ShortestPathLength {
operator fun invoke(graph: Array<IntArray>): Int
}
class ShortestPathLengthBFS : ShortestPathLength {
override fun invoke(graph: Array<IntArray>): Int {
val n = graph.size
val allVisitedMask = (1 shl n) - 1
val queue: Queue<Pair<Int, Pair<Int, Int>>> = java.util.LinkedList() // Pair<currNode, Pair<dist, mask>>
val seen = mutableSetOf<Pair<Int, Int>>() // Pair<currNode, mask as path>
// Initially push all nodes in the queue to start the path with all nodes
for (i in 0 until n) {
queue.offer(Pair(i, Pair(0, 1 shl i)))
seen.add(Pair(i, 1 shl i))
}
while (queue.isNotEmpty()) {
val curr = queue.poll()
val node = curr.first
val dist = curr.second.first
val mask = curr.second.second
// If all nodes are visited
if (mask == allVisitedMask) return dist
// Go through all neighbors
for (nei in graph[node]) {
val nextMask = mask or (1 shl nei)
if (Pair(nei, nextMask) !in seen) {
queue.offer(Pair(nei, Pair(dist + 1, nextMask)))
seen.add(Pair(nei, nextMask))
}
}
}
return 0
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,136 | kotlab | Apache License 2.0 |
app/src/main/kotlin/aoc2021/day06/Day06.kt | dbubenheim | 435,284,482 | false | {"Kotlin": 31242} | package aoc2021.day06
import aoc2021.toFile
class Day06 {
companion object {
@JvmStatic
fun lanternfishPart1() = "input-day06.txt".toFile()
.readLines()
.first()
.split(",")
.map { it.toInt() }
.groupingBy { it }
.eachCount()
.map { it.key to it.value.toLong() }
.toMap()
.lanternfish()
@JvmStatic
fun lanternfishPart2() = "input-day06.txt".toFile()
.readLines()
.first()
.split(",")
.map { it.toInt() }
.groupingBy { it }
.eachCount()
.map { it.key to it.value.toLong() }
.toMap()
.lanternfish(256)
@JvmStatic
fun main(args: Array<String>) {
println(lanternfishPart1())
println(lanternfishPart2())
}
}
}
private fun Map<Int, Long>.lanternfish(days: Int = 80): Long {
println("initial state: ${this.toSortedMap()}")
var numbers = this
repeat(days) { day ->
val timers = numbers.keys.sorted()
val hasZeros = timers.contains(0)
val currentNumbers = numbers.toMutableMap()
val zeroCount = numbers[0] ?: 0
timers.forEach { timer ->
val count = currentNumbers[timer] ?: 0
when (timer) {
0 -> currentNumbers[0] = 0
else -> {
currentNumbers[timer] = currentNumbers[timer]?.minus(count) ?: 0
currentNumbers[timer - 1] = currentNumbers[timer - 1]?.plus(count) ?: count
}
}
println("timer[$timer]: ${currentNumbers.toSortedMap()}")
}
if (hasZeros) {
currentNumbers[6] = currentNumbers[6]?.plus(zeroCount) ?: zeroCount
currentNumbers[8] = currentNumbers[8]?.plus(zeroCount) ?: zeroCount
}
numbers = currentNumbers
println("day[${day + 1}]: ${numbers.toSortedMap()}")
}
return numbers.values.sum()
}
| 9 | Kotlin | 0 | 0 | 83a93845ebbc1a6405f858214bfa79b3448b932c | 2,059 | advent-of-code-2021 | MIT License |
src/Day18.kt | felldo | 572,233,925 | false | {"Kotlin": 76496} | import kotlin.system.measureNanoTime
data class Point(val x: Int, val y: Int, val z: Int, var visited: Boolean = false)
fun main() {
fun part1(input: List<String>): Int {
val cubes = mutableListOf<Point>()
var totalExposed = 0
for (line in input) {
val nums = line.split(",").map { it.toInt() }
cubes.add(Point(nums[0], nums[1], nums[2]))
}
for (cube in cubes) {
val checks = listOf(-1, 1)
for (check in checks) {
if (cubes.none { it.x == cube.x + check && it.y == cube.y && it.z == cube.z }) {
totalExposed++
}
if (cubes.none { it.x == cube.x && it.y == cube.y + check && it.z == cube.z }) {
totalExposed++
}
if (cubes.none { it.x == cube.x && it.y == cube.y && it.z == cube.z + check }) {
totalExposed++
}
}
}
return totalExposed
}
fun part2(input: List<String>): Int {
val cubes = mutableListOf<Point>()
for (line in input) {
val nums = line.split(",").map { it.toInt() }
cubes.add(Point(nums[0], nums[1], nums[2]))
}
val minX = cubes.minOf { it.x } - 1
val maxX = cubes.maxOf { it.x } + 1
val minY = cubes.minOf { it.y } - 1
val maxY = cubes.maxOf { it.y } + 1
val minZ = cubes.minOf { it.z } - 1
val maxZ = cubes.maxOf { it.z } + 1
val void = mutableListOf<Point>()
for (x in minX..maxX) {
for (y in minY..maxY) {
for (z in minZ..maxZ) {
void.add(Point(x, y, z))
}
}
}
for (cube in cubes) {
void.remove(cube)
}
val first = void.find { it.x == minX }
val q = mutableListOf<Point>()
q.add(first!!)
while (q.isNotEmpty()) {
val next = q.removeFirst()
if (!next.visited) {
next.visited = true
val checks = listOf(-1, 1)
for (check in checks) {
var neighbor = void.find { it.x == next.x + check && it.y == next.y && it.z == next.z }
if (neighbor != null) {
q.add(neighbor)
}
neighbor = void.find { it.x == next.x && it.y == next.y + check && it.z == next.z }
if (neighbor != null) {
q.add(neighbor)
}
neighbor = void.find { it.x == next.x && it.y == next.y && it.z == next.z + check }
if (neighbor != null) {
q.add(neighbor)
}
}
}
}
var totalExposed = 0
for (v in void.filter { it.visited }) {
for (c in cubes) {
if (kotlin.math.abs(v.x - c.x) == 1 && v.y == c.y && v.z == c.z) {
totalExposed++
}
if (v.x == c.x && kotlin.math.abs(v.y - c.y) == 1 && v.z == c.z) {
totalExposed++
}
if (v.x == c.x && v.y == c.y && kotlin.math.abs(v.z - c.z) == 1) {
totalExposed++
}
}
}
return totalExposed
}
val input = readInput("Day18")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0ef7ac4f160f484106b19632cd87ee7594cf3d38 | 3,516 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day22.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | private enum class Tile {
VOID, WALL, OPEN;
}
private sealed interface Command {
object TurnLeft : Command {
override fun toString(): String = "L"
}
object TurnRight : Command {
override fun toString(): String = "R"
}
data class Move(val distance: Int) : Command {
override fun toString(): String = distance.toString()
}
}
private enum class Facing {
RIGHT, DOWN, LEFT, UP;
fun turnRight() = when (this) {
RIGHT -> DOWN
DOWN -> LEFT
LEFT -> UP
UP -> RIGHT
}
fun turnLeft() = when (this) {
RIGHT -> UP
DOWN -> RIGHT
LEFT -> DOWN
UP -> LEFT
}
}
fun main() {
data class Point(val row: Int, val col: Int)
fun Point.next(facing: Facing) = when (facing) {
Facing.RIGHT -> copy(col = col + 1)
Facing.DOWN -> copy(row = row + 1)
Facing.LEFT -> copy(col = col - 1)
Facing.UP -> copy(row = row - 1)
}
data class State(val position: Point, val facing: Facing)
fun Array<Array<Tile>>.tileAt(point: Point): Tile = getOrNull(point.row)?.getOrNull(point.col) ?: Tile.VOID
fun readCommands(path: String): List<Command> = buildList {
var currentNumber = 0
for (c in path) {
if (c.isDigit()) {
currentNumber = currentNumber * 10 + c.digitToInt()
} else {
if (currentNumber > 0) {
add(Command.Move(currentNumber))
currentNumber = 0
}
add(
when (c) {
'L' -> Command.TurnLeft
'R' -> Command.TurnRight
else -> error("Unrecognized character: $c")
}
)
}
}
if (currentNumber > 0) {
add(Command.Move(currentNumber))
}
}
fun readGrid(input: List<String>): Array<Array<Tile>> = Array(input.size) { row ->
Array(input[row].length) { col ->
when (input[row][col]) {
'#' -> Tile.WALL
'.' -> Tile.OPEN
else -> Tile.VOID
}
}
}
fun findPassword(grid: Array<Array<Tile>>, commands: List<Command>, moveForward: (State) -> State): Int {
var currentState = State(Point(0, grid[0].indexOf(Tile.OPEN)), Facing.RIGHT)
for (command in commands) {
when (command) {
Command.TurnLeft -> currentState = currentState.let { it.copy(facing = it.facing.turnLeft()) }
Command.TurnRight -> currentState = currentState.let { it.copy(facing = it.facing.turnRight()) }
is Command.Move -> {
for (x in 0 until command.distance) {
val next = moveForward(currentState)
when (grid.tileAt(next.position)) {
Tile.OPEN -> currentState = next
Tile.WALL -> break
Tile.VOID -> error("out of bounds")
}
}
}
}
}
val (row, col) = currentState.position
return 1000 * (row + 1) + 4 * (col + 1) + currentState.facing.ordinal
}
fun part1(input: List<String>): Int {
val grid = readGrid(input.takeWhile { it.isNotBlank() })
val commands = readCommands(input.last { it.isNotBlank() })
fun State.next(): State {
val nextPosition = position.next(facing)
return copy(position = when (grid.tileAt(nextPosition)) {
Tile.OPEN, Tile.WALL -> nextPosition
Tile.VOID -> when (facing) {
Facing.RIGHT -> position.copy(col = grid[position.row].indexOfFirst { it != Tile.VOID })
Facing.DOWN -> position.copy(row = grid.indexOfFirst { it.getOrElse(position.col) { Tile.VOID } != Tile.VOID })
Facing.LEFT -> position.copy(col = grid[position.row].indexOfLast { it != Tile.VOID })
Facing.UP -> position.copy(row = grid.indexOfLast { it.getOrElse(position.col) { Tile.VOID } != Tile.VOID })
}
})
}
return findPassword(grid, commands) { it.next() }
}
fun part2(input: List<String>, warps: Map<State, State>): Int
{
val grid = readGrid(input.takeWhile { it.isNotBlank() })
val commands = readCommands(input.last { it.isNotBlank() })
return findPassword(grid, commands) {
val nextPosition = it.position.next(it.facing)
val nextState = it.copy(position = nextPosition)
when(grid.tileAt(nextPosition)) {
Tile.WALL, Tile.OPEN -> nextState
Tile.VOID -> warps.getValue(nextState)
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day22_test")
check(part1(testInput) == 6032)
val testWarps = (0..3).asSequence().flatMap {
sequenceOf(
// top
State(Point(-1, 8 + it), Facing.UP) to State(Point(4, 3 - it), Facing.DOWN),
State(Point(it, 7), Facing.LEFT) to State(Point(4, 4 + it), Facing.DOWN),
State(Point(it, 12), Facing.RIGHT) to State(Point(11 - it, 15), Facing.LEFT),
// mid left
State(Point(3, it), Facing.UP) to State(Point(0, 11 - it), Facing.DOWN),
State(Point(4 + it, -1), Facing.LEFT) to State(Point(11, 15 - it), Facing.UP),
State(Point(8, it), Facing.DOWN) to State(Point(11, 11 - it), Facing.UP),
// mid mid
State(Point(3, 4 + it), Facing.UP) to State(Point(it, 8), Facing.RIGHT),
State(Point(8, 4 + it), Facing.DOWN) to State(Point(11 - it, 8), Facing.RIGHT),
// mid right
State(Point(4 + it, 12 ), Facing.RIGHT) to State(Point(8, 15 - it), Facing.DOWN),
// bottom left
State(Point(8 + it, 7), Facing.LEFT) to State(Point(7, 7 - it), Facing.UP),
State(Point(12, 8 + it), Facing.DOWN) to State(Point(7, 3 - it), Facing.UP),
// bottom right
State(Point(7, 11 + it), Facing.UP) to State(Point(7 - it, 11), Facing.LEFT),
State(Point(8 + it, 15), Facing.RIGHT) to State(Point(3 - it, 11), Facing.LEFT),
State(Point(12, 11 + it), Facing.DOWN) to State(Point(7 - it, 0), Facing.RIGHT)
)
}.toMap()
check(part2(testInput, testWarps) == 5031)
val input = readInput("Day22")
println(part1(input))
val warps = (0..49).asSequence().flatMap {
sequenceOf(
// top left
State(Point(-1, 50 + it), Facing.UP) to State(Point(150 + it, 0), Facing.RIGHT),
State(Point(it, 49), Facing.LEFT) to State(Point(149 - it, 0), Facing.RIGHT),
// top right
State(Point(-1, 100 + it), Facing.UP) to State(Point(199, it), Facing.UP),
State(Point(it, 150), Facing.RIGHT) to State(Point(149 - it, 99), Facing.LEFT),
State(Point(50, 100 + it), Facing.DOWN) to State(Point(50 + it, 99), Facing.LEFT),
// upper mid
State(Point(50 + it, 49), Facing.LEFT) to State(Point(100, it), Facing.DOWN),
State(Point(50 + it, 100), Facing.RIGHT) to State(Point(49, 100 + it), Facing.UP),
// lower mid left
State(Point(99, it), Facing.UP) to State(Point(50 + it, 50), Facing.RIGHT),
State(Point(100 + it, -1), Facing.LEFT) to State(Point(49 - it, 50), Facing.RIGHT),
// lower mid right
State(Point(100 + it, 100), Facing.RIGHT) to State(Point(49 - it, 149), Facing.LEFT),
State(Point(150, 50 + it), Facing.DOWN) to State(Point(150 + it, 49), Facing.LEFT),
// bottom
State(Point(150 + it, -1), Facing.LEFT) to State(Point(0, 50 + it), Facing.DOWN),
State(Point(150 + it, 50), Facing.RIGHT) to State(Point(149, 50 + it), Facing.UP),
State(Point(200, it), Facing.DOWN) to State(Point(0, 100 + it), Facing.DOWN)
)
}.toMap()
println(part2(input, warps))
}
| 0 | Kotlin | 0 | 0 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 8,214 | advent-of-code-22 | Apache License 2.0 |
lib/src/main/kotlin/aoc/day16/Day16.kt | Denaun | 636,769,784 | false | null | @file:Suppress("UnstableApiUsage")
package aoc.day16
import java.util.*
import kotlin.math.max
fun part1(input: String): Int = maximizeSingleReleasedPressure(parse(input), Valve("AA"), 30)!!
fun part2(input: String): Int = maximizeDoubleReleasedPressure(parse(input), Valve("AA"), 26)
fun maximizeSingleReleasedPressure(scan: Scan, initialValve: Valve, minutes: Int): Int? {
val simplifiedScan = scan.simplify(initialValve)
val states = PriorityQueue(compareByDescending(simplifiedScan::upperBoundReleasedPressure))
states.add(initialState(initialValve, minutes))
while (states.isNotEmpty()) {
val state = states.remove()
val neighbors = simplifiedScan.tunnels.adjacentNodes(state.valve)
.mapNotNull { state.moveToAndOpen(it, simplifiedScan) }
states.addAll(neighbors)
if (neighbors.isEmpty()) {
return state.busyWait(simplifiedScan).releasedPressure
}
}
return null
}
fun maximizeDoubleReleasedPressure(scan: Scan, initialValve: Valve, minutes: Int): Int {
val simplifiedScan = scan.simplify(initialValve)
val solutions = mutableMapOf<Set<Valve>, Int>()
val toVisit = mutableListOf(initialState(initialValve, minutes))
while (toVisit.isNotEmpty()) {
val state = toVisit.removeFirst()
solutions.merge(state.openValves, state.busyWait(simplifiedScan).releasedPressure, ::max)
toVisit.addAll(simplifiedScan.tunnels.adjacentNodes(state.valve)
.mapNotNull { state.moveToAndOpen(it, simplifiedScan) })
}
return solutions.maxOf { (valves, releasedPressure) ->
solutions.filterKeys { (valves intersect it).isEmpty() }.values.maxOf(releasedPressure::plus)
}
}
fun SimplifiedScan.upperBoundReleasedPressure(state: State): Int {
var releasedPressure = state.releasedPressure
var totalFlowRate = state.flowRate(flowRates)
var minutesLeft = state.minutesLeft
for (flowRate in flowRates.filterKeys { it !in state.openValves }.values.sortedDescending()) {
val minutesToMoveAndOpen = 2
minutesToMoveAndOpen.takeIf { it <= minutesLeft }?.let {
releasedPressure += totalFlowRate * it
totalFlowRate += flowRate
minutesLeft -= it
}
}
return releasedPressure + totalFlowRate * minutesLeft
}
data class State(
val valve: Valve,
val minutesLeft: Int,
val releasedPressure: Int = 0,
val openValves: Set<Valve> = emptySet(),
) {
fun moveToAndOpen(other: Valve, scan: SimplifiedScan): State? =
scan.tunnels.edgeValue(valve, other).orNull()
?.takeIf { it < minutesLeft && other !in openValves }?.let {
State(
other,
minutesLeft - it - 1,
releasedPressure + flowRate(scan.flowRates) * (it + 1),
openValves + other,
)
}
fun busyWait(scan: SimplifiedScan) = State(
valve,
0,
releasedPressure + flowRate(scan.flowRates) * minutesLeft,
openValves,
)
fun flowRate(flowRates: Map<Valve, Int>): Int =
flowRates.filterKeys(openValves::contains).values.sum()
}
fun initialState(valve: Valve, minutesLeft: Int) = State(valve, minutesLeft, 0, emptySet())
fun <T> Optional<T>.orNull(): T? = orElse(null) | 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 3,337 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day16.kt | tobiasae | 434,034,540 | false | {"Kotlin": 72901} | class Day16 : Solvable("16") {
override fun solveA(input: List<String>): String {
val bits = input.first().toBinary()
val p = Packet.parsePacket(bits.toConsumer())
fun getVersionSum(p: Packet): Int {
var sum = p.version
if (p is OperatorPacket) sum += p.packets.map { getVersionSum(it) }.sum()
return sum
}
return getVersionSum(p).toString()
}
override fun solveB(input: List<String>): String {
return Packet.parsePacket(input.first().toBinary().toConsumer()).evaluate().toString()
}
}
class BitConsumer(private var bits: List<Int>) {
fun consume(n: Int) = bits.take(n).also { bits = bits.drop(n) }
fun consumeAsInt(n: Int) = consume(n).toInt()
fun consumeNext() = bits[0].also { bits = bits.drop(1) }
fun isNotEmpty() = bits.isNotEmpty()
}
abstract class Packet(val version: Int) {
abstract fun evaluate(): Long
companion object {
fun parsePacket(bits: BitConsumer): Packet {
val version = bits.consumeAsInt(3)
val type = bits.consumeAsInt(3)
return when (type) {
0 -> SumPacket(version, bits)
1 -> ProductPacket(version, bits)
2 -> MinimumPacket(version, bits)
3 -> MaximumPacket(version, bits)
4 -> LiteralPacket(version, bits)
5 -> GreaterPacket(version, bits)
6 -> LessPacket(version, bits)
7 -> EqualPacket(version, bits)
else -> throw Exception("Invalid packet type '$type'")
}
}
}
}
class LiteralPacket(version: Int, bits: BitConsumer) : Packet(version) {
val value: Long
init {
val valueBits = mutableListOf<Int>()
do {
val next = bits.consume(5)
valueBits.addAll(next.drop(1))
} while (next[0] == 1)
value = valueBits.toLong()
}
override fun evaluate() = value
}
abstract class OperatorPacket(version: Int, bits: BitConsumer) : Packet(version) {
val packets: List<Packet>
init {
val lengthType = bits.consumeNext()
packets = mutableListOf<Packet>()
if (lengthType == 0) {
val length = bits.consumeAsInt(15)
val subpacketBits = bits.consume(length).toConsumer()
while (subpacketBits.isNotEmpty()) {
packets.add(Packet.parsePacket(subpacketBits))
}
} else {
val numPackets = bits.consumeAsInt(11)
repeat(numPackets) { packets.add(Packet.parsePacket(bits)) }
}
}
}
class SumPacket(version: Int, bits: BitConsumer) : OperatorPacket(version, bits) {
override fun evaluate() = packets.map { it.evaluate() }.sum()
}
class ProductPacket(version: Int, bits: BitConsumer) : OperatorPacket(version, bits) {
override fun evaluate() = packets.map { it.evaluate() }.reduce { l, r -> l * r }
}
class MinimumPacket(version: Int, bits: BitConsumer) : OperatorPacket(version, bits) {
override fun evaluate() = packets.map { it.evaluate() }.min()!!
}
class MaximumPacket(version: Int, bits: BitConsumer) : OperatorPacket(version, bits) {
override fun evaluate() = packets.map { it.evaluate() }.max()!!
}
class GreaterPacket(version: Int, bits: BitConsumer) : OperatorPacket(version, bits) {
override fun evaluate() = if (packets[0].evaluate() > packets[1].evaluate()) 1L else 0L
}
class LessPacket(version: Int, bits: BitConsumer) : OperatorPacket(version, bits) {
override fun evaluate() = if (packets[0].evaluate() < packets[1].evaluate()) 1L else 0L
}
class EqualPacket(version: Int, bits: BitConsumer) : OperatorPacket(version, bits) {
override fun evaluate() = if (packets[0].evaluate() == packets[1].evaluate()) 1L else 0L
}
fun List<Int>.toConsumer() = BitConsumer(this)
fun List<Int>.toInt() = this.reversed().reduceIndexed { i, l, r -> l + (r shl i) }
fun List<Int>.toLong() = this.reversed().map(Int::toLong).reduceIndexed { i, l, r -> l + (r shl i) }
fun String.toBinary() =
this.map { it.toString().toInt(16).toString(2) }
.map { MutableList(4 - it.length) { 0 } + it.map { it.toInt() - 48 } }
.flatten()
| 0 | Kotlin | 0 | 0 | 16233aa7c4820db072f35e7b08213d0bd3a5be69 | 4,258 | AdventOfCode | Creative Commons Zero v1.0 Universal |
leetcode-75-kotlin/src/main/kotlin/FindTheHighestAltitude.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes.
* The biker starts his trip on point 0 with altitude equal 0.
*
* You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n).
* Return the highest altitude of a point.
*
*
*
* Example 1:
*
* Input: gain = [-5,1,5,0,-7]
* Output: 1
* Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
* Example 2:
*
* Input: gain = [-4,-3,-2,-1,4,3,2]
* Output: 0
* Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.
*
*
* Constraints:
*
* n == gain.length
* 1 <= n <= 100
* -100 <= gain[i] <= 100
* @see <a href="https://leetcode.com/problems/find-the-highest-altitude/">LeetCode</a>
*/
fun largestAltitude(gain: IntArray): Int {
var currentAltitude = 0
var maxAltitude = 0
for (netGain in gain) {
currentAltitude += netGain
maxAltitude = maxOf(currentAltitude, maxAltitude)
}
return maxAltitude
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,073 | leetcode-75 | Apache License 2.0 |
src/day03/Day03.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day03
import readInput
fun main() {
fun score(item: Char): Int = when (item) {
in 'a'..'z' -> item - 'a' + 1
in 'A'..'Z' -> item - 'A' + 27
else -> error("")
}
fun part1(input: List<String>): Int {
return input
.map { it.chunked(it.length / 2) }
.map {
it[0].toSet() intersect it[1].toSet()
}.sumOf { score(it.single()) }
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map {
it[0].toSet() intersect it[1].toSet() intersect it[2].toSet()
}.sumOf { score(it.single()) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day03/Day03_test")
println(part1(testInput))
check(part1(testInput) == 157)
val input = readInput("day03/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 954 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | sjgoebel | 573,578,579 | false | {"Kotlin": 21782} | fun main() {
fun part1(input: List<String>): Int {
var count = 0
for (line in input) {
val (a, b) = line.split(',')
val (c, d) = a.split("-").map(String::toInt)
val (e, f) = b.split("-").map(String::toInt)
if ((e >= c && f <= d) || (c >= e) && (d <= f)) {
count++
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
for (line in input) {
val (a, b) = line.split(',')
val (c, d) = a.split("-").map(String::toInt)
val (e, f) = b.split("-").map(String::toInt)
if ((e in c..d) || c in e..f || f in c .. d || d in e .. f) {
count++
}
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | ae1588dbbb923dbcd4d19fd1495ec4ebe8f2593e | 1,071 | advent-of-code-2022-kotlin | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day23/Day23.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day23
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.year2021.DayOf2021
import java.util.PriorityQueue
import kotlin.math.abs
/**
* See [Year 2021, Day 23](https://adventofcode.com/2021/day/23)
*/
object Day23 : DayOf2021(23) {
private val COST = mapOf(
'A' to 1,
'B' to 10,
'C' to 100,
'D' to 1000,
)
override fun first(): Any? {
return solve(lines)
}
override fun second(): Any? {
val insert = """
| #D#C#B#A#
| #D#B#A#C#
""".trimMargin().lines()
return solve(
lines.take(3) + insert + lines.drop(3),
)
}
private fun solve(data: List<String>): Int {
val points = data
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
if (c in 'A'..'D' || c == '.') Vector2D(x, y) to c else null
}
}
val rawStacks = points.filter { it.second in 'A'..'D' }
.groupBy { it.first.x }
.toList()
.zip('A'..'D') { (x, points), char ->
Triple(char, x, points)
}
val depth = rawStacks.first().third.size
val stacks = rawStacks.map {
Node(
x = it.second,
char = it.first,
)
}
val startStacks = stacks.zip(rawStacks) { stack, rawStack ->
stack to rawStack.third.map { it.second }
}.toMap()
val entries = stacks.map { stack -> stack.x }
val spots = points.filter { it.second == '.' }
.map { it.first.x }
.filterNot { it in entries }
.map { Node(it) }
val exitLinks = stacks.associateWith { stack ->
spots.map { spot ->
val range = when {
stack.x < spot.x -> (stack.x + 1)..(spot.x - 1)
stack.x > spot.x -> (spot.x + 1)..(stack.x - 1)
else -> IntRange.EMPTY
}
Link(
to = spot,
blocking = spots.filter { it.x in range },
costX = abs(stack.x - spot.x),
)
}
}
val enterFromSpotLinks = spots.associateWith { spot ->
stacks.map { stack ->
val range = when {
spot.x < stack.x -> (spot.x + 1)..(stack.x - 1)
spot.x > stack.x -> (stack.x + 1)..(spot.x - 1)
else -> IntRange.EMPTY
}
Link(
to = stack,
blocking = spots.filter { it.x in range },
costX = abs(spot.x - stack.x),
)
}
}
val enterFromStackLinks = stacks.associateWith { fromStack ->
stacks.filterNot { it == fromStack }
.map { stack ->
val range = when {
fromStack.x < stack.x -> (fromStack.x + 1)..(stack.x - 1)
fromStack.x > stack.x -> (stack.x + 1)..(fromStack.x - 1)
else -> IntRange.EMPTY
}
Link(
to = stack,
blocking = spots.filter { it.x in range },
costX = abs(fromStack.x - stack.x),
)
}
}
val startWorld = World(
spots = emptyMap(),
stacks = startStacks,
)
val queue = PriorityQueue<Triple<World, Int, Int>>(1_000_000, compareBy { it.second + it.third })
queue += Triple(startWorld, 0, Int.MAX_VALUE)
val seen = mutableSetOf<World>()
while (queue.isNotEmpty()) {
val (world, score, _) = queue.remove()
if (world in seen) {
continue
} else {
seen += world
}
if (world.spots.isEmpty() && world.stacks.all { (stack, chars) -> chars.all { it == stack.char } }) {
return score
}
val canFill = world.stacks
.filter { it.value.all { char -> char == it.key.char } }
.filter { it.value.size < depth }
val canExit = world.stacks
.filter { it.value.isNotEmpty() }
.filter { it.key !in canFill }
.filter { it.value.any { char -> char != it.key.char } }
val exiting = canExit.flatMap { (stack, stackData) ->
val targets = exitLinks[stack].orEmpty()
.filter { it.to !in world.spots }
.filter { it.blocking.none { blocking -> blocking in world.spots } }
val costY = (depth - stackData.size + 1)
targets.map { target ->
World(
spots = world.spots + (target.to to stackData.first()),
stacks = world.stacks.mapValues { (key, value) ->
if (key == stack) value.drop(1) else value
},
) to score + (target.costX + costY) * COST.getValue(stackData.first())
}
}
val enteringFromStacks = canExit.flatMap { (stack, stackData) ->
val targets = enterFromStackLinks[stack].orEmpty()
.filter { it.to in canFill }
.filter { it.to.char == stackData.first() }
.filter { it.blocking.none { blocking -> blocking in world.spots } }
val costFromY = (depth - stackData.size + 1)
targets.map { target ->
val costToY = (depth - world.stacks[target.to].orEmpty().size)
World(
spots = world.spots,
stacks = world.stacks.mapValues { (key, value) ->
when (key) {
stack -> value.drop(1)
target.to -> stackData.take(1) + value
else -> value
}
},
) to score + (target.costX + costFromY + costToY) * COST.getValue(stackData.first())
}
}
val enteringFromSpots = world.spots.flatMap { (spot, char) ->
val targets = enterFromSpotLinks[spot].orEmpty()
.filter { it.to in canFill }
.filter { it.to.char == char }
.filter { it.blocking.none { blocking -> blocking in world.spots } }
targets.map { target ->
val costToY = (depth - world.stacks[target.to].orEmpty().size)
World(
spots = world.spots - spot,
stacks = world.stacks.mapValues { (key, value) ->
when (key) {
target.to -> listOf(char) + value
else -> value
}
},
) to score + (target.costX + costToY) * COST.getValue(char)
}
}
val toAdd = (exiting + enteringFromStacks + enteringFromSpots)
.filter { it.first !in seen }
.map { (world, score) ->
val spotCosts = world.spots.map { (node, char) ->
((stacks.first { it.char == char }.x - node.x) + depth) * COST.getValue(char)
}.sum()
val stackCosts = world.stacks.map { (node, stack) ->
stack.filter { it != node.char }.sumOf { COST.getValue(it) } * 2 * depth
}.sum()
Triple(world, score, (spotCosts + stackCosts) / 4)
}
queue.addAll(toAdd)
}
return 0
}
data class World(
val spots: Map<Node, Char>,
val stacks: Map<Node, List<Char>>,
)
data class Link(
val to: Node,
val blocking: List<Node>,
val costX: Int,
)
data class Node(
val x: Int,
val char: Char = '.',
)
}
fun main() = SomeDay.mainify(Day23)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 6,959 | adventofcode | MIT License |
calendar/day07/Day7.kt | mpetuska | 571,764,215 | false | {"Kotlin": 18073} | package day07
import Day
import Lines
class Day7 : Day() {
sealed interface FS {
val name: String
val size: Int
data class Dir(override val name: String, override val size: Int, val children: List<FS>) : FS {
fun flatten(): List<Dir> =
listOf(this) + children
.mapNotNull { if (it is Dir) it.flatten() else null }
.flatten()
}
data class File(override val name: String, override val size: Int) : FS
}
private fun listDirectory(name: String, input: Lines): FS.Dir {
fun ls(name: String, lines: Lines): Pair<FS.Dir, Int> {
val children = mutableListOf<FS>()
var i = 0
var size = 0
do {
val line = lines[i++].split(" ")
when {
line[0][0] == '$' -> when (line[1]) {
"cd" -> when (line[2]) {
"..", "/" -> break
else -> ls(line[2], lines.drop(i)).let { (dir, ii) ->
children += dir
size += dir.size
i += ii
}
}
"ls" -> continue
}
line[0][0].isDigit() -> line[0].toInt().let { s ->
size += s
children += FS.File(line[1], s)
}
else -> continue
}
} while (i < lines.size)
return FS.Dir(name, size, children) to i
}
return ls(name, input).first
}
override fun part1(input: Lines): Any {
return listDirectory("/", input.drop(1))
.flatten()
.filter { it.size <= 100_000 }
.sumOf(FS::size)
}
override fun part2(input: Lines): Any {
val dirs = listDirectory("/", input.drop(1)).flatten()
val missingSpace = 30_000_000 - (70_000_000 - dirs[0].size)
return dirs.reduce { acc, dir ->
if (dir.size >= missingSpace && dir.size < acc.size) {
dir
} else {
acc
}
}.size
}
}
| 0 | Kotlin | 0 | 0 | be876f0a565f8c14ffa8d30e4516e1f51bc3c0c5 | 1,873 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Excercise21.kt | underwindfall | 433,989,850 | false | {"Kotlin": 55774} | private fun part1() {
val input = getInputAsTest("21")
val p = IntArray(2)
for (i in 0..1) {
p[i] = input[i].removePrefix("Player ${i + 1} starting position: ").toInt()
}
var rolls = 0L
val s = IntArray(2)
var i = 0
var d = 1
fun next(): Int {
rolls++
return d.also { d = d % 100 + 1 }
}
while (true) {
p[i] = (p[i] + next() + next() + next() - 1) % 10 + 1
s[i] += p[i]
if (s[i] >= 1000) {
println("part1 ${s[1 - i] * rolls}")
break
}
i = (i + 1) % 2
}
}
private fun part2() {
val input = getInputAsTest("21")
val p = IntArray(2)
for (i in 0..1) {
p[i] = input[i].removePrefix("Player ${i + 1} starting position: ").toInt()
}
data class WC(var w1: Long, var w2: Long)
val dp = Array(11) { Array(11) { Array(21) { arrayOfNulls<WC>(21) } } }
fun find(p1: Int, p2: Int, s1: Int, s2: Int): WC {
dp[p1][p2][s1][s2]?.let {
return it
}
val c = WC(0, 0)
for (d1 in 1..3) for (d2 in 1..3) for (d3 in 1..3) {
val p1n = (p1 + d1 + d2 + d3 - 1) % 10 + 1
val s1n = s1 + p1n
if (s1n >= 21) {
c.w1++
} else {
val cn = find(p2, p1n, s2, s1n)
c.w1 += cn.w2
c.w2 += cn.w1
}
}
dp[p1][p2][s1][s2] = c
return c
}
val c = find(p[0], p[1], 0, 0)
println(c)
println(maxOf(c.w1, c.w2))
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 4fbee48352577f3356e9b9b57d215298cdfca1ed | 1,390 | advent-of-code-2021 | MIT License |
src/main/kotlin/days/aoc2023/Day4.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
import kotlin.math.pow
class Day4 : Day(2023, 4) {
override fun partOne(): Any {
return calculatePartOne(inputList)
}
fun calculatePartOne(inputList: List<String>): Int {
return inputList.sumOf { line ->
Card.factory(line).score()
}
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
fun calculatePartTwo(inputList: List<String>): Int {
val cardCounts = mutableMapOf<Int,Int>()
inputList.forEach { line ->
val card = Card.factory(line)
val matches = card.matches()
cardCounts[card.cardNumber] = (cardCounts[card.cardNumber] ?: 0) + 1
for (copy in 1 .. cardCounts[card.cardNumber]!!) {
for (i in 1..matches) {
cardCounts[card.cardNumber + i] = (cardCounts[card.cardNumber + i] ?: 0) + 1
}
}
}
return cardCounts.values.sum()
}
internal class Card(
val cardNumber: Int,
private val winningNumbers: Set<Int>,
private val numbersOnCard: Set<Int>
) {
companion object {
fun factory(line: String): Card {
val cardNumber = line.dropWhile { !it.isDigit() }.takeWhile { it.isDigit() }.toInt()
val split = line.dropWhile { it != ':' }.drop(1).split('|')
val winningNumbers =
split.first().trim().split("\\s+".toRegex()).map { it.trim().toInt() }.toSet()
val numbersOnCard =
split.last().trim().split("\\s+".toRegex()).map { it.trim().toInt() }.toSet()
return Card(cardNumber, winningNumbers, numbersOnCard)
}
}
fun score(): Int {
return (2.0.pow(matches() - 1)).toInt()
}
fun matches() = numbersOnCard.intersect(winningNumbers).size
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 1,941 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/day10/Day10.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day10
import readLines
private fun part1(input: List<String>): Int {
var cycle = 0
var register = 1
val map = mutableMapOf<Int, Int>()
input.forEach {
val instruction = it.substringBefore(" ")
if (instruction == "addx") {
val number = it.substringAfter(" ").toInt()
cycle += 1 // cycle one
map[cycle] = register
cycle += 1 // cycle two
map[cycle] = register
register += number
} else {
cycle += 1
map[cycle] = register
}
}
return (20..220 step 40).sumOf {
it * map.getOrDefault(it, 0)
}
}
private fun incrementCycle(sprite: IntRange, cycle: Int): Int {
if (sprite.contains(cycle % 40)) {
print("#")
} else {
print(".")
}
val incrementedCycle = cycle + 1
if (incrementedCycle % 40 == 0) {
println()
}
return incrementedCycle
}
private fun part2(input: List<String>) {
var cycle = 0
var register = 1
var sprite = IntRange(0, 2)
input.forEach {
val instruction = it.substringBefore(" ")
if (instruction == "addx") {
val number = it.substringAfter(" ").toInt()
cycle = incrementCycle(sprite, cycle)
cycle = incrementCycle(sprite, cycle)
register += number
sprite = IntRange(register-1, register+1)
} else {
cycle = incrementCycle(sprite, cycle)
}
}
}
fun main() {
println(part1(readLines("day10/input")))
part2(readLines("day10/input"))
} | 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 1,603 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/arrays/CompliancePriorities.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.arrays
/*
https://leetcode.com/discuss/interview-question/1362915/amazon-hackerrank-question-priority-assignment
*/
fun main() {
reassignedPriorities(arrayOf(1, 4, 8, 4)).forEach { print("$it ") }// [1, 2, 3, 2]
println()
reassignedPrioritiesHS(arrayOf(1, 4, 8, 4)).forEach { print("$it ") }// [1, 2, 3, 2]
}
// O(n) time | O(1) space
private fun reassignedPriorities(priorities: Array<Int>): Array<Int> {
val occur = IntArray(100) { 0 }
priorities.forEach { occur[it] = 1 }
var priority = 1
occur.forEachIndexed { idx, el -> if (el > 0) occur[idx] = priority++ }
priorities.forEachIndexed { idx, el -> priorities[idx] = occur[el] }
return priorities
}
// O(n * log(n)) time | O(n) space
private fun reassignedPrioritiesHS(priorities: Array<Int>): Array<Int> {
var counter = 1
val numberToMinimum = priorities.toSortedSet().associateWith { counter++ }
return priorities.map { numberToMinimum[it]!! }.toTypedArray()
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 1,023 | algs4-leprosorium | MIT License |
leetcode2/src/leetcode/LeafSimilarTrees.kt | hewking | 68,515,222 | false | null | package leetcode
import leetcode.structure.TreeNode
import java.util.*
/**
* 872. 叶子相似的树
* https://leetcode-cn.com/problems/leaf-similar-trees/
* Created by test
* Date 2019/5/29 1:09
* Description
* 请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。
举个例子,如上图所示,给定一颗叶值序列为 (6, 7, 4, 9, 8) 的树。
如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。
如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false 。
提示:
给定的两颗树可能会有 1 到 100 个结点。
*/
object LeafSimilarTrees{
/**
* 思路:
* 1.中序遍历叶子节点
* 2.然后对比
*/
class Solution {
fun leafSimilar(root1: TreeNode?, root2: TreeNode?): Boolean {
val list1 = mutableListOf<Int>()
val list2 = mutableListOf<Int>()
travsel(root1,list1)
travsel(root2,list2)
if (list1.size != list2.size) return false
for (i in list1.indices) {
if (list1[i] != list2[i]) return false
}
return true
}
fun travsel(root : TreeNode?,list : MutableList<Int>){
if (root == null) return
if (root?.left == null && root?.right == null){
list.add(root?.`val`)
}
travsel(root?.left,list)
travsel(root?.right,list)
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,593 | leetcode | MIT License |
src/Day04.kt | kipwoker | 572,884,607 | false | null |
fun main() {
fun parse(lines: List<String>): List<Pair<Interval, Interval>> {
return lines.map { line ->
val intervals = line
.split(',')
.map { range ->
val rangeParts = range.split('-')
Interval(rangeParts[0].toInt(), rangeParts[1].toInt())
}
intervals[0]to intervals[1]
}
}
fun part1(input: List<String>): Int {
return parse(input)
.filter { (left, right) -> left.hasFullOverlap(right) }
.size
}
fun part2(input: List<String>): Int {
return parse(input)
.filter { (left, right) -> left.hasOverlap(right) }
.size
}
val testInput = readInput("Day04_test")
assert(part1(testInput), 2)
assert(part2(testInput), 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 936 | aoc2022 | Apache License 2.0 |
src/questions/ContainerWithMostWater.kt | realpacific | 234,499,820 | false | null | package questions
import algorithmdesignmanualbook.print
import kotlin.test.assertTrue
fun _containerWithMostWater(height: IntArray): Int {
if (height.size == 2) {
return calcArea(0, 1, height)
}
var maxArea = calcArea(0, height.lastIndex, height)
for (i in 0 until height.lastIndex) {
for (j in (i + 1)..height.lastIndex) {
val max = calcArea(i, j, height)
if (max > maxArea) {
maxArea = max
}
}
}
return maxArea
}
/**
* Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
* n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
* Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
* <img src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg" height="150" width="300"/>
* [Source](https://leetcode.com/problems/container-with-most-water/)
*/
fun containerWithMostWater(height: IntArray): Int {
var maxArea = 0
var i = 0
var j = height.lastIndex
while (i < j) {
val area = calcArea(i, j, height)
maxArea = maxOf(area, maxArea)
if (height[i] >= height[j]) {
j--
} else {
i++
}
}
return maxArea
}
private fun calcArea(x1: Int, x2: Int, heights: IntArray): Int {
if (x1 >= x2) {
return 0
}
return (x2 - x1) * minOf(heights[x2], heights[x1])
}
fun main() {
assertTrue {
containerWithMostWater(intArrayOf(1, 8, 100, 2, 100, 4, 8, 3, 7)).print() == 200
}
assertTrue {
containerWithMostWater(intArrayOf(3, 2, 1, 3)).print() == 3 * 3
}
assertTrue {
containerWithMostWater(intArrayOf(4, 3, 2, 1, 4)).print() == 16
}
assertTrue {
containerWithMostWater(intArrayOf(1, 2, 1)).print() == 2
}
assertTrue {
containerWithMostWater(intArrayOf(1, 1)).print() == 1
}
assertTrue {
containerWithMostWater(intArrayOf(1, 8, 6, 2, 5, 4, 8, 3, 7)).print() == 49
}
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,136 | algorithms | MIT License |
src/Day03.kt | shepard8 | 573,449,602 | false | {"Kotlin": 73637} | fun main() {
fun priority(item: Char) = when(item) {
in 'a'..'z' -> item - 'a' + 1
in 'A'..'Z' -> item - 'A' + 27
else -> throw IllegalArgumentException()
}
fun part1(rucksacks: List<String>) =
rucksacks.map { line ->
val left = line.subSequence(0, line.length / 2)
val right = line.subSequence(line.length / 2, line.length)
left.first { c -> c in right }
}.sumOf { priority(it) }
fun part2(rucksacks: List<String>) =
rucksacks.chunked(3).map { group ->
group[0].first { c -> c in group[1] && c in group[2] }
}.sumOf { priority(it) }
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 81382d722718efcffdda9b76df1a4ea4e1491b3c | 747 | aoc2022-kotlin | Apache License 2.0 |
src/day10.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import kotlin.math.max
import kotlin.system.exitProcess
private const val DAY = 10
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String -> x.toMutableList() }
val input = loadInput(DAY, false, transformer)
println(solvePart1(input))
println(solvePart2(input))
}
// Part 1
private fun solvePart1(maze: List<List<Char>>): Int {
// S = F
val start = Pair(8, 42)
// val start = Pair(4, 0)
// val start = Pair(12, 4)
var p1 = start
var p2 = start
var p1From = "S"
var p2From = "E"
var p1Steps = 0
var p2Steps = 0
do {
val p1Next = getNext(p1From, maze[p1.second][p1.first])
p1From = p1Next.second
p1 = Pair(p1.first + p1Next.first.first, p1.second + p1Next.first.second)
p1Steps++
val p2Next = getNext(p2From, maze[p2.second][p2.first])
p2From = p2Next.second
p2 = Pair(p2.first + p2Next.first.first, p2.second + p2Next.first.second)
p2Steps++
} while (p1 != p2)
return max(p1Steps, p2Steps)
}
// Part 2
private fun solvePart2(maze: List<List<Char>>): Int {
val start = Pair(8, 42)
// val start = Pair(12, 4)
val instructions = mutableListOf<Pair<Pair<Int, Int>, String>>()
val maze = maze.map { it.toMutableList() }.toMutableList()
var p1 = start
var p1From = "S"
var p1Steps = 0
do {
val p1Next = getNext(p1From, maze[p1.second][p1.first])
instructions.add(p1Next)
maze[p1.second][p1.first] = '*'
p1From = p1Next.second
p1 = Pair(p1.first + p1Next.first.first, p1.second + p1Next.first.second)
p1Steps++
} while (p1 != start)
p1 = start
var from = 'S'
while (instructions.isNotEmpty()) {
val ins = instructions.removeFirst()
var rightHandDir = getInsideDirection(from)
var cPos = Pair(p1.first + rightHandDir.first, p1.second + rightHandDir.second)
while (maze[cPos.second][cPos.first] != '*') {
maze[cPos.second][cPos.first] = '$'
cPos = Pair(cPos.first + rightHandDir.first, cPos.second + rightHandDir.second)
}
from = ins.second.first()
rightHandDir = getInsideDirection(from)
cPos = Pair(p1.first + rightHandDir.first, p1.second + rightHandDir.second)
while (maze[cPos.second][cPos.first] != '*') {
maze[cPos.second][cPos.first] = '$'
cPos = Pair(cPos.first + rightHandDir.first, cPos.second + rightHandDir.second)
}
p1 = Pair(p1.first + ins.first.first, p1.second + ins.first.second)
}
return maze.sumOf { it.count { it == '$' } }
}
fun getInsideDirection(from: Char): Pair<Int, Int> {
return when (from) {
'N' -> Pair(1, 0)
'S' -> Pair(-1, 0)
'E' -> Pair(0, 1)
'W' -> Pair(0, -1)
else -> throw Exception("BOOM")
}
}
fun getNext(from: String, pos: Char): Pair<Pair<Int, Int>, String> {
var dx = 0
var dy = 0
var nextFrom = from
val pos = if (pos == 'S') 'F' else pos
// val pos = if (pos == 'S') '7' else pos
when (from) {
"N" -> when (pos) {
'|' -> dy = 1
'J' -> {
dx = -1
nextFrom = "E"
}
'L' -> {
dx = 1
nextFrom = "W"
}
}
"S" -> when (pos) {
'|' -> dy = -1
'7' -> {
dx = -1
nextFrom = "E"
}
'F' -> {
dx = 1
nextFrom = "W"
}
}
"W" -> when (pos) {
'-' -> dx = 1
'7' -> {
dy = 1
nextFrom = "N"
}
'J' -> {
dy = -1
nextFrom = "S"
}
}
"E" -> when (pos) {
'-' -> dx = -1
'F' -> {
dy = 1
nextFrom = "N"
}
'L' -> {
dy = -1
nextFrom = "S"
}
}
}
return Pair(Pair(dx, dy), nextFrom)
}
| 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 4,255 | aoc2023 | MIT License |
src/main/kotlin/g1301_1400/s1368_minimum_cost_to_make_at_least_one_valid_path_in_a_grid/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1301_1400.s1368_minimum_cost_to_make_at_least_one_valid_path_in_a_grid
// #Hard #Array #Breadth_First_Search #Matrix #Heap_Priority_Queue #Graph #Shortest_Path
// #2023_06_06_Time_220_ms_(100.00%)_Space_37.6_MB_(100.00%)
import java.util.LinkedList
import java.util.Objects
import java.util.Queue
@Suppress("NAME_SHADOWING")
class Solution {
private val dir = arrayOf(
intArrayOf(0, 0), intArrayOf(0, 1),
intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)
)
fun minCost(grid: Array<IntArray>): Int {
val visited = Array(grid.size) { IntArray(grid[0].size) }
val queue: Queue<Pair> = LinkedList()
addAllTheNodeInRange(0, 0, grid, queue, visited)
if (visited[grid.size - 1][grid[0].size - 1] == 1) {
return 0
}
var cost = 0
while (queue.isNotEmpty()) {
cost++
val size = queue.size
for (i in 0 until size) {
val pa = queue.poll()
for (k in 1 until dir.size) {
val m = Objects.requireNonNull(pa).x + dir[k][0]
val n = pa.y + dir[k][1]
addAllTheNodeInRange(m, n, grid, queue, visited)
if (visited[grid.size - 1][grid[0].size - 1] == 1) {
return cost
}
}
}
}
return -1
}
private fun addAllTheNodeInRange(
x: Int,
y: Int,
grid: Array<IntArray>,
queue: Queue<Pair>,
visited: Array<IntArray>
) {
var x = x
var y = y
while (x >= 0 && x < visited.size && y >= 0 && y < visited[0].size && visited[x][y] == 0) {
queue.offer(Pair(x, y))
visited[x][y]++
val d = dir[grid[x][y]]
x += d[0]
y += d[1]
}
}
private class Pair(var x: Int, var y: Int)
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,936 | LeetCode-in-Kotlin | MIT License |
src/Day03.kt | elliaoster | 573,666,162 | false | {"Kotlin": 14556} | fun main() {
fun findPriority(commonChar: Char) = when (commonChar) {
'a' -> 1
'b' -> 2
'c' -> 3
'd' -> 4
'e' -> 5
'f' -> 6
'g' -> 7
'h' -> 8
'i' -> 9
'j' -> 10
'k' -> 11
'l' -> 12
'm' -> 13
'n' -> 14
'o' -> 15
'p' -> 16
'q' -> 17
'r' -> 18
's' -> 19
't' -> 20
'u' -> 21
'v' -> 22
'w' -> 23
'x' -> 24
'y' -> 25
'z' -> 26
'A' -> 27
'B' -> 28
'C' -> 29
'D' -> 30
'E' -> 31
'F' -> 32
'G' -> 33
'H' -> 34
'I' -> 35
'J' -> 36
'K' -> 37
'L' -> 38
'M' -> 39
'N' -> 40
'O' -> 41
'P' -> 42
'Q' -> 43
'R' -> 44
'S' -> 45
'T' -> 46
'U' -> 47
'V' -> 48
'W' -> 49
'X' -> 50
'Y' -> 51
'Z' -> 52
else -> 0
}
fun part1(input: List<String>): Int {
var total=0
//go through each line
for (line in input) {
//split the line
val half = line.length / 2
val chars = line.toCharArray()
val firstHalf = CharArray(half)
for (i in 0..half - 1) {
firstHalf[i] = chars[i]
}
var commonChar = ' '
//find the common letter
for (i in half..line.lastIndex) {
for (j in 0..half - 1) {
if (chars[i] == firstHalf[j]) {
commonChar = chars[i]
}
}
}
//find the prority of letter
total+=findPriority(commonChar)
}
//return the sum
return total
}
fun part2(input: List<String>): Int {
var total=0
//go through each line
for (lineIndex in 0 .. input.size-3 step 3) {
var commonChar = ' '
val chars = input[lineIndex].toCharArray()
val nextLinechars = input[lineIndex+1].toCharArray()
val thirdLinechars = input[lineIndex+2].toCharArray()
//walk through each char in the next line
for (curr in 0..chars.lastIndex) {
for (next in 0..nextLinechars.lastIndex) {
if (chars[curr]==nextLinechars[next]) {
for (third in 0..thirdLinechars.lastIndex) {
if (chars[curr]==thirdLinechars[third]) {
commonChar=chars[curr]
}
}
}
}
}
//println(commonChar)
//find the prority of letter
total+=findPriority(commonChar)
}
//return the sum
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 27e774b133f9d5013be9a951d15cefa8cb01a984 | 3,202 | advent-of-code-2022 | Apache License 2.0 |
day 01/Wouter - kotlin/solution.kts | AE-nv | 420,076,649 | false | {"Python": 254337, "Java": 180867, "C#": 167466, "F#": 114222, "Clojure": 88016, "C++": 45744, "HTML": 22679, "TypeScript": 19433, "Go": 16626, "JavaScript": 10488, "Assembly": 8364, "Rust": 6671, "Kotlin": 3264, "Scala": 2328, "CSS": 252} | fun solve(input: List<String>) : Int =
input.map { it.toInt() }
.windowed(2, 1)
.sumOf { (a, b) -> compare(a, b) }
fun solve2(input: List<String>) : Int =
input.asSequence().map { it.toInt() }
.windowed(3, 1)
.map { it.sum() }
.windowed(2, 1)
.sumOf { (a, b) -> compare(a, b) }
fun compare(a: Int, b: Int) : Int {
if(b > a) {
return 1
}
return 0
}
val testInput = """
199
200
208
210
200
207
240
269
260
263
""".trimIndent().split("\n")
println("Part 1: ${solve(testInput)}")
println("Part 2: ${solve2(testInput)}")
| 0 | Python | 1 | 1 | e9c803dc5fab3c51a2acbbaade56b71d4f5ce7d2 | 638 | aedvent-code-2021 | MIT License |
src/day03/day03.kt | mahmoud-abdallah863 | 572,935,594 | false | {"Kotlin": 16377} | package day03
import assertEquals
import readInput
import readTestInput
fun main() {
fun part1(input: List<String>): Int = input
.sumOf { line ->
val (compartment1, compartment2) = line.chunked(line.length / 2).map { it.toSet() }
val commonCharacters = compartment1.intersect(compartment2)
commonCharacters.sumOf { char ->
if (char.isLowerCase()) char - 'a' + 1
else char - 'A' + 27
}
}
fun part2(input: List<String>): Int = input
.chunked(3)
.sumOf { rucksack ->
val commonCharacter = rucksack
.asSequence()
.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.firstOrNull() ?: return@sumOf 0
if (commonCharacter.isLowerCase()) commonCharacter - 'a' + 1
else commonCharacter - 'A' + 27
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput()
assertEquals(part1(testInput), 157)
assertEquals(part2(testInput),70)
val input = readInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f6d1a1583267e9813e2846f0ab826a60d2d1b1c9 | 1,204 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestRepeatingSubstring.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.pow
/**
* 1062. Longest Repeating Substring
* @see <a href="https://leetcode.com/problems/longest-repeating-substring/">Source</a>
*/
interface LongestRepeatingSubstring {
operator fun invoke(s: String): Int {
val n = s.length
var left = 1
var right = n
var l: Int
while (left <= right) {
l = left + right.minus(left) / 2
if (search(l, n, s) != -1) {
left = l + 1
} else {
right = l - 1
}
}
return left - 1
}
fun search(l: Int, n: Int, s: String): Int {
return -1
}
}
/**
* Approach 1: Binary Search + Hashset of Already Seen Strings
*/
class LRSBinarySearch : LongestRepeatingSubstring {
override fun search(l: Int, n: Int, s: String): Int {
val seen: MutableSet<String> = HashSet()
var tmp: String
for (start in 0 until n - l + 1) {
tmp = s.substring(start, start + l)
if (seen.contains(tmp)) return start
seen.add(tmp)
}
return -1
}
}
/**
* Approach 2: Binary Search + Hashset of Hashes of Already Seen Strings
*/
class LRSHashes : LongestRepeatingSubstring {
override fun search(l: Int, n: Int, s: String): Int {
val seen: MutableSet<Int> = HashSet()
var tmp: String
var hc: Int
for (start in 0 until n - l + 1) {
tmp = s.substring(start, start + l)
hc = tmp.hashCode()
if (seen.contains(hc)) return start
seen.add(hc)
}
return super.search(l, n, s)
}
}
/**
* Approach 3: Binary Search + Rabin-Karp
*/
class LRSRabinKarp : LongestRepeatingSubstring {
override operator fun invoke(s: String): Int {
val n = s.length
// convert string to array of integers
// to implement constant time slice
val nums = IntArray(n)
for (i in 0 until n) nums[i] = s[i].code - 'a'.code
// modulus value for the rolling hash function to avoid overflow
val modulus = 2.0.pow(HASH_ROLLING_MODULUS).toLong()
// binary search, L = repeating string length
var left = 1
var right = n
var l: Int
while (left <= right) {
l = left + (right - left) / 2
if (search(l, modulus, n, nums) != -1) left = l + 1 else right = l - 1
}
return left - 1
}
private fun search(l: Int, modulus: Long, n: Int, nums: IntArray): Int {
// compute the hash of string S[:L]
var h: Long = 0
for (i in 0 until l) h = (h * HASH_ROLLING_NUM + nums[i]) % modulus
// already seen hashes of strings of length L
val seen: HashSet<Long> = HashSet()
seen.add(h)
// const value to be used often : a**L % modulus
var aL: Long = 1
for (i in 1..l) aL = aL * HASH_ROLLING_NUM % modulus
for (start in 1 until n - l + 1) {
// compute rolling hash in O(1) time
h = (h * HASH_ROLLING_NUM - nums[start - 1] * aL % modulus + modulus) % modulus
h = (h + nums[start + l - 1]) % modulus
if (seen.contains(h)) return start
seen.add(h)
}
return -1
}
companion object {
private const val HASH_ROLLING_NUM = 26
private const val HASH_ROLLING_MODULUS = 24.0
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,046 | kotlab | Apache License 2.0 |
kotlin/2021/round-1c/closest-pick/src/main/kotlin/Solution.kt | ShreckYe | 345,946,821 | false | null | import kotlin.math.max
fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val (n, k) = readLine()!!.splitToSequence(' ').map { it.toInt() }.toList()
val ps = readLine()!!.splitToSequence(' ').map { it.toInt() }.toList()
val sortedPs = ps.sorted().distinct()
val sortedGaps = sortedPs.asSequence().zipWithNext()
.map { it.second - it.first - 1 }
.filter { it > 0 }
.sortedDescending().toList()
val startAndEndGaps = listOf(sortedPs.first() - 1, k - sortedPs.last()).filter { it > 0 }
val maxGap = sortedGaps.getOrNull(0)
val secondMaxGap = sortedGaps.getOrNull(1)
val maxNumbersTaken = max(
(listOfNotNull(maxGap, secondMaxGap).map(::numbersTakenWithSingle) + startAndEndGaps)
.sortedDescending().run { if (size >= 2) take(2).sum() else 0 },
(listOfNotNull(maxGap) + startAndEndGaps).maxOrNull() ?: 0
)
val y = maxNumbersTaken.toDouble() / k
println("Case #${ti + 1}: $y")
}
fun numbersTakenWithSingle(gap: Int): Int =
(gap - 1) / 2 + 1 | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 1,089 | google-code-jam | MIT License |
problems/2021adventofcode16b/submissions/accepted/Stefan.kt | stoman | 47,287,900 | false | {"C": 169266, "C++": 142801, "Kotlin": 115106, "Python": 76047, "Java": 68331, "Go": 46428, "TeX": 27545, "Shell": 3428, "Starlark": 2165, "Makefile": 1582, "SWIG": 722} | import java.math.BigInteger
import java.util.*
abstract class Packet(val version: Int, val type: Int, val bitCount: Int) {
abstract fun value(): BigInteger
}
class Literal(version: Int, type: Int, bitCount: Int, private val value: Long) : Packet(version, type, bitCount) {
override fun value(): BigInteger = value.toBigInteger()
}
class Operator(version: Int, type: Int, bitCount: Int, private val subPackets: List<Packet>) : Packet(version, type, bitCount) {
override fun value(): BigInteger = when(type) {
0 -> subPackets.sumOf { it.value() }
1 -> subPackets.map { it.value() }.reduce(BigInteger::times)
2 -> subPackets.minOf { it.value() }
3 -> subPackets.maxOf { it.value() }
5 -> if(subPackets[0].value() > subPackets[1].value()) BigInteger.ONE else BigInteger.ZERO
6 -> if(subPackets[0].value() < subPackets[1].value()) BigInteger.ONE else BigInteger.ZERO
7 -> if(subPackets[0].value() == subPackets[1].value()) BigInteger.ONE else BigInteger.ZERO
else -> throw IllegalStateException("unknown packet type $type")
}
}
fun Char.toBits(): List<Int> {
var v = lowercaseChar().digitToInt(16)
val r = mutableListOf<Int>()
repeat(4) {
r.add(v % 2)
v /= 2
}
return r.reversed()
}
fun List<Int>.parseBits(): Long {
var r = 0L
for (bit in this) {
r *= 2
r += bit
}
return r
}
fun List<Int>.parsePacket(): Packet {
val version = slice(0..2).parseBits().toInt()
when (val type = slice(3..5).parseBits().toInt()) {
// Literal value.
4 -> {
val value = mutableListOf<Int>()
var i = 1
do {
i += 5
value.addAll(slice(i + 1..i + 4))
} while (get(i) == 1)
return Literal(version, type, i + 5, value.parseBits())
}
// Operator
else -> {
val subPackets = mutableListOf<Packet>()
var parsedBits = 0
when(get(6)) {
0 -> {
val subLength = slice(7..21).parseBits()
parsedBits = 22
while(parsedBits < 22 + subLength) {
val nextPacket = drop(parsedBits).parsePacket()
subPackets.add(nextPacket)
parsedBits += nextPacket.bitCount
}
}
1 -> {
val subLength = slice(7..17).parseBits()
parsedBits = 18
while(subPackets.size < subLength) {
val nextPacket = drop(parsedBits).parsePacket()
subPackets.add(nextPacket)
parsedBits += nextPacket.bitCount
}
}
}
return Operator(version, type, parsedBits, subPackets)
}
}
}
fun main() {
val packet = Scanner(System.`in`).next().flatMap { it.toBits() }.parsePacket()
println(packet.value())
}
| 0 | C | 1 | 3 | ee214c95c1dc1d5e9510052ae425d2b19bf8e2d9 | 2,683 | CompetitiveProgramming | MIT License |
src/main/kotlin/leetcode/kotlin/array/SortingAlgorithms/EfficientSort/MergeSort.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.array.SortingAlgorithms.EfficientSort
// https://en.wikipedia.org/wiki/Sorting_algorithm
/*
1. Merge Sort
(a.) Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted)
(b.) Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list.
-------------------------
| Time | O(nlogn)| worst case
| Aux-Space | O(n) |
-------------------------
| In-place | no | we need auxiliary space
| Stable | yes | Most implementation are stable
| Online | no |
-------------------------
Highlights:
1. Can be applied to lists as it require sequential access. Best chois for sorting linked list.
2. Its based on divide and conquer paradigm.
Todo :Must Visit https://en.wikipedia.org/wiki/Merge_sort#Comparison_with_other_sort_algorithms
*/
private fun sort(arr: IntArray) {
fun merge(arr: IntArray, l: Int, m: Int, r: Int) {
var aux = IntArray(r - l + 1)
var i = l
var j = m + 1
var k = 0
while (i <= m && j <= r) {
if (arr[i] <= arr[j]) aux[k++] = arr[i++]
else aux[k++] = arr[j++]
}
while (i <= m) aux[k++] = arr[i++]
while (j <= r) aux[k++] = arr[j++]
i = l
for (a in aux) arr[i++] = a
}
fun mergeSort(arr: IntArray, l: Int, r: Int) {
if (l < r) {
var m = l + (r - l) / 2
mergeSort(arr, 0, m)
mergeSort(arr, m + 1, r)
merge(arr, l, m, r)
}
}
mergeSort(arr, 0, arr.lastIndex)
}
fun main() {
var arr = intArrayOf(64, 25, 12, 22, 11)
println(sort(arr))
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 1,729 | kotlinmaster | Apache License 2.0 |
src/main/kotlin/aoc2019/CrossedWires.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.utils.Direction
import komu.adventofcode.utils.Direction.*
import komu.adventofcode.utils.Point
private typealias Wire = List<Movement>
fun crossedWires(input: String): Int {
val (wire1, wire2) = input.lines().take(2).map { parseWire(it) }
val visited = wire1.points().toSet()
return wire2.points().filter { it in visited }.map { it.manhattanDistanceFromOrigin }.minOrNull() ?: Integer.MAX_VALUE
}
fun crossedWires2(input: String): Int {
val (wire1, wire2) = input.lines().take(2).map { parseWire(it) }
val stepsToPoint = mutableMapOf<Point, Int>()
for ((steps, point) in wire1.points().withIndex())
stepsToPoint.putIfAbsent(point, steps)
var minCount = Integer.MAX_VALUE
for ((steps, point) in wire2.points().withIndex()) {
val count2 = stepsToPoint[point]
if (count2 != null)
minCount = minOf(minCount, steps + count2)
}
return minCount + 2 // convert 0-based indices to 1-based steps
}
private fun Wire.points(): Sequence<Point> = sequence {
var point = Point.ORIGIN
for (movement in this@points) {
repeat(movement.steps) {
point += movement.direction
yield(point)
}
}
}
private fun parseWire(wire: String): Wire =
wire.split(',').map(Movement.Companion::parse)
private class Movement(val direction: Direction, val steps: Int) {
companion object {
fun parse(step: String) = Movement(
direction = when (step[0]) {
'U' -> UP
'D' -> DOWN
'L' -> LEFT
'R' -> RIGHT
else -> error("invalid direction ${step[0]}")
}, steps = step.substring(1).toInt()
)
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,784 | advent-of-code | MIT License |
src/main/kotlin/g0901_1000/s1000_minimum_cost_to_merge_stones/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s1000_minimum_cost_to_merge_stones
// #Hard #Array #Dynamic_Programming #2023_05_13_Time_152_ms_(75.00%)_Space_35.5_MB_(12.50%)
class Solution {
private lateinit var memo: Array<IntArray>
private lateinit var prefixSum: IntArray
fun mergeStones(stones: IntArray, k: Int): Int {
val n = stones.size
if ((n - 1) % (k - 1) != 0) {
return -1
}
memo = Array(n) { IntArray(n) }
for (arr in memo) {
arr.fill(-1)
}
prefixSum = IntArray(n + 1)
for (i in 1 until n + 1) {
prefixSum[i] = prefixSum[i - 1] + stones[i - 1]
}
return dp(0, n - 1, k)
}
private fun dp(left: Int, right: Int, k: Int): Int {
if (memo[left][right] > 0) {
return memo[left][right]
}
if (right - left + 1 < k) {
memo[left][right] = 0
return memo[left][right]
}
if (right - left + 1 == k) {
memo[left][right] = prefixSum[right + 1] - prefixSum[left]
return memo[left][right]
}
var `val` = Int.MAX_VALUE
var i = 0
while (left + i + 1 <= right) {
`val` = `val`.coerceAtMost(dp(left, left + i, k) + dp(left + i + 1, right, k))
i += k - 1
}
if ((right - left) % (k - 1) == 0) {
`val` += prefixSum[right + 1] - prefixSum[left]
}
memo[left][right] = `val`
return `val`
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,498 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/tw/gasol/aoc/aoc2022/Day4.kt | Gasol | 574,784,477 | false | {"Kotlin": 70912, "Shell": 1291, "Makefile": 59} | package tw.gasol.aoc.aoc2022
class Day4 {
fun part1(input: String): Int {
return input.lineSequence()
.filterNot { it.isBlank() }
.map(::toTwoSections)
.filter { it.isFullContained() }
.count()
}
private fun toTwoSections(line: String): Pair<IntRange, IntRange> {
val (first, second) = line.split(",")
.map {
it.split("-")
.map { num -> num.toInt() }
.let { (start, end) -> start..end }
}
return first to second
}
fun part2(input: String): Int {
return input.lineSequence()
.filterNot { it.isBlank() }
.map(::toTwoSections)
.filter { it.first.contains(it.second) || it.second.contains(it.first) }
.count()
}
}
fun IntRange.containsAll(other: IntRange): Boolean {
return this.first <= other.first && this.last >= other.last
}
fun IntRange.contains(other: IntRange): Boolean {
return (this.first <= other.first && this.last >= other.first) ||
(this.first <= other.last && this.last >= other.last)
}
fun Pair<IntRange, IntRange>.isFullContained(): Boolean {
val (first, second) = this
return first.containsAll(second) || second.containsAll(first)
} | 0 | Kotlin | 0 | 0 | a14582ea15f1554803e63e5ba12e303be2879b8a | 1,312 | aoc2022 | MIT License |
src/main/kotlin/Day08.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | fun main() {
fun parseLine(line: String): List<Int> =
line.toList().map { it.digitToInt() }.toList()
fun parse(input: List<String>): List<List<Int>> = input.map { parseLine(it) }
fun part1(input: List<String>): Int {
val heights = parse(input)
val visible = mutableListOf<MutableList<Boolean>>()
for (row in heights) {
val newrow = mutableListOf<Boolean>()
for (tree in row) {
newrow.add(false)
}
visible.add(newrow)
}
for (rowIdx in heights.indices) {
val row = heights[rowIdx]
var shortest = -1
for (fromLeftIdx in row.indices) {
if (row[fromLeftIdx] > shortest) {
visible[rowIdx][fromLeftIdx] = true
shortest = row[fromLeftIdx]
}
}
shortest = -1
for (fromRightIdx in row.indices.reversed()) {
if (row[fromRightIdx] > shortest) {
visible[rowIdx][fromRightIdx] = true
shortest = row[fromRightIdx]
}
}
}
for (colIdx in heights[0].indices) {
var shortest = -1
for (fromTopIdx in heights.indices) {
if (heights[fromTopIdx][colIdx] > shortest) {
visible[fromTopIdx][colIdx] = true
shortest = heights[fromTopIdx][colIdx]
}
}
shortest = -1
for (fromBottomIdx in heights.indices.reversed()) {
if (heights[fromBottomIdx][colIdx] > shortest) {
visible[fromBottomIdx][colIdx] = true
shortest = heights[fromBottomIdx][colIdx]
}
}
}
return visible.flatten().count { it }
}
fun part2(input: List<String>): Int {
val heights = parse(input)
val scores = mutableListOf<MutableList<Int>>()
for (row in heights) {
val newrow = mutableListOf<Int>()
for (tree in row) {
newrow.add(0)
}
scores.add(newrow)
}
fun viewingDistance(rowIdx: Int, colIdx: Int): Int {
val height = heights[rowIdx][colIdx]
var score = 1
var inc = 0
var movingUp = rowIdx - 1
while (movingUp >= 0) {
inc++
if (heights[movingUp][colIdx] >= height) {
break
}
movingUp--
}
score *= inc
inc = 0
var movingDown = rowIdx + 1
while (movingDown <= heights.lastIndex) {
inc++
if (heights[movingDown][colIdx] >= height) {
break
}
movingDown++
}
score *= inc
inc = 0
var movingLeft = colIdx - 1
while (movingLeft >= 0) {
inc++
if (heights[rowIdx][movingLeft] >= height) {
break
}
movingLeft--
}
score *= inc
inc = 0
var movingRight = colIdx + 1
while (movingRight <= heights[0].lastIndex) {
inc++
if (heights[rowIdx][movingRight] >= height) {
break
}
movingRight++
}
score *= inc
return score
}
for (rowIdx in heights.indices.drop(1).dropLast(1)) {
for (colIdx in heights[rowIdx].indices.drop(1).dropLast(1)) {
scores[rowIdx][colIdx] = viewingDistance(rowIdx, colIdx)
}
}
return scores.flatten().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 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 4,130 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day5.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.chunks
import shared.getText
fun main() {
val input = getText("day5.txt")
println(day5A(input))
println(day5B(input))
}
fun day5A(input: String): String {
val (drawing, procedures) = input.chunks()
val stacks = readDrawing(drawing)
for(procedure in procedures.lines()) {
val moveN = procedure.split(' ')[1].toInt()
val moveFrom = procedure.split(' ')[3].toInt() - 1
val moveTo = procedure.split(' ')[5].toInt() - 1
repeat(moveN) {
stacks[moveTo].add(stacks[moveFrom].removeLast())
}
}
return stacks.topWord()
}
fun day5B(input: String): String {
val (drawing, procedures) = input.chunks()
val stacks = readDrawing(drawing)
for(procedure in procedures.lines()) {
val moveN = procedure.split(' ')[1].toInt()
val moveFrom = procedure.split(' ')[3].toInt() - 1
val moveTo = procedure.split(' ')[5].toInt() - 1
stacks[moveTo].addAll(stacks[moveFrom].pop(moveN))
}
return stacks.topWord()
}
private fun readDrawing(drawing: String): List<MutableList<Char>> {
val stacks = List(9) { mutableListOf<Char>() }
for(line in drawing.lines().reversed()) {
Regex("[A-Z]").findAll(line).forEach { letter ->
val stack = letter.range.first / 4
stacks[stack] += letter.value.first()
}
}
return stacks
}
private fun MutableList<Char>.pop(n: Int): List<Char> {
val take = takeLast(n)
repeat(n) {
removeLast()
}
return take
}
private fun List<MutableList<Char>>.topWord() = mapNotNull { it.lastOrNull() }.joinToString("")
| 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 1,636 | AdventOfCode2022 | MIT License |
src/year2022/day17/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2022.day17
import arrow.optics.copy
import arrow.optics.optics
import io.kotest.matchers.shouldBe
import kotlin.math.max
import utils.Direction
import utils.Point
import utils.continuing
import utils.cyclical
import utils.mapSecond
import utils.move
import utils.readInput
import utils.x
import utils.y
fun main() {
val testInput = readInput("17", "test_input").first()
val realInput = readInput("17", "input").first()
findCycle(testInput)
.totalHeight(2022L)
.also(::println) shouldBe 3068L
findCycle(realInput)
.totalHeight(2022L)
.let(::println)
findCycle(testInput)
.totalHeight(1000000000000)
.also(::println) shouldBe 1514285714288L
findCycle(realInput)
.totalHeight(1000000000000)
.let(::println)
}
private fun findCycle(completePushSequence: String): Cycle {
val testRockMovements = completePushSequence.asRockMovementSequence()
val shapeSequence = Shape.values().asSequence().cyclical().continuing()
return generateSequence(emptyList<RockFallPattern>()) { previousState ->
val lastRockFallPattern = previousState.lastOrNull()
val startingPosition = Point(2, (lastRockFallPattern?.towerHeight?.unaryMinus() ?: 0) - 3)
val initialRock = Rock(
startingPosition,
shapeSequence.first()
)
val (restingRock, pushSequence) = initialRock.fall(testRockMovements, previousState)
val rockTop = restingRock.occupiedSpace.minOf { it.y }
val fallenRock = RockFallPattern(
restingRock = restingRock,
pushSequence = pushSequence!!,
towerHeight = if (lastRockFallPattern == null) 1 - rockTop
else max(lastRockFallPattern.towerHeight, 1 - rockTop)
)
previousState + fallenRock
}
.mapNotNull { it.toCycleOrNull() }
.first()
}
private fun Rock.fall(
testRockMovements: Sequence<IndexedValue<Direction>>,
previousState: List<RockFallPattern>,
): Pair<Rock, Pair<IndexedValue<Direction>, IndexedValue<Direction>>?> {
return generateSequence(this to null as Pair<IndexedValue<Direction>, IndexedValue<Direction>>?) { (rock, pushSequence) ->
val currentMovement = testRockMovements.first()
val movement = currentMovement.value
val movedRock = rock.move(movement)
val isInvalidPosition = movedRock.occupiedSpace.any { rockPart ->
rockPart.x !in 0 until 7
|| rockPart.y > 0
|| rockPart in previousState.flatMap { it.restingRock.occupiedSpace }
}
if (movement == Direction.Down && isInvalidPosition) null
else (if (isInvalidPosition) rock else movedRock) to (
pushSequence?.mapSecond { currentMovement } ?: (currentMovement to currentMovement)
)
}.last()
}
private fun String.asRockMovementSequence(): Sequence<IndexedValue<Direction>> {
return asSequence()
.map { if (it == '>') Direction.Right else Direction.Left }
.withGravity()
.withIndex()
.cyclical()
.continuing()
}
private fun Sequence<Direction.Horizontal>.withGravity() = flatMap { sequenceOf(it, Direction.Down) }
@optics
data class Rock(
val reference: Point,
val shape: Shape,
) {
val occupiedSpace = occupiedSpaceFrom(reference, shape)
companion object
}
enum class Shape {
FLAT_LINE, PLUS, CORNER, TALL_LINE, SQUARE
}
private fun Rock.move(direction: Direction) = Rock.reference.modify(this) { it move direction }
private fun occupiedSpaceFrom(reference: Point, shape: Shape): Set<Point> = when (shape) {
Shape.FLAT_LINE -> generateSequence(reference, Point.x.lift(Int::inc)).take(4).toSet()
Shape.PLUS -> setOf(
Point.x.modify(reference, Int::inc),
Point.y.modify(reference, Int::dec),
reference.copy {
Point.x transform { it + 2 }
Point.y transform Int::dec
},
reference.copy {
Point.x transform Int::inc
Point.y transform { it - 2 }
},
)
Shape.CORNER -> setOf(
reference,
Point.x.modify(reference, Int::inc),
Point.x.modify(reference) { it + 2 },
reference.copy {
Point.x transform { it + 2 }
Point.y transform Int::dec
},
reference.copy {
Point.x transform { it + 2 }
Point.y transform { it - 2 }
},
)
Shape.TALL_LINE -> generateSequence(reference, Point.y.lift(Int::dec)).take(4).toSet()
Shape.SQUARE -> setOf(
reference,
Point.x.modify(reference, Int::inc),
reference.copy {
Point.x transform Int::inc
Point.y transform Int::dec
},
Point.y.modify(reference, Int::dec),
)
}
private fun List<RockFallPattern>.toCycleOrNull(): Cycle? {
val reference = lastOrNull() ?: return null
val cycleStart = asSequence()
.withIndex()
.lastOrNull { (index, potentialCycleStart) ->
potentialCycleStart != reference
&& potentialCycleStart.pushSequence.first.index == reference.pushSequence.first.index
&& potentialCycleStart.pushSequence.second.index == reference.pushSequence.second.index
&& potentialCycleStart.restingRock.reference.x == reference.restingRock.reference.x
&& potentialCycleStart.restingRock.shape == reference.restingRock.shape
&& topTower(lastIndex) == topTower(index)
}?.index
return if (cycleStart != null && cycleStart in indices) Cycle(
preCycle = take(cycleStart + 1),
cycle = subList(cycleStart + 1, size),
) else null
}
private fun List<RockFallPattern>.topTower(rockCount: Int): Set<Point> {
val heightDifference = this[rockCount].towerHeight - last().towerHeight
return subList(rockCount - 9, rockCount + 1)
.asSequence()
.flatMap { it.restingRock.occupiedSpace }
.mapTo(mutableSetOf(), Point.y.lift { it + heightDifference })
}
private fun Cycle.totalHeight(rockCount: Long): Long {
if (rockCount <= preCycle.size) return preCycle[rockCount.toInt() - 1].towerHeight.toLong()
val heightAtCycleStart = preCycle.last().towerHeight
val cycleHeight = cycle.last().towerHeight - heightAtCycleStart
val cycleCount = (rockCount - preCycle.size) / cycle.size
val missingRocks = (rockCount - preCycle.size) % cycle.size
val missingHeight =
if (missingRocks == 0L) 0L else cycle[missingRocks.toInt() - 1].towerHeight.toLong() - heightAtCycleStart
return heightAtCycleStart + cycleCount * cycleHeight + missingHeight
}
@optics
data class RockFallPattern(
val restingRock: Rock,
val pushSequence: Pair<IndexedValue<Direction>, IndexedValue<Direction>>,
val towerHeight: Int = 0,
) {
companion object
}
private data class Cycle(
val preCycle: List<RockFallPattern>,
val cycle: List<RockFallPattern>,
)
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 6,989 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/dev/siller/aoc2023/Day06.kt | chearius | 725,594,554 | false | {"Kotlin": 50795, "Shell": 299} | package dev.siller.aoc2023
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.pow
import kotlin.math.sqrt
data object Day06 : AocDayTask<ULong, ULong>(
day = 6,
exampleInput =
"""
|Time: 7 15 30
|Distance: 9 40 200
""".trimMargin(),
expectedExampleOutputPart1 = 288u,
expectedExampleOutputPart2 = 71503u
) {
private val WHITESPACES = "\\s+".toRegex()
private data class Race(
val duration: ULong,
val distance: ULong
)
override fun runPart1(input: List<String>): ULong =
parseRaces(input, ignoreSpaces = false).run(::determineNumberOfWaysToWin)
override fun runPart2(input: List<String>): ULong =
parseRaces(input, ignoreSpaces = true).run(::determineNumberOfWaysToWin)
private fun parseRaces(
input: List<String>,
ignoreSpaces: Boolean = false
): List<Race> {
if (input.size != 2) {
error("Invalid number of lines in the input data.")
}
val replacement =
if (ignoreSpaces) {
""
} else {
" "
}
val durations = input[0].substringAfter(':').trim().replace(WHITESPACES, replacement).split(' ')
val distances = input[1].substringAfter(':').trim().replace(WHITESPACES, replacement).split(' ')
if (durations.size != distances.size) {
error("The number of race durations is not equal to the number of race distance records.")
}
return durations.mapIndexed { index, duration ->
Race(duration.toULong(), distances[index].toULong())
}
}
private fun determineNumberOfWaysToWin(races: List<Race>): ULong =
races
.map { race ->
// Equation to solve: x * (race.duration - x) - race.distance > 0
// -x^2 + race.duration * x - race.distance > 0
// x^2 - race.duration * x - race.distance > 0
// Solutions: x_1 next integer, x_2 previous integer
val intervalHalf = sqrt((race.duration.toDouble() / 2.0).pow(2) - race.distance.toDouble())
val intervalStart = race.duration.toDouble() / 2.0 - intervalHalf
val intervalEnd = race.duration.toDouble() / 2.0 + intervalHalf
val firstWinningTime =
if (intervalStart == ceil(intervalStart)) {
intervalStart.toULong() + 1u
} else {
ceil(intervalStart).toULong()
}
val lastWinningTime =
if (intervalEnd == floor(intervalEnd)) {
intervalEnd.toULong() - 1u
} else {
floor(intervalEnd).toULong()
}
lastWinningTime - firstWinningTime + 1u
}.fold(1u) { acc, i ->
acc * i
}
}
| 0 | Kotlin | 0 | 0 | fab1dd509607eab3c66576e3459df0c4f0f2fd94 | 3,017 | advent-of-code-2023 | MIT License |
src/main/day04/Day04.kt | FlorianGz | 573,204,597 | false | {"Kotlin": 8491} | package main.day04
import readInput
import kotlin.math.max
import kotlin.math.min
fun main() {
val elfSections = readInput("main/day04/day04")
fun part1(): Int {
return elfSections.map { it.asRanges() }.count { (range1, range2) ->
range1.containedIn(range2) >= 2 || range2.containedIn(range1) >= 2
}
}
fun part2(): Int {
return elfSections.map { it.asRanges() }.count { (range1, range2) ->
range1.containedIn(range2) >= 0 || range2.containedIn(range1) >= 0
}
}
println(part1())
println(part2())
}
private fun String.asRanges(): Pair<IntRange,IntRange> = substringBefore(",").asIntRange() to substringAfter(",").asIntRange()
private fun String.asIntRange(): IntRange = substringBefore("-").toInt() .. substringAfter("-").toInt()
private fun IntRange.containedIn(other: IntRange) = (min(endInclusive, other.last) - max(start, other.first)).coerceAtLeast(-1)
| 0 | Kotlin | 0 | 0 | 58c9aa8fdec77c25a9d9945ca8e77ecd1170321b | 948 | aoc-kotlin-2022 | Apache License 2.0 |
Hackerrank/queens-attack-2-v1.kt | myinnernerd | 423,058,040 | true | {"Java": 95496, "C++": 36899, "Python": 8691, "JavaScript": 5544, "Kotlin": 4888, "C#": 4557, "C": 2699, "Ruby": 1277, "Clojure": 1018, "Scala": 563, "OCaml": 121} | import kotlin.collections.*
import kotlin.io.*
import kotlin.math.abs
import kotlin.ranges.*
import kotlin.text.*
/**
* @author: <NAME>
* This problem comes from HackerRank: https://www.hackerrank.com/challenges/queens-attack-2/problem
*
* queensAttack() Function Description:
* Given the queen's position and the locations of all the obstacles on a chess board,
* find and print the number of squares the queen can attack from her position at (r, c)
*
* @param:
* - int n: the number of rows and columns in the board
* - int k: the number of obstacles on the board
* - int r_q: the row number of the queen's position
* - int c_q: the column number of the queen's position
* - int obstacles[k][2]: each element is an array of integers, the row number and column number of an obstacle
*
* @return:
* - int: the number of squares the queen can attack
*
* Constraints:
* - 0 < n <= 10^5
* - 0 <= k <= 10 ^5
* - A single cell may contain more than one obstacle
* - There will never be an obstacle at the position where the queen is located
*
* Notes:
* Because there can be duplicate obstacles and because the obstacles are not in order,
* we have to iterate through the entire array of obstacles, checking the location of each.
* This results in a time complexity of O(n), where n = length of obstacles array
*
*/
fun queensAttack(n: Int, k: Int, r_q: Int, c_q: Int, obstacles: Array<Array<Int>>): Int {
val queenRow = r_q
val queenCol = c_q
var spacesUp = n - queenRow
var spacesDown = queenRow - 1
var spacesRight = n - queenCol
var spacesLeft = queenCol - 1
var spacesUpperLeft = minOf(spacesUp, spacesLeft)
var spacesLowerRight = minOf(spacesDown, spacesRight)
var spacesUpperRight = minOf(spacesUp, spacesRight)
var spacesLowerLeft = minOf(spacesDown, spacesLeft)
// Iterate through array of obstacles, calculating the distance between the queen and each obstacle.
// Keep track of the nearest obstacles by always storing the shortest distances.
obstacles.forEach {
val obstacleRow = it[0]
val obstacleCol = it[1]
fun hasNegativeSlopeOf1(row1: Int, row2: Int, col1: Int, col2: Int) = (row2 - row1) == -1 * (col2 - col1)
fun hasPositiveSlopeOf1(row1: Int, row2: Int, col1: Int, col2: Int) = (row2 - row1) == (col2 - col1)
fun distanceBetween(num1: Int, num2: Int) = abs(num1 - num2) - 1
when {
queenCol == obstacleCol -> {
val spacesBetweenRows = distanceBetween(obstacleRow, queenRow)
if (queenRow < obstacleRow) spacesUp = minOf(spacesUp, spacesBetweenRows)
else spacesDown = minOf(spacesDown, spacesBetweenRows)
}
queenRow == obstacleRow -> {
val spacesBetweenColumns = distanceBetween(obstacleCol, queenCol)
if (queenCol < obstacleCol) spacesRight = minOf(spacesRight, spacesBetweenColumns)
else spacesLeft = minOf(spacesLeft, spacesBetweenColumns)
}
// since the slope along the diagonal paths is 1 or -1,
// the difference in the rows and columns will be the same, so can use either
hasPositiveSlopeOf1(queenRow, obstacleRow, queenCol, obstacleCol) -> {
val spacesBetweenRows = distanceBetween(obstacleRow, queenRow)
if (queenRow < obstacleRow) spacesUpperRight = minOf(spacesUpperRight, spacesBetweenRows)
else spacesLowerLeft = minOf(spacesLowerLeft, spacesBetweenRows)
}
hasNegativeSlopeOf1(queenRow, obstacleRow, queenCol, obstacleCol) -> {
val spacesBetweenRows = distanceBetween(obstacleRow, queenRow)
if (queenRow < obstacleRow) spacesUpperLeft = minOf(spacesUpperLeft, spacesBetweenRows)
else spacesLowerRight = minOf(spacesLowerRight, spacesBetweenRows)
}
}
}
val allMoves = listOf(
spacesUp,
spacesDown,
spacesRight,
spacesLeft,
spacesUpperLeft,
spacesLowerRight,
spacesUpperRight,
spacesLowerLeft
)
return allMoves.sumBy { it }
}
/** The logic in main() was provided by HackerRank */
fun main(args: Array<String>) {
val first_multiple_input = readLine()!!.trimEnd().split(" ")
val n = first_multiple_input[0].toInt()
val k = first_multiple_input[1].toInt()
val second_multiple_input = readLine()!!.trimEnd().split(" ")
val r_q = second_multiple_input[0].toInt()
val c_q = second_multiple_input[1].toInt()
val obstacles = Array<Array<Int>>(k, { Array<Int>(2, { 0 }) })
for (i in 0 until k) {
obstacles[i] = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray()
}
val result = queensAttack(n, k, r_q, c_q, obstacles)
println(result)
}
| 0 | Java | 0 | 0 | b046b327a795ffd527112671413dc131d19bcc75 | 4,888 | Hacktoberfest | MIT License |
src/day05/Main.kt | nikwotton | 572,814,041 | false | {"Kotlin": 77320} | package day05
import java.io.File
import java.util.ArrayList
import java.util.Stack
const val workingDir = "src/day05"
fun main() {
val sample = File("$workingDir/sample.txt")
val input1 = File("$workingDir/input_1.txt")
println("Step 1a: ${runStep1(sample)}")
println("Step 1b: ${runStep1(input1)}")
println("Step 2a: ${runStep2(sample)}")
println("Step 2b: ${runStep2(input1)}")
}
fun runStep1(input: File): String {
val stacks = mutableListOf<Stack<Char>>()
input.readLines().takeWhile { !it.trim().first().isDigit() }.reversed().forEach {
it.replace("[", "").replace("]", "").replace(" ", "_").replace(" ", "").forEachIndexed { index, c ->
if (c != '_') {
while (stacks.getOrNull(index) == null) stacks.add(Stack())
stacks[index].push(c)
}
}
}
input.readLines().filter { it.startsWith("move ") }.forEach {
val count = it.removePrefix("move ").split(" ")[0].toInt()
val from = it.split(" from ")[1].split(" to ")[0].toInt()
val to = it.split(" to ")[1].toInt()
repeat(count) {
val moving = stacks[from - 1].pop()
stacks[to - 1].push(moving)
}
}
return stacks.map { it.peek() }.joinToString("")
}
fun runStep2(input: File): String {
val stacks = mutableListOf<Stack<Char>>()
input.readLines().takeWhile { !it.trim().first().isDigit() }.reversed().forEach {
it.replace("[", "").replace("]", "").replace(" ", "_").replace(" ", "").forEachIndexed { index, c ->
if (c != '_') {
while (stacks.getOrNull(index) == null) stacks.add(Stack())
stacks[index].push(c)
}
}
}
input.readLines().filter { it.startsWith("move ") }.forEach {
val count = it.removePrefix("move ").split(" ")[0].toInt()
val from = it.split(" from ")[1].split(" to ")[0].toInt()
val to = it.split(" to ")[1].toInt()
val moving = Stack<Char>()
repeat(count) {
moving.add(stacks[from - 1].pop())
}
moving.reversed().forEach {
stacks[to - 1].push(it)
}
}
return stacks.map { it.peek() }.joinToString("")
}
| 0 | Kotlin | 0 | 0 | dee6a1c34bfe3530ae6a8417db85ac590af16909 | 2,246 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountHighestScoreNodes.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 2049. Count Nodes With the Highest Score
* @see <a href="https://leetcode.com/problems/count-nodes-with-the-highest-score/">Source</a>
*/
fun interface CountHighestScoreNodes {
operator fun invoke(parents: IntArray): Int
}
class CountHighestScoreNodesDfs : CountHighestScoreNodes {
override operator fun invoke(parents: IntArray): Int {
if (parents.isEmpty()) return 0
val al: MutableList<MutableList<Int>> = ArrayList()
for (i in parents.indices) {
al.add(ArrayList())
}
val s = LongArray(parents.size)
for (i in 1 until parents.size) {
al[parents[i]].add(i)
}
dfs(al, s, 0)
val maxVal: Long = s.max()
return s.filter {
it == maxVal
}.size
}
private fun dfs(al: List<List<Int>>, s: LongArray, i: Int): Long {
var prod: Long = 1
var sum: Long = 1
for (j in al[i]) {
val cnt = dfs(al, s, j)
prod *= cnt
sum += cnt
}
s[i] = prod * max(1, al.size - sum)
return sum
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,772 | kotlab | Apache License 2.0 |
src/ad/kata/aoc2021/day03/DiagnosticReport.kt | andrej-dyck | 433,401,789 | false | {"Kotlin": 161613} | package ad.kata.aoc2021.day03
import ad.kata.aoc2021.PuzzleInput
import ad.kata.aoc2021.extensions.transposed
class DiagnosticReport(val statusCodes: List<BinaryNumber>) {
val gammaRate: BinaryNumber by lazy { mostCommonBits(statusCodes) }
val epsilonRate: BinaryNumber by lazy { gammaRate.inv() }
val oxygenGeneratorRating: BinaryNumber? by lazy {
findRatingValue(statusCodes) { mostCommonBits(it) }
}
val cO2ScrubberRating: BinaryNumber? by lazy {
findRatingValue(statusCodes) { leastCommonBits(it) }
}
private fun mostCommonBits(codes: List<BinaryNumber>): BinaryNumber {
val half = codes.size / 2.0
return BinaryNumber(
codes.map(BinaryNumber::toDigitsAsIntList)
.reduceCols(List<Int>::sum)
.map { if (it >= half) 1 else 0 }
.ifEmpty { listOf(0) }
)
}
private fun <T, R> List<List<T>>.reduceCols(transform: (List<T>) -> R): List<R> =
transposed().map(transform)
private fun leastCommonBits(codes: List<BinaryNumber>) =
mostCommonBits(codes).inv()
private tailrec fun findRatingValue(
codes: List<BinaryNumber>,
pos: Int = 0,
prevSize: Int = 0,
bitsMask: (List<BinaryNumber>) -> BinaryNumber
): BinaryNumber? =
if (codes.size <= 1 || codes.size == prevSize)
codes.firstOrNull()
else {
val sigBit = bitsMask(codes).bitFromLeft(pos)
val filtered = codes.filter { sigBit == it.bitFromLeft(pos) }
findRatingValue(filtered, pos = pos + 1, prevSize = codes.size, bitsMask)
}
private fun BinaryNumber.bitFromLeft(index: Int) = toString().getOrNull(index)
}
fun DiagnosticReport.powerConsumption() =
gammaRate.toInt() * epsilonRate.toInt()
fun DiagnosticReport.liveSupportRating() =
(oxygenGeneratorRating?.toInt() ?: 0) * (cO2ScrubberRating?.toInt() ?: 0)
fun diagnosticReportFromInput(filename: String) = DiagnosticReport(
PuzzleInput(filename).lines().map { BinaryNumber(it) }.toList()
) | 0 | Kotlin | 0 | 0 | 28d374fee4178e5944cb51114c1804d0c55d1052 | 2,081 | advent-of-code-2021 | MIT License |
src/Day02.kt | msernheim | 573,937,826 | false | {"Kotlin": 32820} | fun main() {
fun getMoveScore(s: String): Int {
return when (s) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
}
fun getMatchScore(moveA: String, moveB: String): Int {
return when (moveA) {
"A" -> {
when (moveB) {
"X" -> 3
"Y" -> 6
"Z" -> 0
else -> 0
}
}
"B" -> {
when (moveB) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> 0
}
}
"C" -> {
when (moveB) {
"X" -> 6
"Y" -> 0
"Z" -> 3
else -> 0
}
}
else -> 0
}
}
fun part1(input: List<String>): Int {
var score = 0
input.forEach { row ->
val moves = row.split(" ")
val moveScore = getMoveScore(moves[1])
val matchScore = getMatchScore(moves[0], moves[1])
score += moveScore
score += matchScore
}
return score
}
fun figureOutMovePart2(moves: List<String>): String {
return when (moves[1]) {
"X" -> { //LOSE
when (moves[0]) {
"A" -> "Z"
"B" -> "X"
"C" -> "Y"
else -> ""
}
}
"Y" -> (moves[0].toCharArray()[0].code + 23).toChar().toString() //DRAW
"Z" -> {//WIN
when (moves[0]) {
"A" -> "Y"
"B" -> "Z"
"C" -> "X"
else -> ""
}
}
else -> ""
}
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach { row ->
val moves = row.split(" ")
val moveToMake = figureOutMovePart2(moves)
score += getMoveScore(moveToMake) + getMatchScore(moves[0], moveToMake)
}
return score
}
val input = readInput("Day02")
val part1 = part1(input)
val part2 = part2(input)
println("Result part1: $part1")
println("Result part2: $part2")
}
| 0 | Kotlin | 0 | 3 | 54cfa08a65cc039a45a51696e11b22e94293cc5b | 2,399 | AoC2022 | Apache License 2.0 |
src/main/kotlin/year2023/Day11.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2023
import utils.Point2D
class Day11 {
fun part1(input: String) = solve(input, 2L)
fun part2(input: String) = solve(input, 1000000L)
fun solve(input: String, shift: Long): Long {
val space = input.lines().map { it.toCharArray() }
space.forEach { row ->
if (row.all { it == '.' }) {
row.indices.forEach { col -> row[col] = 'v' }
}
}
space[0].indices.forEach { colIdx ->
if (space.all { row -> row[colIdx] == '.' || row[colIdx] == 'v' }) {
space.forEach { row -> row[colIdx] = 'v' }
}
}
val points = space.flatMapIndexed { rowIdx, row ->
row.mapIndexed { colIdx, col ->
if (col == '#') {
Point2D(colIdx, rowIdx)
} else {
null
}
}.filterNotNull()
}
return points.indices.flatMap { idx1 ->
points.indices.drop(idx1).map { idx2 ->
var p1 = points[idx1]
val p2 = points[idx2]
var counter = 0L
while (p1 != p2) {
p1 = if (p1.x < p2.x) {
p1.move(1, 0)
} else if (p1.x > p2.x) {
p1.move(-1, 0)
} else if (p1.y < p2.y) {
p1.move(0, 1)
} else {
p1.move(0, -1)
}
counter = if (space[p1.y][p1.x] == 'v') {
counter + shift
} else {
counter + 1L
}
}
counter
}
}.sum()
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 1,785 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | KristianAN | 571,726,775 | false | {"Kotlin": 9011} | fun Char.valueOf(): Int =
if (this.isLowerCase()) this.code.minus(96) else this.code.minus(38)
fun main() {
fun part1(input: List<String>): Int = input.map { s ->
s.chunked(s.length / 2).let { it[0].toSet().intersect(it[1].toSet()) }.toCharArray()[0]
}.sumOf { it.valueOf() }
fun part2(input: List<String>): Int = input.chunked(3).map { rucksacks ->
rucksacks[0].first { char -> (rucksacks[1].contains(char) && rucksacks[2].contains(char)) }
}.sumOf { it.valueOf() }
val input = readInput("day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3a3af6e99794259217bd31b3c4fd0538eb797941 | 596 | AoC2022Kt | Apache License 2.0 |
dojos/music-theory/kotlin/Main.kt | magrathealabs | 210,662,430 | false | null | data class Note(val name: String)
{
fun flatten() = Note(name[0].toString() + 'b')
}
val Notes by lazy {
listOf("C", "C#", "D", "D#", "E", "F",
"F#", "G", "G#", "A", "A#", "B")
.map { Note(it) }
}
enum class Interval(val value: Int) {
Half(1),
Whole(2),
WholeAndHalf(3);
operator fun times(multiplier: Int) =
Array(multiplier) { this }
}
infix fun Note.hasSameLetterOf(note: Note) =
this.name.startsWith(note.name[0])
/**
* Changes note names to avoid repeated letters (e.g. "F" followed by "F#").
*/
fun uniqueNotes(notes: List<Note>): List<Note>
{
val newNotes = notes.toMutableList()
return notes.foldIndexed(newNotes) { i, acc, note ->
val cycle = CyclicIterator(acc).apply { next(i) }
val chromaticCycle = CyclicIterator(Notes)
if (cycle.prev() hasSameLetterOf note)
acc.apply {
set(i, chromaticCycle.next(Notes.indexOf(note) + 1).flatten())
}
else
acc
}
}
open class Scale(val root: Note, vararg val intervals: Interval)
{
fun notes(): List<Note> {
val iterator = CyclicIterator(Notes)
iterator.next(Notes.indexOf(root))
val notes = intervals.dropLast(1).fold(mutableListOf(root)) {
acc, interval -> acc.apply { add(iterator.next(interval.value)) }
}
return uniqueNotes(notes)
}
}
object Scales
{
class Major(root: Note)
: Scale(root, Interval.Whole,
Interval.Whole,
Interval.Half,
Interval.Whole,
Interval.Whole,
Interval.Whole,
Interval.Half)
class Minor(root: Note)
: Scale(root, Interval.Whole,
Interval.Half,
Interval.Whole,
Interval.Whole,
Interval.Half,
Interval.Whole,
Interval.Whole)
}
open class Chord(val root: Note, val intervals: List<Array<Interval>>)
{
fun notes(): List<Note> {
val cyclicIterator = CyclicIterator(Notes).apply { next(Notes.indexOf(root)) }
return intervals.fold(mutableListOf<Note>()) {
acc, intervals -> acc.apply {
add(cyclicIterator.next(intervals.halfStepsCount))
}
}.apply { add(0, root) }
}
private val Array<Interval>.halfStepsCount get() =
fold(0) { sum, interval -> sum + interval.value }
}
object Chords
{
class MajorTriad(root: Note)
: Chord(root, listOf(Interval.Whole * 2,
Interval.Half * 3))
}
class CyclicIterator<T>(val list: List<T>)
{
private var position = 0
val current get() = list[position]
fun next(n: Int = 1) =
if (list.size == 0) {
list[0]
} else if (list.size > position + n) {
position += n
list[position]
} else {
position = position + n - list.size
list[position]
}
fun prev(n: Int = 1) =
if (position - n < 0) {
position = list.size - n
list[position]
} else {
position = position - n
list[position]
}
}
fun <T> assertEquals(a: T, b: T) {
try {
assert(a == b)
} catch (e: AssertionError) {
println("Expected: $a")
println("Received: $b")
throw e
}
}
fun main() {
assertEquals(
listOf("Db", "Eb", "F", "Gb", "Ab", "Bb", "C"),
Scales.Major(root = Note("C#")).notes().map { it.name }
)
assertEquals(
listOf("B", "C#", "D#", "E", "F#", "G#", "A#"),
Scales.Major(root = Note("B")).notes().map { it.name }
)
assertEquals(
listOf("Bb", "C", "D", "Eb", "F", "G", "A"),
Scales.Major(root = Note("A#")).notes().map { it.name }
)
assertEquals(
listOf("Gb", "Ab", "Bb", "Cb", "Db", "Eb", "F"),
Scales.Major(root = Note("F#")).notes().map { it.name }
)
assertEquals(
listOf("C", "D", "Eb", "F", "G", "Ab", "Bb"),
Scales.Minor(root = Note("C")).notes().map { it.name }
)
assertEquals(
listOf("C", "E", "G"),
Chords.MajorTriad(root = Note("C")).notes().map { it.name }
)
assertEquals(
listOf("D", "F#", "A"),
Chords.MajorTriad(root = Note("D")).notes().map { it.name }
)
println("All tests passed!")
}
| 0 | Jupyter Notebook | 1 | 27 | c6f28443895f70c9f677bc9346f9757cc526d678 | 4,565 | university | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[39]组合总和.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} |
import java.util.*
import kotlin.collections.ArrayList
//给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
//
// candidates 中的数字可以无限制重复被选取。
//
// 说明:
//
//
// 所有数字(包括 target)都是正整数。
// 解集不能包含重复的组合。
//
//
// 示例 1:
//
// 输入:candidates = [2,3,6,7], target = 7,
//所求解集为:
//[
// [7],
// [2,2,3]
//]
//
//
// 示例 2:
//
// 输入:candidates = [2,3,5], target = 8,
//所求解集为:
//[
// [2,2,2,2],
// [2,3,3],
// [3,5]
//]
//
//
//
// 提示:
//
//
// 1 <= candidates.length <= 30
// 1 <= candidates[i] <= 200
// candidate 中的每个元素都是独一无二的。
// 1 <= target <= 500
//
// Related Topics 数组 回溯算法
// 👍 1390 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
//递归回溯 剪枝
// 使用栈来保存当前层结果 栈顶操作 方便回溯移除不符合元素
//时间复杂度 O(n) n 为组合长度
//想法 每次从数组取出一个数与 target 相减 继续在数组中寻找数与 target 相减
var res = ArrayList<ArrayList<Int>>()
//递归
if (candidates.isEmpty()) return res
dfsCombination(0,LinkedList<Int>(),candidates,target,res)
return res
}
private fun dfsCombination(index: Int, stack: LinkedList<Int>, candidates: IntArray, target: Int, res: ArrayList<ArrayList<Int>>) {
//递归结束条件
if(target == 0){
//符合条件 保存数组
res.add(ArrayList(stack))
}
//逻辑处理 进入下层循环
//index 为本分支上一节点的减数下标
for(i in index until candidates.size){
//目标值大于当前 index 值 继续寻找
if (candidates[i] <= target){
stack.addLast(candidates[i])
dfsCombination(i,stack,candidates,target - candidates[i],res)
//回溯不符合的值
stack.removeLast()
}
}
//数据reverse
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 2,384 | MyLeetCode | Apache License 2.0 |
src/Day01.kt | sebastian-heeschen | 572,932,813 | false | {"Kotlin": 17461} | fun main() {
fun caloriesPerElf(
input: List<String>
): List<Int> {
val indexesOfSeparators = input.mapIndexedNotNull { index, element -> index.takeIf { element.isEmpty() } }
var indexToInsert1 = 0
val list = mutableListOf<Int>()
input.forEachIndexed { index, element ->
if (indexesOfSeparators.contains(index)) {
indexToInsert1++
} else {
if (list.size < indexToInsert1 + 1) {
list.apply { add(element.toInt()) }
} else {
list[indexToInsert1] += element.toInt()
}
}
}
return list
}
fun part1(input: List<String>): Int {
val list = caloriesPerElf(input)
return list.max()
}
fun part2(input: List<String>): Int = caloriesPerElf(input)
.sortedDescending()
.subList(0, 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 | 4432581c8d9c27852ac217921896d19781f98947 | 1,223 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/pl/klemba/aoc/day4/Main.kt | aklemba | 726,935,468 | false | {"Kotlin": 16373} | package pl.klemba.aoc.day4
import java.io.File
import kotlin.math.pow
fun main() {
// ----- PART 1 -----
File(inputPath)
.readLines()
.sumOf { card -> getNumberOfPointsForCard(card) }
.let { println(it) }
// ----- PART 2 -----
val cardList = File(inputPath)
.readLines()
val amountOfScratchCards = IntArray(cardList.size) { 1 }
cardList
.foldIndexed(amountOfScratchCards) { index, acc, card -> calculateNumberOfCards(card, acc, index) }
.sum()
.let { println(it) }
}
fun getNumberOfPointsForCard(card: String): Int {
val amountOfMatchingNumbers = getNumberOfMatchingNumbers(card)
return if (amountOfMatchingNumbers == 1) 1 else 2.0.pow(amountOfMatchingNumbers - 1).toInt()
}
fun getNumberOfMatchingNumbers(card: String): Int {
val winningNumbers = getWinningNumbers(card)
val numbersYouHave = getNumbersYouHave(card)
return winningNumbers.intersect(numbersYouHave.toSet()).size
}
fun getWinningNumbers(card: String): List<Int> =
winningNumbersRegex.find(card)
?.value
?.removeRange(0, 2)
?.trim()
?.split(" ", " ")
?.map { it.toInt() }
?: throw IllegalStateException("No winning numbers found!")
fun getNumbersYouHave(card: String): List<Int> =
numbersYouHaveRegex.find(card)
?.value
?.removeRange(0, 2)
?.trim()
?.split(" ", " ")
?.map { it.toInt() }
?: throw IllegalStateException("No your numbers found!")
fun calculateNumberOfCards(card: String, acc: IntArray, index: Int): IntArray {
val numberOfPoints = getNumberOfMatchingNumbers(card)
val numberOfCards = acc[index]
repeat(numberOfPoints) { i ->
acc[index + i + 1] += numberOfCards
}
return acc
}
private val winningNumbersRegex = Regex(""": +\d+(?: +\d+)+""")
private val numbersYouHaveRegex = Regex("""\| +\d+(?: +\d+)+""")
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day4/input.txt" | 0 | Kotlin | 0 | 1 | 2432d300d2203ff91c41ffffe266e19a50cca944 | 1,959 | adventOfCode2023 | Apache License 2.0 |
src/Day01.kt | jmorozov | 573,077,620 | false | {"Kotlin": 31919} | import java.util.PriorityQueue
fun main() {
val inputData = readInput("Day01")
part1(inputData)
part2(inputData)
}
private fun part1(inputData: List<String>) {
var theMostTotalCalories = 0
var currentElfCalories = 0
for (line in inputData) {
when(line.trim()) {
"" -> {
if (currentElfCalories > theMostTotalCalories) {
theMostTotalCalories = currentElfCalories
}
currentElfCalories = 0
}
else -> {
val caloriesNumber = line.toInt()
currentElfCalories += caloriesNumber
}
}
}
if (currentElfCalories > theMostTotalCalories) {
theMostTotalCalories = currentElfCalories
}
println("The most total calories: $theMostTotalCalories")
}
private const val NUMBER_OF_TOPS = 3
private fun part2(inputData: List<String>) {
var currentElfCalories = 0
val queue = PriorityQueue<Int>(NUMBER_OF_TOPS)
for (line in inputData) {
when(line.trim()) {
"" -> {
val minCaloriesNumber: Int? = queue.peek()
when {
minCaloriesNumber == null || queue.size < NUMBER_OF_TOPS -> queue.add(currentElfCalories)
minCaloriesNumber < currentElfCalories -> {
queue.poll()
queue.add(currentElfCalories)
}
}
currentElfCalories = 0
}
else -> {
val caloriesNumber = line.toInt()
currentElfCalories += caloriesNumber
}
}
}
val minCaloriesNumber: Int? = queue.peek()
if (minCaloriesNumber != null) {
if (queue.size < NUMBER_OF_TOPS) {
queue.add(currentElfCalories)
} else if (minCaloriesNumber < currentElfCalories) {
queue.poll()
queue.add(currentElfCalories)
}
}
val theMostNTotalCalories = queue.sum()
println("The most $NUMBER_OF_TOPS total calories: $theMostNTotalCalories")
}
| 0 | Kotlin | 0 | 0 | 480a98838949dbc7b5b7e84acf24f30db644f7b7 | 2,122 | aoc-2022-in-kotlin | Apache License 2.0 |
advent-of-code-2023/src/main/kotlin/Day08.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | // Day 08: <NAME>
// https://adventofcode.com/2023/day/8
import java.io.File
import kotlin.math.min
fun main() {
val lines = File("src/main/resources/Day08.txt").readLines()
val steps = lines.first().toList()
val map = lines.drop(2)
println(getHumanSteps(map, steps))
println(getGhostSteps(map, steps))
}
private fun getHumanSteps(map: List<String>, steps: List<Char>): Int {
val start = map.indexOfFirst { it.startsWith("AAA") }
val end = map.indexOfFirst { it.startsWith("ZZZ") }
var position = start
var counter = -1
while (position != end) {
counter++
val move = steps[counter % steps.size]
val step = getNextPath(map[position], move)
position = map.indexOfFirst { it.startsWith(step) }
}
return counter + 1
}
private fun getGhostSteps(map: List<String>, steps: List<Char>): Long {
val starts = map.filter { it[2] == 'A' }
val counts = starts.map { start ->
var counter = 0L
var index = 0
var step = start
while (step[2] != 'Z') {
val move = steps[index]
val next = getNextPath(step, move)
step = map.first { it.startsWith(next) }
index = (index + 1) % steps.size
counter++
}
counter
}
return counts.reduce { acc, i ->
lcm(acc, i)
}
}
private fun getNextPath(string: String, move: Char): String {
return if (move == 'L') {
string.substringAfter("(").substringBefore(", ")
} else {
string.substringAfter(", ").substringBefore(")")
}
}
private fun lcm(num1: Long, num2: Long): Long {
var lcm = min(num1, num2)
while (lcm <= num1 * num2) {
if (lcm % num1 == 0L && lcm % num2 == 0L) {
return lcm
}
lcm += min(num1, num2)
}
return lcm
} | 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 1,857 | advent-of-code | Apache License 2.0 |
commons/src/commonMain/kotlin/org/jetbrains/letsPlot/commons/intern/typedGeometry/algorithms/Geometry.kt | JetBrains | 176,771,727 | false | {"Kotlin": 6221641, "Python": 1158665, "Shell": 3495, "C": 3039, "JavaScript": 931, "Dockerfile": 94} | /*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.commons.intern.typedGeometry.algorithms
import org.jetbrains.letsPlot.commons.geometry.DoubleVector
import org.jetbrains.letsPlot.commons.interval.IntSpan
import kotlin.math.abs
fun <T> reduce(points: List<T>, dropDistance: Double, distance: (T, T) -> Double): List<T> {
return points.foldIndexed(mutableListOf()) { i, acc, el ->
if (i == 0) acc.add(el)
else if (i == points.lastIndex) acc.add(el)
else if (distance(acc.last(), el) >= dropDistance) acc.add(el)
acc
}
}
inline fun <reified T> splitRings(points: List<T>): List<List<T>> = splitRings(points) { o1, o2 -> o1 == o2 }
fun <T> splitRings(points: List<T>, eq: (T, T) -> Boolean): List<List<T>> {
val rings = findRingIntervals(points, eq).map(points::sublist).toMutableList()
if (rings.isNotEmpty()) {
if (!rings.last().isClosed()) {
rings[rings.lastIndex] = makeClosed(rings.last())
}
}
return rings
}
private fun <T> makeClosed(path: List<T>) = path.toMutableList() + path.first()
fun <T> List<T>.isClosed() = first() == last()
private fun <T> findRingIntervals(path: List<T>, eq: (T, T) -> Boolean): List<IntSpan> {
val intervals = ArrayList<IntSpan>()
var startIndex = 0
var i = 0
val n = path.size
while (i < n) {
if (startIndex != i && eq(path[startIndex], path[i])) {
intervals.add(IntSpan(startIndex, i + 1))
startIndex = i + 1
}
i++
}
if (startIndex != path.size) {
intervals.add(IntSpan(startIndex, path.size))
}
return intervals
}
private fun <T> List<T>.sublist(range: IntSpan): List<T> {
return this.subList(range.lowerEnd, range.upperEnd)
}
fun calculateArea(ring: List<DoubleVector>): Double {
return calculateArea(ring, DoubleVector::x, DoubleVector::y)
}
fun <T> isClockwise(ring: List<T>, x: (T) -> Double, y: (T) -> Double): Boolean {
check(ring.isNotEmpty()) { "Ring shouldn't be empty to calculate clockwise" }
var sum = 0.0
var prev = ring[ring.size - 1]
for (point in ring) {
sum += x(prev) * y(point) - x(point) * y(prev)
prev = point
}
return sum < 0.0
}
fun <T> calculateArea(ring: List<T>, x: T.() -> Double, y: T.() -> Double): Double {
var area = 0.0
var j = ring.size - 1
for (i in ring.indices) {
val p1 = ring[i]
val p2 = ring[j]
area += (p2.x() + p1.x()) * (p2.y() - p1.y())
j = i
}
return abs(area / 2)
}
| 128 | Kotlin | 46 | 1,373 | c61353ece18358ba6c6306a0f634e3b4b036577a | 2,671 | lets-plot | MIT License |
src/main/kotlin/days/Day3.kt | C06A | 435,034,782 | false | {"Kotlin": 20662} | package days
class Day3: Day(3) {
override fun partOne(): Any {
val onesCounts = Array<Int>(inputList[0].length) { 0 }
val half = inputList.size / 2
inputList.forEach {
it.toCharArray().forEachIndexed { i, char ->
if (char == '1') onesCounts[i]++
}
}
val (most, least) = onesCounts.fold(0 to 0) { pair, count ->
if( count > half) {
(pair.first * 2 + 1) to (pair.second * 2)
} else {
(pair.first * 2) to (pair.second * 2 + 1)
}
}
return most * least
}
override fun partTwo(): Any {
val (generator, scrubber) = inputList.map { it.toCharArray() }.run {
reduce {
val ones: List<CharArray> = it['1'] ?: emptyList()
val zeros: List<CharArray> = it['0'] ?: emptyList()
if (zeros.size > ones.size) {
zeros
} else {
ones
}
}[0] to reduce {
val ones: List<CharArray> = it['1'] ?: emptyList()
val zeros: List<CharArray> = it['0'] ?: emptyList()
if (zeros.size > ones.size) {
ones
} else {
zeros
}
}[0]
}
return String(generator).toInt(2) * String(scrubber).toInt(2)
}
fun List<CharArray>.reduce(
bitIndx: Int = 0,
reducer: (Map<Char, List<CharArray>>) -> List<CharArray>
): List<CharArray> {
if (size == 1) {
return this
}
return reducer(groupBy {
it[bitIndx]
}).reduce(bitIndx + 1, reducer)
}
}
| 0 | Kotlin | 0 | 0 | afbe60427eddd2b6814815bf7937a67c20515642 | 1,756 | Aoc2021 | Creative Commons Zero v1.0 Universal |
src/day04/Day04.kt | easchner | 572,762,654 | false | {"Kotlin": 104604} | package day04
import readInputString
fun main() {
fun part1(input: List<String>): Long {
var totalOverlap = 0L
for (line in input) {
val elves = line.split(",").map {
it.split("-").map {
it.toInt()
}
}.map {
(it[0]..it[1]).toSet()
}
if (elves[0].intersect(elves[1]) == elves[0] ||
elves[1].intersect(elves[0]) == elves[1]) {
totalOverlap++
}
}
return totalOverlap
}
fun part2(input: List<String>): Long {
var totalOverlap = 0L
for (line in input) {
val elves = line.split(",").map {
it.split("-").map {
it.toInt()
}
}.map {
(it[0]..it[1]).toSet()
}
if (elves[0].intersect(elves[1]).isNotEmpty()) {
totalOverlap++
}
}
return totalOverlap
}
val testInput = readInputString("day04/test")
val input = readInputString("day04/input")
check(part1(testInput) == 2L)
println(part1(input))
check(part2(testInput) == 4L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 1,254 | Advent-Of-Code-2022 | Apache License 2.0 |
src/net/sheltem/aoc/y2022/Day12.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2022
class Day12 : Day<Int>(31, 29) {
override suspend fun part1(input: List<String>) = HeightMap(input).dijkstra().goal.cost
override suspend fun part2(input: List<String>) = HeightMap(input, true).dijkstra().goal.cost
}
suspend fun main() {
Day12().run()
}
class HeightMap(input: List<String>, aIsZero: Boolean = false) {
private lateinit var start: Coordinate
lateinit var goal: Coordinate
private val coordinates: List<Coordinate> =
input.mapIndexed { y, row ->
row.mapIndexed { x, char ->
Coordinate(x, y, char.height()).apply {
if (char == 'S' || (aIsZero && height == 0)) cost = 0
if (char == 'S') start = this
if (char == 'E') goal = this
}
}
}.flatten()
fun dijkstra(coordinate: Coordinate = start): HeightMap = this.apply {
coordinate.visited = true
val cost = coordinate.cost + 1
coordinate.neighbours().filter { it.cost > cost }.forEach { it.cost = cost }
coordinates.filterNot { it.visited }.minByOrNull { it.cost }?.let { dijkstra(it) }
}
private fun Coordinate.neighbours() = listOfNotNull(
find(x - 1, y, height),
find(x + 1, y, height),
find(x, y - 1, height),
find(x, y + 1, height),
)
private fun find(x: Int, y: Int, maxHeight: Int) = coordinates.asSequence().filter { it.height <= maxHeight + 1 }.find { it.x == x && it.y == y }
}
class Coordinate(
val x: Int,
val y: Int,
val height: Int,
var cost: Int = Int.MAX_VALUE,
var visited: Boolean = false
)
private fun Char.height() = when (this) {
'S' -> 0
'E' -> 26
else -> this - 'a'
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 1,764 | aoc | Apache License 2.0 |
LeetCode/Medium/3-sum/Solution.kt | GregoryHo | 254,657,102 | false | null | class Solution {
fun threeSum(nums: IntArray): List<List<Int>> {
val size = nums.size
val sortedNums = nums.sorted()
val answers = mutableListOf<List<Int>>()
if (size < 3) {
return answers
}
for (i in 0 until size - 2) {
var leftIndex = i + 1
var rightIndex = size - 1
val num = sortedNums[i]
if (i > 0 && num == sortedNums[i - 1]) {
continue
}
while (leftIndex < rightIndex) {
val leftNum = sortedNums[leftIndex]
val rightNum = sortedNums[rightIndex]
val sum = leftNum + rightNum
if (num + sum == 0) {
answers.add(listOf(num, leftNum, rightNum))
// skip left value which the same as previous
while (leftIndex < rightIndex && leftNum == sortedNums[leftIndex + 1]) {
leftIndex++
}
leftIndex++
// skip right value which the same as previous
while (rightIndex > leftIndex && rightNum == sortedNums[rightIndex - 1]) {
rightIndex--
}
rightIndex--
} else if (-num > sum) {
leftIndex++
} else {
rightIndex--
}
}
}
return answers
}
}
fun main(args: Array<String>) {
val solution = Solution()
println(solution.threeSum(intArrayOf(-1, 0, 1, 2, -1, -4))) // -4, -1, -1, 0, 1, 2
println(solution.threeSum(intArrayOf()))
println(solution.threeSum(intArrayOf(0, 0)))
println(solution.threeSum(intArrayOf(0, 0, 0)))
println(solution.threeSum(intArrayOf(-2, 0, 1, 1, 2)))
println(solution.threeSum(intArrayOf(0, 0, 0, 0)))
println(solution.threeSum(intArrayOf(3, 0, -2, -1, 1, 2)))
println(solution.threeSum(intArrayOf(-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6)))
println(solution.threeSum(intArrayOf(1, -1, -1, 0)))
}
| 0 | Kotlin | 0 | 0 | 8f126ffdf75aa83a6d60689e0b6fcc966a173c70 | 1,823 | coding-fun | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.