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/me/anno/docs/stats/FunctionLength.kt | AntonioNoack | 686,716,019 | false | {"Kotlin": 41609, "JavaScript": 19397, "HTML": 4377, "CSS": 3451} | package me.anno.docs.stats
import me.anno.docs.Method
import me.anno.docs.Scope
import me.anno.docs.collectAll
import me.anno.utils.structures.lists.Lists.largestKElements
import me.anno.utils.types.Floats.f3
import kotlin.math.log2
fun main() {
// done set start and end length to each function
// collect all functions
collectAll()
collectMethods(Scope.all)
val buckets = IntArray(10)
for (func in functions) {
buckets[bucket(func.lines)]++
}
// print the longest functions
// finally shorten them by splitting them up
println()
println("Longest Functions:")
val largestK = functions.largestKElements(20, Comparator { p0, p1 -> p0.lines.compareTo(p1.lines) })
for ((idx, func) in largestK.withIndex()) {
println(
"${
(idx + 1).toString().padStart(2)
}. ${func.scope.combinedName}.${func.method.name}(): ${func.lines} lines"
)
}
println()
// plot the number of lines per function
val total = functions.size
println("Total: $total")
for ((idx, value) in buckets.withIndex()) {
val percentile = (0..idx).sumOf { buckets[it] }.toFloat() / total
println(
"Bucket[$idx]: ${value.toString().padStart(5)} // ${percentile.f3()} // ${
("${1.shl(idx)}+").padStart(
4
)
}"
)
}
}
class Function(val scope: Scope, val method: Method) {
val lines = method.endLine - method.startLine + 1
}
val functions = ArrayList<Function>()
fun collectMethods(scope: Scope) {
functions.addAll(scope.methods.map { Function(scope, it) })
for (child in scope.children.values) {
collectMethods(child)
}
}
fun bucket(lineCount: Int): Int {
return log2(lineCount.toDouble()).toInt()
} | 0 | Kotlin | 0 | 1 | 7e7b3635cb4dd63105bf9503957108407308729f | 1,832 | RemsDocsGenerator | Apache License 2.0 |
src/iii_conventions/MyDate.kt | agbragin | 108,394,108 | false | null | package iii_conventions
import java.time.LocalDate
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(other: MyDate): Int {
return LocalDate.of(year, month + 1, dayOfMonth).compareTo(
LocalDate.of(other.year, other.month + 1, other.dayOfMonth))
}
operator fun rangeTo(other: MyDate): DateRange {
return DateRange(this, other)
}
operator fun plus(timeInterval: TimeInterval): MyDate {
return addTimeIntervals(timeInterval, 1)
}
operator fun plus(myInterval: MyInterval): MyDate {
var updated = LocalDate.of(year, month + 1, dayOfMonth)
.plusYears(myInterval.years.toLong())
.plusMonths(myInterval.months.toLong())
.plusDays(myInterval.days.toLong())
return MyDate(updated.year, updated.month.value - 1, updated.dayOfMonth)
}
}
operator fun MyDate.compareTo(other: MyDate) : Int {
return compareTo(other)
}
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> {
override fun iterator(): Iterator<MyDate> {
return object : Iterator<MyDate> {
var current : MyDate = start
override fun hasNext(): Boolean {
return current <= endInclusive
}
override fun next(): MyDate {
val nextDate = LocalDate.of(current.year, current.month + 1, current.dayOfMonth)
.plusDays(1)
return current.let {
current = MyDate(nextDate.year, nextDate.month.value - 1, nextDate.dayOfMonth)
return it
}
}
}
}
operator fun contains(d: MyDate): Boolean {
return start <= d && d <= endInclusive
}
}
class MyInterval (val years: Int, val months: Int, val days: Int) {
operator fun plus(other: MyInterval): MyInterval {
return MyInterval(years + other.years, months + other.months, days + other.days)
}
}
fun fromInterval(timeInterval: TimeInterval): MyInterval {
return when (timeInterval) {
TimeInterval.YEAR -> MyInterval(1, 0, 0)
TimeInterval.WEEK -> MyInterval(0, 0, 7)
TimeInterval.DAY -> MyInterval(0, 0, 1)
}
}
operator fun TimeInterval.times(times: Int): MyInterval {
var total: MyInterval = MyInterval(0, 0, 0)
for (i in 0 until times) {
total += fromInterval(this)
}
return total
}
| 0 | Kotlin | 1 | 0 | 34caea48743312ed30272842b61b3d148fc6b00d | 2,568 | kotlin-koans | MIT License |
src/Day13.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | import kotlinx.serialization.json.*
import kotlinx.serialization.json.Json.Default.parseToJsonElement
sealed class Packet : Comparable<Packet> {
data class Value(val value: Int) : Packet() {
fun toList() = Container(listOf(this))
override fun compareTo(other: Packet): Int = when (other) {
is Value -> value.compareTo(other.value)
is Container -> toList().compareTo(other)
}
}
data class Container(val values: List<Packet>) : Packet() {
override fun compareTo(other: Packet): Int = when (other) {
is Value -> compareTo(other.toList())
is Container -> values.zip(other.values)
.map { (left, right) -> left.compareTo(right) }
.firstOrNull { it != 0 } ?: values.size.compareTo(other.values.size)
}
}
}
fun main() {
fun JsonElement.parse(): Packet = when (this) {
is JsonArray -> Packet.Container(this.map { it.parse() })
else -> Packet.Value(this.jsonPrimitive.int)
}
fun String.toPacket() = parseToJsonElement(this).parse()
fun List<String>.toPackets() = this
.chunked(3)
.map { (left, right) -> left.toPacket() to right.toPacket() }
fun part1(input: List<String>): Int {
return input
.toPackets()
.foldIndexed(0) { i, acc, (left, right) ->
if (left < right) {
acc + i + 1
} else {
acc
}
}
}
fun part2(input: List<String>): Int {
val dividerTop = Packet.Container(listOf(Packet.Container(listOf(Packet.Value(2)))))
val dividerBottom = Packet.Container(listOf(Packet.Container(listOf(Packet.Value(6)))))
val packets = input
.toPackets()
.flatMap { (left, right) -> listOf(left, right) }
.plus(listOf(dividerTop, dividerBottom))
.sorted()
return (packets.indexOf(dividerTop) + 1) * (packets.indexOf(dividerBottom) + 1)
}
val testInput = readInput("Day13_test")
println(part1(testInput)) // 13
println(part2(testInput)) // 140
val input = readInput("Day13")
println(part1(input)) // 5675
println(part2(input)) // 20383
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 2,264 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day03/Puzzle.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day03
import eu.janvdb.aocutil.kotlin.point2d.Point2D
val NUMBER_REGEX = Regex("\\d+")
class Puzzle(input: List<String>) {
private val numbers: List<Number>
private val symbols: List<Symbol>
init {
this.numbers = input.flatMapIndexed { y, line ->
NUMBER_REGEX.findAll(line)
.map { it.groups[0]!! }
.map {
Number(Point2D(it.range.first, y), it.range.last - it.range.first + 1, it.value.toInt())
}
}
this.symbols = input.flatMapIndexed { y, line ->
line.mapIndexed { x, c -> Symbol(Point2D(x, y), c) }
.filter { it.symbol != '.' && !it.symbol.isDigit() }
}.toList()
}
fun sumOfAdjacentNumbers(): Int {
return numbers.filter { number -> symbols.any { number.isAdjacentTo(it) } }
.sumOf { it.value }
}
fun getSumOfGearRatios(): Int {
return symbols
.filter { it.isGear() }
.map { it.getAdjacentNumbers(numbers) }
.filter { it.size == 2 }
.sumOf { it[0].value * it[1].value }
}
}
data class Number(val position: Point2D, val length: Int, val value: Int) {
fun isAdjacentTo(symbol: Symbol): Boolean {
val xMinOk = position.x - 1 <= symbol.position.x
val xMaxOk = position.x + length >= symbol.position.x
val yMinOk = position.y - 1 <= symbol.position.y
val yMaxOk = position.y + 1 >= symbol.position.y
return xMinOk && xMaxOk && yMinOk && yMaxOk
}
}
data class Symbol(val position: Point2D, val symbol: Char) {
fun isGear() = symbol == '*'
fun getAdjacentNumbers(numbers: List<Number>) = numbers.filter { it.isAdjacentTo(this) }
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 1,537 | advent-of-code | Apache License 2.0 |
src/main/java/challenges/coderbyte/SeatingStudents.kt | ShabanKamell | 342,007,920 | false | null | package challenges.coderbyte
/*
Have the function SeatingStudents(arr) read the array of integers stored in arr which will be in the
following format: [K, r1, r2, r3, ...] where K represents the number of desks in a classroom,
and the rest of the integers in the array will be in sorted order and will represent the desks
that are already occupied. All of the desks will be arranged in 2 columns,
where desk #1 is at the top left, desk #2 is at the top right, desk #3 is below #1, desk #4 is below #2, etc.
Your program should return the number of ways 2 students can be seated next to each other.
This means 1 student is on the left and 1 student on the right, or 1 student is directly above or below the other student.
For example: if arr is [12, 2, 6, 7, 11] then this classrooms looks like the following diagram:
1 (2)
3 4
5 (6)
(7) 8
9 10
(11) 12
Based on above arrangement of occupied desks, there are a total of 6 ways ([1,3][3,4][3,5][8,10][9,10][10,12])
to seat 2 new students next to each other. The combinations are: [1, 3], [3, 4], [3, 5], [8, 10], [9, 10], [10, 12].
So for this input your program should return 6. K will range from 2 to 24 and will always be an even number.
After K, the number of occupied desks in the array can range from 0 to K.
Sample Test Cases
Input:6, 4
Output:4
Input:8, 1, 8
Output:6
*/
object SeatingStudents {
/*
Solution Steps:
1- Fill all occupied sets with 1, empty with 0
2- Increase count if behind/beside seats found
*/
fun seatingStudents(arr: Array<Int>): Int {
val k = arr[0]
val seats = createSeats(arr)
var count = 0
count += pairsBeside(seats, k)
count += pairsBehind(seats, k)
return count
}
private fun createSeats(arr: Array<Int>): Array<IntArray> {
val k = arr[0]
val seats = Array(k / 2) { IntArray(2) }
var index = 1
for (i in 0 until k / 2) {
for (j in 0..1) {
if (index < arr.size && arr[index] == i * 2 + j + 1) {
seats[i][j] = 1
index++
}
}
}
return seats
}
private fun pairsBeside(seats: Array<IntArray>, k: Int): Int {
var count = 0
for (i in 0 until k / 2) {
if (seats[i][0] == 0 && seats[i][1] == 0) {
count++
}
}
return count
}
private fun pairsBehind(seats: Array<IntArray>, k: Int): Int {
var count = 0
for (j in 0..1) {
for (i in 0 until k / 2 - 1) {
if (seats[i][j] == 0 && seats[i + 1][j] == 0) {
count++
}
}
}
return count
}
@JvmStatic
fun main(args: Array<String>) {
val input = arrayOf(6, 4)
val input2 = arrayOf(8, 1, 8)
println(seatingStudents(input))
println(seatingStudents(input2))
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,965 | CodingChallenges | Apache License 2.0 |
src/day09/Day09.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | package day09
import readInput
import java.lang.Math.abs
data class Position(var x: Int, var y: Int) {
fun move(deltaX: Int, deltaY: Int) {
x += deltaX
y += deltaY
}
fun follow(position: Position): Boolean {
var moved = false
val dx = position.x - x
val dy = position.y - y
val diagonal = (abs(dx) + abs(dy) > 2)
/*
if (diagonal) {
print("Diagonal ")
}
*/
if (abs(dx) > 1 || diagonal) {
x += abs(dx) / dx
moved = true
}
if (abs(dy) > 1 || diagonal) {
y += abs(dy) / dy
moved = true
}
return moved
}
}
data class Move(val move: String) {
var deltaX = 0
var deltaY = 0
var steps = 0
init {
val parsedMove = move.split(" ")
steps = parsedMove[1].toInt()
when(parsedMove[0]) {
"R" -> deltaX = 1
"L" -> deltaX = -1
"U" -> deltaY = -1
"D" -> deltaY = 1
else -> throw Exception("Unexpected move direction")
}
}
}
fun main() {
fun part1(input: List<String>): Int {
var headPosition = Position(0, 0)
var tailPosition = Position(0, 0)
var tailVisits = mutableSetOf(tailPosition.copy())
for (moveString in input) {
val move = Move(moveString)
//println("day09.Move: ${moveString}")
var stepsRemaining = move.steps
while(stepsRemaining > 0) {
headPosition.move(move.deltaX, move.deltaY)
//println("Head moved to ${headPosition.x}, ${headPosition.y}")
if (tailPosition.follow(headPosition)) {
//println("Tail moved to ${tailPosition.x}, ${tailPosition.y}")
tailVisits.add(tailPosition.copy())
}
stepsRemaining -= 1
}
}
return tailVisits.size
}
fun part2(input: List<String>): Int {
val knotCount = 10
var knotPositions = MutableList(knotCount) { Position(0, 0) }
var tailVisits = mutableSetOf(knotPositions[knotCount-1].copy())
for (moveString in input) {
val move = Move(moveString)
//println("day09.Move: ${moveString}")
var stepsRemaining = move.steps
while(stepsRemaining > 0) {
knotPositions[0].move(move.deltaX, move.deltaY)
//println("Head moved to ${knotPositions[0].x}, ${knotPositions[0].y}")
for (i in IntRange(1, knotCount-1)) {
knotPositions[i].follow(knotPositions[i - 1])
}
tailVisits.add(knotPositions[knotCount-1].copy())
stepsRemaining -= 1
}
}
return tailVisits.size
}
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
val test2Input = readInput("Day09_test2")
check(part1(test2Input) == 8)
val testPart2Input = readInput("Day09_part2_test")
check(part2(testPart2Input) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 3,209 | AdventOfCode2022 | Apache License 2.0 |
src/Day20.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | fun main() {
fun part1(input: List<String>): Int {
var v = mutableListOf<Pair<Int, Int>>()
for (i in input.indices) {
var line = input[i]
v.add(Pair(line.toInt(), i))
}
var n = v.size
for (ite in 0 until v.size) {
var ini = 0
for (i in v.indices) {
if (v[i].second == ite) {
ini = i
break
}
}
val steps = v[ini].first
for (st in 0 until kotlin.math.abs(steps)) {
var nxt = (ini + 1) % n
if (steps < 0) nxt = (ini - 1 + n) % n
var tmp = Pair(v[ini].first, v[ini].second)
v[ini] = Pair(v[nxt].first, v[nxt].second)
v[nxt] = tmp
ini = nxt
}
}
var zeroPos = 0
for (i in v.indices) {
if (v[i].first == 0) {
zeroPos = i
break
}
}
return v[(zeroPos+1000)%n].first + v[(zeroPos+2000)%n].first + v[(zeroPos+3000)%n].first
}
fun part2(input: List<String>): Long {
val key: Long = 811589153
var v = mutableListOf<Pair<Int, Int>>()
for (i in input.indices) {
var line = input[i]
if (line.isEmpty()) continue
v.add(Pair(line.toInt(), i))
}
var n = v.size
for (mixing in 1 .. 10) {
for (ite in 0 until v.size) {
var ini = 0
for (i in v.indices) {
if (v[i].second == ite) {
ini = i
break
}
}
var steps = (kotlin.math.abs(v[ini].first.toLong()) * key) % (n-1)
if (v[ini].first < 0) steps *= -1
for (st in 0 until kotlin.math.abs(steps)) {
var nxt = (ini + 1) % n
if (steps < 0) nxt = (ini - 1 + n) % n
var tmp = Pair(v[ini].first, v[ini].second)
v[ini] = Pair(v[nxt].first, v[nxt].second)
v[nxt] = tmp
ini = nxt
}
}
}
var zeroPos = 0
for (i in v.indices) {
if (v[i].first == 0) {
zeroPos = i
break
}
}
return (v[(zeroPos+1000)%n].first + v[(zeroPos+2000)%n].first + v[(zeroPos+3000)%n].first) * key
}
val input = readInput("Day20")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 2,618 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day22.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.math.max
import kotlin.math.min
import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
val pathDescription = parsePathDescription(input.last())
val board = Board.parse(input.dropLast(2))
return board.getPassword(pathDescription)
}
fun part2(input: List<String>): Int {
val pathDescription = parsePathDescription(input.last())
val cube = CubeMap.parse(input.dropLast(2))
return cube.getPassword(pathDescription)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day22_test")
assertEquals(6032, part1(testInput))
assertEquals(5031, part2(testInput))
val input = readInput("Day22")
println(part1(input))
println(part2(input))
}
class CubeMap(val regions: Map<Int, MapRegion>) {
fun getPassword(pathDescription: List<String>): Int {
var currentPosition = Position2(1, 0, 0, RIGHT)
for (description in pathDescription) {
currentPosition =
if (description in listOf("L", "R")) {
currentPosition.turn(description)
} else {
val numMoves = description.toInt()
currentPosition.move(numMoves, this)
}
}
return 1000 *
(currentPosition.rowIndex + regions[currentPosition.regionNumber]!!.rowOffset + 1) +
4 * (currentPosition.columnIndex + regions[currentPosition.regionNumber]!!.colOffset + 1) +
currentPosition.facing
}
companion object {
fun parse(input: List<String>): CubeMap {
val numColumns = input.maxOf { it.length }
val input = input.map { it.padEnd(numColumns, ' ') }
val minMapWidth = input.minOf { row -> row.count { it != ' ' } }
val minMapHeight =
(0 until numColumns).minOf { colIndex -> input.count { it[colIndex] != ' ' } }
val cubeSize = min(minMapWidth, minMapHeight)
val isValidMapRegion: Array<Array<Boolean>> =
Array(input.size / cubeSize) { regionRowIndex ->
Array(numColumns / cubeSize) { regionColumnIndex ->
val rowIndex = regionRowIndex * cubeSize
val columnIndex = regionColumnIndex * cubeSize
input[rowIndex][columnIndex] != ' '
}
}
val faceRegionMapping: Array<Array<CubeFace?>> =
Array(input.size / cubeSize) { Array(numColumns / cubeSize) { null } }
faceRegionMapping[0][isValidMapRegion[0].indexOf(true)] =
CubeFace(1, DiceUtils.diceEdges[1]!!)
repeat(5) {
for (i in faceRegionMapping.indices) {
for (j in faceRegionMapping[i].indices) {
if (faceRegionMapping[i][j] != null) {
// right
if (j < faceRegionMapping[i].lastIndex &&
isValidMapRegion[i][j + 1] &&
faceRegionMapping[i][j + 1] == null) {
faceRegionMapping[i][j + 1] = faceRegionMapping[i][j]!!.face(RIGHT)
}
// left
if (j > 0 && isValidMapRegion[i][j - 1] && faceRegionMapping[i][j - 1] == null) {
faceRegionMapping[i][j - 1] = faceRegionMapping[i][j]!!.face(LEFT)
}
// down
if (i < faceRegionMapping.lastIndex &&
isValidMapRegion[i + 1][j] &&
faceRegionMapping[i + 1][j] == null) {
faceRegionMapping[i + 1][j] = faceRegionMapping[i][j]!!.face(DOWN)
}
// up
if (i > 0 && isValidMapRegion[i - 1][j] && faceRegionMapping[i - 1][j] == null) {
faceRegionMapping[i - 1][j] = faceRegionMapping[i][j]!!.face(UP)
}
}
}
}
}
// println(
// faceRegionMapping.joinToString("\n") {
// it.joinToString("") { if (it == null) " " else it.number.toString() }
// })
val regions =
faceRegionMapping
.mapIndexed { rowIndex, cubeFaces ->
cubeFaces
.mapIndexed { colIndex, cubeFace ->
cubeFace?.let { cubeFace ->
MapRegion(
cubeFace.number,
rowIndex * cubeSize,
colIndex * cubeSize,
input
.slice(rowIndex * cubeSize until rowIndex * cubeSize + cubeSize)
.map {
it.slice(colIndex * cubeSize until colIndex * cubeSize + cubeSize)
},
mapOf(
RIGHT to
{
val newRegion = cubeFace.faceNumber(RIGHT)
val nextFace =
faceRegionMapping.flatten().filterNotNull().first {
it.number == newRegion
}
val turnAmount = cubeFace.turnAmount(RIGHT, nextFace)
val newFacing = (it.facing + turnAmount).mod(4)
when (turnAmount) {
3 ->
Position2(
newRegion, it.columnIndex, it.rowIndex, newFacing)
0 -> Position2(newRegion, it.rowIndex, 0, newFacing)
1 ->
Position2(
newRegion, 0, cubeSize - 1 - it.rowIndex, newFacing)
2 ->
Position2(
newRegion,
cubeSize - 1 - it.rowIndex,
it.columnIndex,
newFacing)
else -> error("should not happen: $turnAmount")
}
},
LEFT to
{
val newRegion = cubeFace.faceNumber(LEFT)
val nextFace =
faceRegionMapping.flatten().filterNotNull().first {
it.number == newRegion
}
val turnAmount = cubeFace.turnAmount(LEFT, nextFace)
val newFacing = (it.facing + turnAmount).mod(4)
when (turnAmount) {
1 ->
Position2(
newRegion,
cubeSize - 1,
cubeSize - 1 - it.rowIndex,
newFacing)
0 ->
Position2(
newRegion, it.rowIndex, cubeSize - 1, newFacing)
3 ->
Position2(
newRegion, it.columnIndex, it.rowIndex, newFacing)
2 ->
Position2(
newRegion,
cubeSize - 1 - it.rowIndex,
it.columnIndex,
newFacing)
else -> error("should not happen")
}
},
DOWN to
{
val newRegion = cubeFace.faceNumber(DOWN)
val nextFace =
faceRegionMapping.flatten().filterNotNull().first { c ->
c.number == newRegion
}
val turnAmount = cubeFace.turnAmount(DOWN, nextFace)
val newFacing = (it.facing + turnAmount).mod(4)
when (turnAmount) {
1 ->
Position2(
newRegion, it.columnIndex, it.rowIndex, newFacing)
0 -> Position2(newRegion, 0, it.columnIndex, newFacing)
3 ->
Position2(
newRegion,
cubeSize - 1 - it.columnIndex,
0,
newFacing)
2 ->
Position2(
newRegion,
it.rowIndex,
cubeSize - 1 - it.columnIndex,
newFacing)
else -> error("should not happen")
}
},
UP to
{
val newRegion = cubeFace.faceNumber(UP)
val nextFace =
faceRegionMapping.flatten().filterNotNull().first {
it.number == newRegion
}
val turnAmount = cubeFace.turnAmount(UP, nextFace)
val newFacing = (it.facing + turnAmount).mod(4)
when (turnAmount) {
1 ->
Position2(
newRegion, it.columnIndex, it.rowIndex, newFacing)
0 ->
Position2(
newRegion, cubeSize - 1, it.columnIndex, newFacing)
3 ->
Position2(
newRegion,
cubeSize - 1,
cubeSize - 1 - it.rowIndex,
newFacing)
2 ->
Position2(
newRegion,
it.rowIndex,
cubeSize - 1 - it.columnIndex,
newFacing)
else -> error("should not happen")
}
},
),
)
}
}
.filterNotNull()
}
.flatten()
//println(regions.joinToString("\n"))
return CubeMap(regions.associateBy { it.number })
}
}
}
class MapRegion(
val number: Int,
val rowOffset: Int,
val colOffset: Int,
val tiles: List<String>,
val wrappingRules: Map<Direction, WrappingRule>,
) {
override fun toString() = "Region $number:\n${tiles.joinToString("\n")}"
}
typealias WrappingRule = (currentPosition: Position2) -> Position2
typealias Direction = Int
const val RIGHT = 0
const val DOWN = 1
const val LEFT = 2
const val UP = 3
data class Position2(
val regionNumber: Int,
val rowIndex: Int,
val columnIndex: Int,
val facing: Direction,
) {
fun turn(input: String): Position2 {
val newFacing =
if (input == "R") {
(facing + 1).mod(4)
} else {
(facing - 1).mod(4)
}
return copy(facing = newFacing)
}
fun move(amount: Int, map: CubeMap): Position2 {
var currentPosition = this
for (i in 1..amount) {
val nextPosition = currentPosition.nextPosition(map)
if (nextPosition.isInvalid(map)) break
currentPosition = nextPosition
}
return currentPosition
}
private fun isInvalid(map: CubeMap) =
map.regions[regionNumber]!!.tiles[rowIndex][columnIndex] == '#'
private fun nextPosition(map: CubeMap): Position2 {
val currentRegion = map.regions[regionNumber]!!
return when (facing) {
RIGHT -> {
val shouldWrap = columnIndex == currentRegion.tiles[rowIndex].lastIndex
if (shouldWrap) {
currentRegion.wrappingRules[RIGHT]!!.invoke(this)
} else {
copy(columnIndex = columnIndex + 1)
}
}
DOWN -> {
val shouldWrap = rowIndex == currentRegion.tiles.lastIndex
if (shouldWrap) {
currentRegion.wrappingRules[DOWN]!!.invoke(this)
} else {
copy(rowIndex = rowIndex + 1)
}
}
LEFT -> {
val shouldWrap = columnIndex == 0
if (shouldWrap) {
currentRegion.wrappingRules[LEFT]!!.invoke(this)
} else {
copy(columnIndex = columnIndex - 1)
}
}
UP -> {
val shouldWrap = rowIndex == 0
if (shouldWrap) {
currentRegion.wrappingRules[UP]!!.invoke(this)
} else {
copy(rowIndex = rowIndex - 1)
}
}
else -> error("should not happen")
}
}
}
/** Represents cube face on the map, edges are ordered: right,bottom,left,top */
class CubeFace(
val number: Int,
val edges: List<CubeEdge>,
) {
fun faceNumber(direction: Int): Int = edges[direction].faceNumbers.first { it != number }
fun face(direction: Int): CubeFace {
val faceNumber = faceNumber(direction)
return CubeFace(
faceNumber,
DiceUtils.getEdges(
faceNumber,
CubeEdge(faceNumber, number),
direction.opposite(),
),
)
}
fun turnAmount(direction: Int, nextFace: CubeFace): Int {
val connectingEdge = CubeEdge(number, nextFace.number)
assertEquals(
direction, edges.indexOf(connectingEdge), "edges are: $edges, did not find $connectingEdge")
return (nextFace.edges.indexOf(connectingEdge) - edges.indexOf(connectingEdge).opposite()).mod(
4)
}
override fun toString(): String {
return "Face: $number, ${edges.map { it.faceNumbers.first { it != number } }}"
}
}
object DiceUtils {
/** face number to edge mapping of a dice. edges are ordered clockwise. */
val diceEdges =
mapOf(
1 to listOf(CubeEdge(1, 3), CubeEdge(1, 2), CubeEdge(1, 4), CubeEdge(1, 5)),
2 to listOf(CubeEdge(2, 3), CubeEdge(2, 6), CubeEdge(2, 4), CubeEdge(1, 2)),
3 to listOf(CubeEdge(3, 5), CubeEdge(3, 6), CubeEdge(2, 3), CubeEdge(1, 3)),
4 to listOf(CubeEdge(2, 4), CubeEdge(4, 6), CubeEdge(4, 5), CubeEdge(1, 4)),
5 to listOf(CubeEdge(3, 5), CubeEdge(1, 5), CubeEdge(4, 5), CubeEdge(5, 6)),
6 to listOf(CubeEdge(3, 6), CubeEdge(5, 6), CubeEdge(4, 6), CubeEdge(2, 6)),
)
/** Returns edges of a dice in clockwise order given its face number */
fun getEdges(faceNumber: Int, with: CubeEdge, atIndex: Int): List<CubeEdge> {
val edges = diceEdges[faceNumber]!!
val indexOfFirstEdge = (edges.indexOf(with) - atIndex).mod(4)
return edges.slice(indexOfFirstEdge..edges.lastIndex) + edges.slice(0 until indexOfFirstEdge)
}
}
fun Int.opposite(): Int = (this + 2).mod(4)
/** Represents an edge of a cube, the two face numbers correspond the faces this edge connects */
data class CubeEdge(val num1: Int, val num2: Int) {
val faceNumbers = setOf(num1, num2)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is CubeEdge) return false
if (min(num1, num2) != min(other.num1, other.num2)) return false
if (max(num1, num2) != max(other.num1, other.num2)) return false
return true
}
override fun hashCode(): Int {
var result = min(num1, num2)
result = 31 * result + max(num1, num2)
return result
}
override fun toString(): String {
return "CubeEdge(${min(num1, num2)}, ${max(num1, num2)})"
}
}
class Board(
val map: Array<CharArray>,
private val rowRangeByColumnIndex: List<IntRange>,
private val columnRangeByRowIndex: List<IntRange>
) {
private var currentPosition = Position(0, columnRangeByRowIndex[0].first)
fun getPassword(pathDescription: List<String>): Int {
for (description in pathDescription) {
if (description in listOf("L", "R")) {
currentPosition = currentPosition.turn(description)
} else {
val numMoves = description.toInt()
when (currentPosition.facing) {
RIGHT -> {
for (i in 1..numMoves) {
var nextColumnIndex = (currentPosition.columnIndex + 1)
if (nextColumnIndex > columnRangeByRowIndex[currentPosition.rowIndex].last) {
nextColumnIndex = columnRangeByRowIndex[currentPosition.rowIndex].first
}
if (map[currentPosition.rowIndex][nextColumnIndex] == '#') break
currentPosition = currentPosition.copy(columnIndex = nextColumnIndex)
}
}
DOWN -> {
for (i in 1..numMoves) {
var nextRowIndex = (currentPosition.rowIndex + 1)
if (nextRowIndex > rowRangeByColumnIndex[currentPosition.columnIndex].last) {
nextRowIndex = rowRangeByColumnIndex[currentPosition.columnIndex].first
}
if (map[nextRowIndex][currentPosition.columnIndex] == '#') break
currentPosition = currentPosition.copy(rowIndex = nextRowIndex)
}
}
LEFT -> {
for (i in 1..numMoves) {
var nextColumnIndex = (currentPosition.columnIndex - 1)
if (nextColumnIndex < columnRangeByRowIndex[currentPosition.rowIndex].first) {
nextColumnIndex = columnRangeByRowIndex[currentPosition.rowIndex].last
}
if (map[currentPosition.rowIndex][nextColumnIndex] == '#') break
currentPosition = currentPosition.copy(columnIndex = nextColumnIndex)
}
}
UP -> {
for (i in 1..numMoves) {
var nextRowIndex = (currentPosition.rowIndex - 1)
if (nextRowIndex < rowRangeByColumnIndex[currentPosition.columnIndex].first) {
nextRowIndex = rowRangeByColumnIndex[currentPosition.columnIndex].last
}
if (map[nextRowIndex][currentPosition.columnIndex] == '#') break
currentPosition = currentPosition.copy(rowIndex = nextRowIndex)
}
}
}
}
}
return 1000 * (currentPosition.rowIndex + 1) +
4 * (currentPosition.columnIndex + 1) +
currentPosition.facing
}
companion object {
fun parse(input: List<String>): Board {
val rowCount = input.size
val rowSize = input.maxOf { it.length }
val rowRangeByColumnIndex =
(0 until rowSize).map { colIndex ->
IntRange(
input.indexOfFirst { it.padEnd(rowSize, ' ')[colIndex] != ' ' },
input.indexOfLast { it.padEnd(rowSize, ' ')[colIndex] != ' ' },
)
}
val columnRangeByRowIndex =
input.map { row ->
IntRange(
row.indexOfFirst { it != ' ' },
row.indexOfLast { it != ' ' },
)
}
val map = Array(rowCount) { CharArray(rowSize) { ' ' } }
for (rowIndex in 0 until rowCount) {
for (columnIndex in columnRangeByRowIndex[rowIndex]) {
map[rowIndex][columnIndex] = input[rowIndex][columnIndex]
}
}
return Board(map, rowRangeByColumnIndex, columnRangeByRowIndex)
}
}
override fun toString() = map.joinToString("\n") { it.joinToString("") }
}
fun parsePathDescription(input: String): List<String> {
val movements = input.split(Regex("[LR]"))
val turns = input.split(Regex("\\d+")).drop(1).dropLast(1)
return movements.zip(turns).flatMap { it.toList() } + movements.last()
}
data class Position(val rowIndex: Int, val columnIndex: Int, val facing: Int = RIGHT) {
fun turn(input: String): Position {
val newFacing =
if (input == "R") {
(facing + 1).mod(4)
} else {
(facing - 1).mod(4)
}
return copy(facing = newFacing)
}
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 21,612 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day10/Day10.kt | afTrolle | 572,960,379 | false | {"Kotlin": 33530} | package day10
import Day
fun main() {
Day10("Day10").solve()
}
class Day10(input: String) : Day<List<Int>>(input) {
override fun parseInput(): List<Int> {
return inputByLines.map {
val (a, b) = (it.split(" ") + " ")
a to b.toIntOrNull()
}.flatMap { (action, num) ->
when (action) {
"noop" -> listOf(0)
else -> listOf(0, num!!)
}
}
}
override fun part1(input: List<Int>): Any? {
val register =
input.runningFold(1) { acc: Int, i: Int ->
acc + i
}
return listOf(20, 60, 100, 140, 180, 220).map {
register[it - 1] * it
}.sumOf { it }
}
override fun part2(input: List<Int>): String {
val width = 40
val spritePos: List<Pair<Int, Boolean>> =
input.runningFoldIndexed(1 to false) { index: Int, (acc: Int, _: Boolean), i: Int ->
val crt = index % width
val spirePosition = acc + i
val sprite = (acc - 1)..(acc + 1)
spirePosition to sprite.contains(crt)
}.drop(1)
return "\n" + spritePos.map { it.second }.chunked(width)
.joinToString(System.lineSeparator()) { line ->
line.joinToString("") { if (it) "#" else "." }
}
}
}
| 0 | Kotlin | 0 | 0 | 4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545 | 1,381 | aoc-2022 | Apache License 2.0 |
kotlin/src/Wardrobe/sal/SalWardrobe.kt | intresrl | 457,786,766 | false | {"Kotlin": 23396, "Java": 13383, "Python": 8693, "JavaScript": 7499, "Common Lisp": 1566, "TypeScript": 861} | package wardrobe.sal
typealias Width = Int
typealias Price = Int
fun combinations(
goal: Width = 250,
availableSizes: List<Width> = listOf(50, 75, 100, 120)
): Set<List<Width>> =
if (goal == 0)
setOf(emptyList())
else
availableSizes
.filter { it <= goal }
.flatMap { width ->
val rest = goal - width
val partial = combinations(rest, availableSizes)
partial.map { it + width }
}
.map { it.sorted() }
.toSet()
fun Collection<List<Width>>.cheapest(
costs: Map<Width, Price>
): Pair<List<Width>, Price> =
map { it to (it priced costs) }
.minByOrNull { (_, cost) -> cost }!!
private infix fun List<Width>.priced(costs: Map<Width, Price>) =
sumOf { costs[it] ?: throw IllegalArgumentException("Invalid cost $it") }
fun main() {
val ikea = combinations()
ikea
.toList()
.sortedByDescending { it.maxOf { list -> list } }
.sortedByDescending { it.size }
.forEachIndexed { i, list ->
println("#${(i + 1).toString().padStart(3)}: $list")
}
val costs = mapOf(50 to 59, 75 to 62, 100 to 90, 120 to 111)
val (best, price) = ikea.cheapest(costs)
println("The cheapest combinations costs $price USD: $best")
}
| 0 | Kotlin | 0 | 1 | 05310869bbc37ae3b2edab3d62c9a9e49a785592 | 1,333 | kata-pulta | MIT License |
src/main/kotlin/Day10.kt | maldoinc | 726,264,110 | false | {"Kotlin": 14472} | import java.util.*
import kotlin.io.path.Path
import kotlin.io.path.readLines
data class Coordinate(val y: Int, val x: Int)
typealias Maze = List<String>
fun Maze.isValidCoordinate(coordinate: Coordinate): Boolean =
coordinate.y in this.indices && coordinate.x in this[coordinate.y].indices
fun getStartingCoordinates(maze: Maze): Pair<Int, Int> =
maze
.withIndex()
.filter { it.value.contains('S') }
.map { it.index to it.value.indexOf('S') }
.first()
fun getPart1(start: Coordinate, maze: Maze): Int {
val up = Coordinate(-1, 0)
val down = Coordinate(1, 0)
val left = Coordinate(0, -1)
val right = Coordinate(0, 1)
val navigation = mapOf(
'|' to setOf(up, down),
'-' to setOf(left, right),
'F' to setOf(down, right),
'7' to setOf(down, left),
'J' to setOf(up, left),
'L' to setOf(up, right),
// getStartCoordNeighbors
// Manually updated for current input. It's 23:55 and I want to sleep
'S' to setOf(left, down)
).withDefault { setOf() }
val costs: MutableMap<Coordinate, Int> = mutableMapOf()
val queue: Queue<Pair<Coordinate, Int>> = PriorityQueue(compareBy { it.second })
queue.add(start to 0)
while (queue.isNotEmpty()) {
val current = queue.poll()
val currentCoords = current.first
val steps = current.second
maze[currentCoords.y][currentCoords.x].let { char ->
navigation.getValue(char).let { offsets ->
offsets.forEach { offset ->
val nextCoord = Coordinate(currentCoords.y + offset.y, currentCoords.x + offset.x)
val newSteps = steps + 1
if (maze.isValidCoordinate(nextCoord) && costs.getOrDefault(nextCoord, Int.MAX_VALUE) > newSteps) {
queue.add(Pair(nextCoord, newSteps))
costs[nextCoord] = newSteps
}
}
}
}
}
return costs.values.max()
}
fun main(args: Array<String>) {
val maze = Path(args.first()).readLines()
val startingCoords = getStartingCoordinates(maze)
println(getPart1(Coordinate(startingCoords.first, startingCoords.second), maze))
}
| 0 | Kotlin | 0 | 1 | 47a1ab8185eb6cf16bc012f20af28a4a3fef2f47 | 2,268 | advent-2023 | MIT License |
src/main/kotlin/day3.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.Input
import shared.Point
import shared.XYMap
fun main() {
val input = Input.day(3)
println(day3A(input))
println(day3B(input))
}
fun day3A(input: Input): Int {
val map = XYMap(input) { if (it == '.') null else it }
val partNumbers = findPartNumbers(input)
return partNumbers
.filter { partNumber ->
partNumber.points.any { p -> map.adjacents(p, true) { !it.isDigit() }.isNotEmpty() }
}
.sumOf { it.value }
}
fun day3B(input: Input): Int {
val map = XYMap(input) { if (it == '.') null else it }
val partNumbers = findPartNumbers(input)
val gearPartPairs = map.all { it == '*' }.map { p ->
val adjacents = map.adjacents(p.key, true).keys
partNumbers.filter { it.points.intersect(adjacents).isNotEmpty() }
}.filter { it.size == 2 }
return gearPartPairs.sumOf { it[0].value * it[1].value }
}
private fun findPartNumbers(input: Input): List<PartNumber> {
return input.lines.flatMapIndexed { y, line ->
Regex("""\d+""").findAll(line).map { match ->
PartNumber(match.value.toInt(), match.range.map { Point(it, y) })
}
}
}
class PartNumber(val value: Int, val points: List<Point>) | 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 1,224 | AdventOfCode2023 | MIT License |
src/day04/Day04.kt | emartynov | 572,129,354 | false | {"Kotlin": 11347} | package day04
import readInput
fun main() {
fun List<String>.toRangeSets() = map { pair ->
pair.split(",")
.map { pairString ->
pairString.split("-")
.map { it.toUInt() }
}
}.map { pairRangeString ->
pairRangeString.map { indexValues ->
UIntRange(indexValues[0], indexValues[1]).toSet()
}
}
fun part1(input: List<String>): Int {
return input.toRangeSets().map { pairRange ->
val intersect = pairRange[0].intersect(pairRange[1])
if (intersect == pairRange[1] || intersect == pairRange[0]) 1 else 0
}.sum()
}
fun part2(input: List<String>): Int {
return input.toRangeSets().map { pairRange ->
val intersect = pairRange[0].intersect(pairRange[1])
if (intersect.isEmpty()) 0 else 1
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day04/Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("day04/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 8f3598cf29948fbf55feda585f613591c1ea4b42 | 1,183 | advent-of-code-2022 | Apache License 2.0 |
aoc-day4/src/Day4.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import java.io.File
import java.text.NumberFormat
object Day4 {
const val BOARD_SIZE = 5
val NUMBER_PARSER: NumberFormat = NumberFormat.getIntegerInstance()
}
fun main() {
val file = File("input")
val input = file.readLines()
val numbers: List<Int>
val boards: List<Board>
input.iterator().also { it ->
numbers = readNumbers(it.next())
it.next() // Skip blank line
boards = readBoards(it)
}
boards.forEach {
println(it)
}
println("Final score from part 1: " + part1(numbers, boards))
println("Final score from part 2: " + part2(numbers, boards))
}
fun part1(numbers: List<Int>, boards: List<Board>): Int {
numbers.forEach { num ->
// Match first, then score
boards.forEach { it.match(num) }
val matched = boards.filter { it.isMatched() }
if (matched.isNotEmpty()) {
return num * matched.maxOf { it.score() }
}
}
return 0
}
fun part2(numbers: List<Int>, boards: List<Board>): Int? {
var remainingBoards: List<Board> = ArrayList(boards)
val scores = ArrayList<Int>()
numbers.forEach { num ->
// Match first, then score
remainingBoards.forEach { it.match(num) }
val matched = remainingBoards.filter { it.isMatched() }
if (matched.isNotEmpty()) {
remainingBoards = remainingBoards.filterNot { it.isMatched() }
scores.addAll(matched.map { it.score() * num })
}
}
return scores.last()
}
fun readBoards(iterator: Iterator<String>): List<Board> {
val boards = ArrayList<Board>()
while (iterator.hasNext()) {
boards.add(Board.read(iterator))
if (iterator.hasNext()) {
// Skip blank line
iterator.next()
}
}
return boards
}
fun readNumbers(line: String): List<Int> = line.split(",").map {
Day4.NUMBER_PARSER.parse(it).toInt()
} | 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 1,920 | adventofcode2021 | MIT License |
src/main/kotlin/day25/Day25.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day25
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day25/Day25.txt")
val answer = solve(data)
println("🎄 Day 25 🎄")
println("Answer: $answer")
}
private data class Area(
val width: Int,
val height: Int,
val cells: List<Char>,
)
private fun Area.getIndex(x: Int, y: Int): Int {
val xi = if (x >= width) {
x - width
} else if (x < 0) {
x + width
} else {
x
}
val yi = if (y >= height) {
y - height
} else if (y < 0) {
y + height
} else {
y
}
return yi * width + xi
}
private fun parse(path: String): Area =
File(path)
.readLines()
.let { lines ->
val height = lines.size
val width = lines[0].length
val cells = lines.flatMap(String::toList)
Area(width, height, cells)
}
private fun move(area: Area, herd: Char): Area {
val dx = if (herd == '>') 1 else 0
val dy = if (herd == '>') 0 else 1
val prev = area.cells
val next = prev.toMutableList()
for (y in 0 until area.height) {
for (x in 0 until area.width) {
val index = area.getIndex(x, y)
if (prev[index] == herd) {
val nextIndex = area.getIndex(x + dx, y + dy)
if (prev[nextIndex] == '.') {
next[nextIndex] = herd
next[index] = '.'
}
}
}
}
return area.copy(cells = next)
}
private fun step(previous: Area): Area {
return move(move(previous, '>'), 'v')
}
private fun solve(area: Area): Int {
return 1 + generateSequence(area) { step(it) }
.zipWithNext()
.indexOfFirst { (a1, a2) -> a1 == a2 }
}
| 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 1,776 | advent-of-code-2021 | MIT License |
src/main/kotlin/days/Day4.kt | jgrgt | 433,952,606 | false | {"Kotlin": 113705} | package days
class Day4 : Day(4) {
override fun partOne(): Any {
return p1(inputList)
}
fun p1(lines: List<String>): Any {
val numbers = lines[0].split(",").map { it.toInt() }
val boards = lines.drop(1).windowed(6, 6).map {
Board.fromLines(it.drop(1))
}.toMutableList()
val bingo = Bingo(boards)
val (number, winningBoard) = bingo.registerNumbers(numbers)
return number * winningBoard.positiveNumber().sum()
}
override fun partTwo(): Any {
return p2(inputList)
}
fun p2(lines: List<String>): Any {
val numbers = lines[0].split(",").map { it.toInt() }
val boards = lines.drop(1).windowed(6, 6).map {
Board.fromLines(it.drop(1))
}.toMutableList()
val bingo = Bingo(boards)
val (number, winningBoard) = bingo.registerNumbersUntilLastBoard(numbers)
return number * winningBoard.positiveNumber().sum()
}
}
data class Bingo(val boards: MutableList<Board>) {
fun registerNumbers(numbers: List<Int>): Pair<Int, Board> {
for (number in numbers) {
registerNumber(number)
val winningBoard = findWinningBoard()
if (winningBoard != null) {
return number to winningBoard
}
}
error("no winner...")
}
// This should be some strategy
fun registerNumbersUntilLastBoard(numbers: List<Int>): Pair<Int, Board> {
for (number in numbers) {
registerNumber(number)
val winningBoards = findWinningBoards()
if (winningBoards.isNotEmpty()) {
if (boards.size == 1) {
return number to winningBoards[0]
} else {
boards.removeAll(winningBoards)
}
}
}
boards.forEach { it.print() }
error("no winner... ${boards.size} boards left")
}
private fun findWinningBoard(): Board? {
return boards.find { it.isWinner() }
}
private fun findWinningBoards(): List<Board> {
return boards.filter{ it.isWinner() }
}
private fun registerNumber(number: Int) {
boards.forEach { it.registerNumber(number) }
}
}
class Board(val matrix: MutableList<MutableList<Int>>) {
fun registerNumber(number: Int) {
matrix.forEach { row ->
row.replaceAll { n ->
if (n == number) {
-1
} else {
n
}
}
}
}
fun isWinner(): Boolean {
return hasFullRow() || hasFullColumn()
}
private fun hasFullColumn(): Boolean {
val rowSize = matrix[0].size
val colSize = matrix.size
return (0 until colSize).any { colIndex ->
(0 until rowSize).all { rowIndex -> matrix[rowIndex][colIndex] < 0 }
}
}
private fun hasFullRow(): Boolean {
return matrix.any { row -> row.all { e -> e < 0 } }
}
fun positiveNumber(): List<Int> {
return matrix.flatMap { row ->
row.filter { it > 0 }
}
}
fun print() {
println("Board:")
matrix.forEach { row ->
println("%02d %02d %02d %02d %02d".format(row[0], row[1], row[2], row[3], row[4]))
}
}
init {
check(matrix.size == 5)
check(matrix[0].size == 5)
}
companion object {
fun fromLines(lines: List<String>): Board {
val matrix = lines.map { line ->
line.trim().split(Regex(" +")).map { it.trim().toInt() }.toMutableList()
}.toMutableList()
return Board(matrix)
}
}
}
| 0 | Kotlin | 0 | 0 | 6231e2092314ece3f993d5acf862965ba67db44f | 3,722 | aoc2021 | Creative Commons Zero v1.0 Universal |
ceria/07/src/main/kotlin/Solution.kt | VisionistInc | 317,503,410 | false | null | import java.io.File;
val yourBag = "shiny gold"
val stopBag = "no other"
val outterBag = "contain"
var total = 0
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(bagRules :List<String>) :Int {
return canContainBag(yourBag, bagRules.filter{ !it.startsWith(yourBag) }, mutableSetOf<String>()).size
}
private fun solution2(bagRules :List<String>) :Int {
countBagsInside(yourBag, bagRules, 1)
return total
}
private fun canContainBag(bag :String, bagRules :List<String>, containingBags :MutableSet<String>) :Set<String> {
for (rule in bagRules) {
if (rule.contains(bag)) {
val containingBag = rule.substring(0, rule.indexOf("bags")).trim()
if (containingBag.equals(bag)) {
containingBags.add(containingBag)
}
if (!containingBags.contains(containingBag)) {
canContainBag(containingBag, bagRules, containingBags)
}
}
}
return containingBags
}
private fun countBagsInside(bag :String, bagRules :List<String>, containingCount :Int) {
val rule = bagRules.filter{ it.startsWith(bag) }.first()
var bagCount = 0
if (!rule.contains(stopBag)) {
val ruleParts = rule.substring(rule.indexOf(outterBag) + outterBag.length + 1).split(" ")
var numBags = 0
while (numBags < ruleParts.size) {
val newBagCount = ruleParts.get(numBags).toInt()
val newBag = ruleParts.get(numBags + 1).plus(" ").plus(ruleParts.get(numBags + 2))
bagCount = (newBagCount * containingCount) + bagCount
countBagsInside(newBag, bagRules, newBagCount * containingCount)
numBags += 4
}
total += bagCount
}
} | 0 | Rust | 0 | 0 | 002734670384aa02ca122086035f45dfb2ea9949 | 1,869 | advent-of-code-2020 | MIT License |
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/mathematics/Prime.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.mathematics
import kotlin.math.sqrt
import kotlin.random.Random
/**
* Two numbers are co-prime when the GCD of the numbers is 1.
* This method uses an algorithm called the Euclidean algorithm to compute GCD.
*/
fun areCoprime(first: Long, second: Long): Boolean {
fun greatestCommonDivisor(first: Long, second: Long): Long {
val smaller = if (first <= second) first else second
val bigger = if (first > second) first else second
return if (bigger % smaller == 0L) smaller
else greatestCommonDivisor(smaller, bigger % smaller)
}
return greatestCommonDivisor(first, second) == 1L
}
/**
* Returns all co-primes starting from 1 of a number, where limit is the biggest number to be checked for coprimality.
*/
fun returnAllCoprimes(number: Long, limit: Long = number): List<Long> {
val result = ArrayList<Long>()
for (i in 1..limit) if (areCoprime(number, i)) result.add(i)
return result
}
/**
* Returns a specified amount of the closest co-primes in either direction from the number.
*/
fun returnClosestCoprimes(number: Long, amount: Int, increment: Boolean = false): List<Long> {
val result = ArrayList<Long>()
when (increment) {
true -> {
var i = number
while (true) {
if (areCoprime(number, ++i)) {
result.add(i)
if (result.size == amount) break
}
}
}
false -> {
for (i in (number - 1) downTo 1) if (areCoprime(number, i)) {
result.add(i)
if (result.size == amount) break
}
}
}
return result
}
/**
* Generates a random prime number within range, using isPrime() function to check for primality.
*/
fun generateRandomPrime(range: IntRange): Int {
val count = range.count()
var i = 0
var number: Int
do {
number = Random.nextInt(range.first, range.last)
if (isPrime(number.toLong())) return number
i++
if (i >= count) return -1
} while (true)
}
/**
* This method returns true if the number is a prime number.
* Simply, it checks all the numbers up to the numbers square root and returns false if the number is divisible by any,
* otherwise returns true.
*/
fun isPrime(num: Long): Boolean {
// Negative integers can not be prime. 0 is also not a prime.
if (num < 1) return false
// Taking shortcuts - if a number is divisible without the remainder by small natural numbers, it is not a prime number.
if (num > 10 && (num % 2 == 0L ||
num % 3 == 0L ||
num % 5 == 0L ||
num % 7 == 0L ||
num % 9 == 0L)) return false
// If the number is belonging to small known prime numbers, return true.
// Likewise, small known not-primes, return false.
when (num) {
in setOf<Long>(2, 3, 5, 7) -> return true
in setOf<Long>(1, 4, 6, 8, 9) -> return false
else -> {
// Otherwise, take every number up to the numbers square root.
// If none of those the number is divisible by without the remainder, it is a prime number.
val sqrt = sqrt(num.toDouble())
for (i in 2..sqrt.toInt()) if (num % i == 0L) return false
}
}
return true
}
/**
* Uses a method called sieve of Eratosthenes to get all prime numbers until the limit.
* Works by adding all the numbers in an arraylist first and then removing all the multiples of every single number in that
* list.
*/
fun getAllPrimesSieve(limit: Int): List<Int> {
val result = ArrayList<Int>()
for (i in 2..limit) {
result.add(i)
}
var finished = false
var currentIndex = 0
while (!finished) {
val currentNumber = result[currentIndex]
val iterator = result.iterator()
while (iterator.hasNext()) {
val next = iterator.next()
if (next % currentNumber == 0 && next != currentNumber) iterator.remove()
}
if (currentIndex + 1 == result.size) finished = true
else currentIndex++
}
return result
}
/**
* Gets all primes until the limit by checking whether every number in the loop is a prime number.
*/
fun getAllPrimesPlain(limit: Int): List<Int> {
val result = ArrayList<Int>()
for (i in 2..limit) if (isPrime(i.toLong())) result.add(i)
return result
}
| 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 4,487 | KAHelpers | MIT License |
src/Day13.kt | greg-burgoon | 573,074,283 | false | {"Kotlin": 120556} | fun main() {
fun constructList(listString: String): MutableList<Any> {
var stack = ArrayDeque<MutableList<Any>>()
var currentInteger = ""
listString.toCharArray().forEach {
if (it == '[') {
stack.add(mutableListOf<Any>())
} else if (it == ']') {
if (currentInteger.length > 0) {
stack.last().add(currentInteger.toInt())
currentInteger = ""
}
if (stack.size == 1)
{
return stack.first()
}
var currentList = stack.removeLast()
stack.last().add(currentList)
} else if (it == ',') {
if (currentInteger.length > 0) {
stack.last().add(currentInteger.toInt())
currentInteger = ""
}
} else {
currentInteger = currentInteger + it
}
}
return stack.first()
}
fun checkLists(listOne: MutableList<*>, listTwo: MutableList<*>): Int {
val iteratorOne = listOne.stream().iterator()
val iteratorTwo = listTwo.stream().iterator()
while(iteratorOne.hasNext() && iteratorTwo.hasNext()) {
val valueOne = iteratorOne.next()
val valueTwo = iteratorTwo.next()
if (valueOne is Int && valueTwo is Int) {
if (valueOne < valueTwo) {
return -1
} else if (valueOne > valueTwo) {
return 1
}
} else if (valueOne is MutableList<*> && valueTwo is MutableList<*>) {
var ordering = checkLists(valueOne, valueTwo)
if (ordering != 0) {
return ordering
}
} else {
if (valueOne is Int && valueTwo is MutableList<*>) {
var ordering = checkLists(mutableListOf<Any>(valueOne), valueTwo)
if (ordering != 0) {
return ordering
}
} else if (valueOne is MutableList<*> && valueTwo is Int) {
var ordering = checkLists(valueOne, mutableListOf<Any>(valueTwo))
if (ordering != 0) {
return ordering
}
}
}
}
var ordering = if (!iteratorOne.hasNext() && iteratorTwo.hasNext()) -1 else if (!iteratorOne.hasNext() && !iteratorTwo.hasNext()) 0 else 1
return ordering
}
fun part1(input: String): Int {
var lists = input.split("\n\n")
.map {
var lists = it.split("\n")
listOf(lists[0], lists[1])
}.map { (listOneString, listTwoString) ->
listOf(constructList(listOneString), constructList(listTwoString))
}.mapIndexed { index, (listOne, listTwo) ->
if (checkLists(listOne, listTwo) == -1) index+1 else 0
}
return lists.sum()
}
fun part2(input: String): Int {
var lists = input.split("\n\n")
.map {
var lists = it.split("\n")
listOf(lists[0], lists[1])
}.flatMap { (listOneString, listTwoString) ->
listOf(constructList(listOneString), constructList(listTwoString))
}.toMutableList()
var twoSeparator = mutableListOf(mutableListOf(2))
var sixSeparator = mutableListOf(mutableListOf(6))
lists.add(twoSeparator.toMutableList())
lists.add(sixSeparator.toMutableList())
lists.sortWith(Comparator { o1, o2 -> checkLists(o1, o2) })
return (lists.indexOf(twoSeparator.toMutableList())+1) * (lists.indexOf(sixSeparator.toMutableList())+1)
}
val testInput = readInput("Day13_test")
val output = part1(testInput)
check(output == 13)
val outputTwo = part2(testInput)
check(outputTwo == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 74f10b93d3bad72fa0fc276b503bfa9f01ac0e35 | 4,125 | aoc-kotlin | Apache License 2.0 |
src/Day01.kt | SpencerDamon | 573,244,838 | false | {"Kotlin": 6482} | import kotlin.math.max
fun main() {
/* Return highest sum dilineated by "" */
fun part1(input: List<String>): Int {
var highestSum = 0
var currentSum = 0
for (s in input) {
if (s.isEmpty()) { // if (see an empty line)
highestSum = max(highestSum, currentSum)
currentSum = 0
} else {
currentSum += s.toInt()
}
}
return highestSum
}
/* Return sum of highest 3 sums dilineated by "" */
fun part2(input: List<String>): Int {
val highestScores = mutableListOf<Int>() // store all the scores
var currentSum = 0
for (s in input) {
if (s.isEmpty()) {
highestScores.add(currentSum) // add current sum to list
currentSum = 0
} else {
currentSum += s.toInt() // add int value to var
}
}
highestScores.sortDescending() // sort list
//println
return highestScores.take(3).sum() // sums the numbers from the 3 highest scores
//return input.size
}
// remove comment to test,
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 24000)
//check(part2(testInput) == 41000)
val input = readInput("Day01_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 659a9e9ae4687bd633bddfb924416c80a8a2db2e | 1,459 | aoc-2022-in-Kotlin | Apache License 2.0 |
src/Day05.kt | OskarWalczak | 573,349,185 | false | {"Kotlin": 22486} | import java.util.*
import kotlin.collections.ArrayList
fun main() {
fun readStacks(input: List<String>): MutableList<Stack<Char>> {
val stacks: MutableList<Stack<Char>> = ArrayList()
var stackNumsLineIndex: Int = 0
for(line in input.withIndex()){
if(line.value.matches(Regex("[0-9 ]+"))){
stackNumsLineIndex = line.index
break
}
}
stacks.add(Stack())
for(i: Int? in input[stackNumsLineIndex].split(' ').map { it.toIntOrNull() }){
if(i != null)
stacks.add(Stack())
}
for(i: Int in stackNumsLineIndex-1 downTo 0){
val line: String = input[i]
var stackNum = 1
for(j: Int in 1..line.length step 4){
if(line[j] in 'A'..'Z'){
stacks[stackNum].push(line[j])
}
stackNum++
}
}
return stacks
}
fun readInstructions(input: List<String>): MutableList<Triple<Int, Int, Int>> {
val instructions: MutableList<Triple<Int, Int, Int>> = ArrayList()
input.forEach { line ->
if(line.startsWith("move")){
val nums = line.split(' ').map { it.toIntOrNull() }
val notNulls = nums.filterNotNull()
instructions.add(Triple(notNulls[0], notNulls[1], notNulls[2]))
}
}
return instructions
}
fun applyInstructionsToStacks(instructions: MutableList<Triple<Int, Int, Int>>, stacks: MutableList<Stack<Char>>): MutableList<Stack<Char>>{
instructions.forEach{ instruction ->
for(i in 1..instruction.first){
stacks[instruction.third].push(stacks[instruction.second].pop())
}
}
return stacks
}
fun applyInstructionsToNotStacks(instructions: MutableList<Triple<Int, Int, Int>>, stacks: MutableList<Stack<Char>>): MutableList<Stack<Char>>{
instructions.forEach{ instruction ->
val tempStack: Stack<Char> = Stack()
for(i in 1..instruction.first){
tempStack.push(stacks[instruction.second].pop())
}
for(i in 0 until tempStack.size){
stacks[instruction.third].push(tempStack.pop())
}
}
return stacks
}
fun part1(input: List<String>): String {
val stacks = applyInstructionsToStacks(readInstructions(input), readStacks(input))
var tops: String = ""
for(i in 1 until stacks.size){
tops += stacks[i].peek()
}
return tops
}
fun part2(input: List<String>): String {
val stacks = applyInstructionsToNotStacks(readInstructions(input), readStacks(input))
var tops: String = ""
for(i in 1 until stacks.size){
tops += stacks[i].peek()
}
return tops
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
//
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d34138860184b616771159984eb741dc37461705 | 3,180 | AoC2022 | Apache License 2.0 |
src/day3/Day03.kt | Johnett | 572,834,907 | false | {"Kotlin": 9781} | package day3
import readInput
fun main() {
fun Char.getPriorityValue(): Int = when (this) {
in 'a'..'z' -> (this - 'a') + 1
in 'A'..'Z' -> (this - 'A') + 27
else -> error("Item not found")
}
fun part1(input: List<String>): Int = input.map { content ->
val (firstCompartment, secondCompartment) = content.chunked(content.length / 2) { item -> item.toSet() }
firstCompartment.intersect(secondCompartment).first()
}.sumOf { commonItem ->
commonItem.getPriorityValue()
}
fun part2(input: List<String>): Int =
input.chunked(3).map { items ->
val (itemOne, itemTwo, itemThree) = items.map { item -> item.toSet() }
itemOne.intersect(itemTwo).intersect(itemThree).first()
}.sumOf { commonItem ->
commonItem.getPriorityValue()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day3/Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("day3/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | c8b0ac2184bdad65db7d2f185806b9bb2071f159 | 1,143 | AOC-2022-in-Kotlin | Apache License 2.0 |
src/Day23.kt | flex3r | 572,653,526 | false | {"Kotlin": 63192} | import java.util.Collections
suspend fun main() {
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
measureAndPrintResult {
part1(input)
}
measureAndPrintResult {
part2(input)
}
}
private fun part1(input: List<String>): Int {
val elves = parseElves(input)
val movedElves = (0 until 10).fold(elves) { acc, i ->
moveElves(acc, i)
}
return movedElves.maxWidth() * movedElves.maxHeight() - movedElves.size
}
private fun part2(input: List<String>): Int {
var elves = parseElves(input)
var rounds = 0
while (true) {
val newElves = moveElves(elves, rounds++)
if (elves == newElves) {
return rounds
}
elves = newElves
}
}
private fun parseElves(input: List<String>): Set<Vec2> {
return input.reversed().flatMapIndexed { rowIdx, row ->
row.mapIndexed { columnIdx, c ->
Vec2(columnIdx, rowIdx).takeIf { c == '#' }
}
}.filterNotNull().toSet()
}
private data class ProposedMove(val checks: List<Vec2>) {
val move get() = checks[0]
}
private val proposedMoves = listOf(
ProposedMove(listOf(Vec2(0, 1), Vec2(-1, 1), Vec2(1, 1))),
ProposedMove(listOf(Vec2(0, -1), Vec2(-1, -1), Vec2(1, -1))),
ProposedMove(listOf(Vec2(-1, 0), Vec2(-1, -1), Vec2(-1, 1))),
ProposedMove(listOf(Vec2(1, 0), Vec2(1, -1), Vec2(1, 1))),
)
private fun proposedMovesForRound(pos: Vec2, roundNumber: Int): List<ProposedMove> {
return proposedMoves.toMutableList()
.also { Collections.rotate(it, -roundNumber) }
.map { it.copy(checks = it.checks.map { v -> v + pos }) }
}
private fun moveElves(elves: Set<Vec2>, roundNumber: Int) = elves.groupBy { currentPosition ->
val proposedMoves = proposedMovesForRound(currentPosition, roundNumber)
when {
proposedMoves.all { move -> move.checks.none { it in elves } } -> currentPosition
else -> proposedMoves
.firstOrNull { move -> move.checks.none { it in elves } }
?.move ?: currentPosition
}
}.flatMap { (newPosition, oldPositions) ->
when (oldPositions.size) {
1 -> listOf(newPosition)
else -> oldPositions
}
}.toSet() | 0 | Kotlin | 0 | 0 | 8604ce3c0c3b56e2e49df641d5bf1e498f445ff9 | 2,297 | aoc-22 | Apache License 2.0 |
src/main/kotlin/bk69/Problem3.kt | yvelianyk | 405,919,452 | false | {"Kotlin": 147854, "Java": 610} | package bk69
// ["dd","aa","bb","dd","aa","dd","bb","dd","aa","cc","bb","cc","dd","cc"]
fun main() {
val res = Problem3().longestPalindrome(
arrayOf(
"xx", "zz"
)
)
println(res)
}
class Problem3 {
fun longestPalindrome(words: Array<String>): Int {
val countMap = words.toList().groupingBy { it }.eachCount() as MutableMap<String, Int>
var sameMax = 0
var res = 0
for (entry in countMap) {
val str = entry.key
val reversed = str.reversed()
val num = entry.value
val reversedCount = countMap.getOrDefault(str.reversed(), 0)
if (str == reversed && num == 1) sameMax = 1
if (num >= 1 && reversedCount >= 1) {
var minNum = minOf(num, reversedCount)
if (minNum > 1 && minNum % 2 == 1) minNum--
res += minNum * if (str == reversed) 2 else 4
countMap[str] = num - minNum
if (countMap.containsKey(reversed)) {
countMap[reversed] = reversedCount - minNum
}
}
}
for (entry in countMap) {
if (entry.key == entry.key.reversed()) sameMax = maxOf(entry.value, sameMax)
}
return res + sameMax * 2
}
}
| 0 | Kotlin | 0 | 0 | 780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd | 1,312 | leetcode-kotlin | MIT License |
2021/src/main/kotlin/com/trikzon/aoc2021/Day13.kt | Trikzon | 317,622,840 | false | {"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397} | package com.trikzon.aoc2021
import kotlin.math.absoluteValue
fun main() {
val input = getInputStringFromFile("/day13.txt")
benchmark(Part.One, ::day13Part1, input, 682, 50)
benchmark(Part.Two, ::day13Part2, input, 682, 50)
}
fun day13Part1(input: String): Int {
var points = ArrayList<Pair<Int, Int>>()
val instructions = ArrayList<Pair<String, Int>>()
input.lines().forEach { line ->
if (line.split(' ')[0] == "fold") {
val instruction = line.split(' ')[2].split('=')
instructions.add(Pair(instruction[0], instruction[1].toInt()))
} else {
val point = line.split(',')
points.add(Pair(point[0].toInt(), point[1].toInt()))
}
}
val firstInstruction = instructions[0]
points = if (firstInstruction.first == "x") {
foldOnX(firstInstruction.second, points)
} else {
foldOnY(firstInstruction.second, points)
}
return points.size
}
fun foldOnX(x: Int, points: List<Pair<Int, Int>>): ArrayList<Pair<Int, Int>> {
val foldedPoints = ArrayList<Pair<Int, Int>>()
for (point in points) {
if (point.first < x) {
if (!foldedPoints.contains(point)) foldedPoints.add(point)
} else {
val foldedPoint = Pair((point.first - (x * 2)).absoluteValue, point.second)
if (!foldedPoints.contains(foldedPoint)) foldedPoints.add(foldedPoint)
}
}
return foldedPoints
}
fun foldOnY(y: Int, points: List<Pair<Int, Int>>): ArrayList<Pair<Int, Int>> {
val foldedPoints = ArrayList<Pair<Int, Int>>()
for (point in points) {
if (point.second < y) {
if (!foldedPoints.contains(point)) foldedPoints.add(point)
} else {
val foldedPoint = Pair(point.first, (point.second - (y * 2)).absoluteValue)
if (!foldedPoints.contains(foldedPoint)) foldedPoints.add(foldedPoint)
}
}
return foldedPoints
}
fun day13Part2(input: String): Int {
var points = ArrayList<Pair<Int, Int>>()
val instructions = ArrayList<Pair<String, Int>>()
input.lines().forEach { line ->
if (line.split(' ')[0] == "fold") {
val instruction = line.split(' ')[2].split('=')
instructions.add(Pair(instruction[0], instruction[1].toInt()))
} else {
val point = line.split(',')
points.add(Pair(point[0].toInt(), point[1].toInt()))
}
}
for (instruction in instructions) {
points = if (instruction.first == "x") {
foldOnX(instruction.second, points)
} else {
foldOnY(instruction.second, points)
}
}
// Just print the letters. I don't feel like parsing them.
// val display = Array(100) { Array(100) { '.' } }
// for (point in points) {
// display[point.first][point.second] = '#'
// }
// for (x in display.indices) {
// for (y in display.indices.reversed()) {
// print(display[x][y])
// }
// println()
// }
return points.size
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 3,051 | advent-of-code | MIT License |
src/main/kotlin/dev/paulshields/aoc/Day17.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 17: Trick Shot
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.Point
import dev.paulshields.aoc.common.extractGroups
import dev.paulshields.aoc.common.readFileAsString
import kotlin.math.abs
fun main() {
println(" ** Day 17: Trick Shot ** \n")
val oceanTrenchArea = readFileAsString("/Day17OceanTrenchArea.txt").let {
val oceanTrenchAreaRegex = Regex("target area: x=([-\\d]+)..([-\\d]+), y=([-\\d]+)..([-\\d]+)")
val parts = oceanTrenchAreaRegex.extractGroups(it).map { it.toInt() }
val xRange = increasingRangeBetween(parts[0], parts[1])
val yRange = increasingRangeBetween(parts[2], parts[3])
TargetArea(xRange, yRange)
}
val maxHeight = findHeightAtVelocityWhichLandsInTrench(oceanTrenchArea)
println("The max height, at thus the most stylish velocity, is $maxHeight")
val allValidVelocities = findAllInitialVelocitiesWhichLandInTrench(oceanTrenchArea)
println("The total number of possible velocities is ${allValidVelocities.size}")
}
fun findHeightAtVelocityWhichLandsInTrench(targetArea: TargetArea) =
findAllInitialVelocitiesWhichLandInTrench(targetArea)
.map { it.maxHeight }
.maxByOrNull { it } ?: 0
fun findAllInitialVelocitiesWhichLandInTrench(targetArea: TargetArea) =
possibleXVelocities(targetArea)
.flatMap { xVelocity ->
possibleYVelocities(targetArea).mapNotNull { collectDataIfLandsInTargetArea(Point(xVelocity, it), targetArea) }
}
private fun possibleXVelocities(targetArea: TargetArea) = (0..targetArea.right)
private fun possibleYVelocities(targetArea: TargetArea) = (targetArea.bottom..maxValidYVelocity(targetArea))
private fun maxValidYVelocity(targetArea: TargetArea) =
if (targetArea.top > 0 && targetArea.bottom < 0) {
targetArea.top + abs(targetArea.bottom)
} else if (targetArea.bottom < 0) {
abs(targetArea.bottom)
} else {
targetArea.top
}
private fun collectDataIfLandsInTargetArea(initialVelocity: Point, targetArea: TargetArea): VelocityMetadata? {
var position = Point(0, 0)
var velocity = initialVelocity
var maxHeight = 0
while (trajectoryIsStillValid(position, targetArea)) {
position += velocity
velocity = calculateNewVelocity(velocity)
maxHeight = if (position.y > maxHeight) position.y else maxHeight
if (targetArea.isWithinArea(position)) return VelocityMetadata(initialVelocity, maxHeight)
}
return null
}
fun calculateNewVelocity(velocity: Point): Point {
val xVelocity = if (velocity.x > 0) {
velocity.x - 1
} else if (velocity.x < 0) {
velocity.x + 1
} else 0
return Point(xVelocity, velocity.y - 1)
}
private fun trajectoryIsStillValid(position: Point, targetArea: TargetArea) =
position.x < targetArea.right && position.y > targetArea.bottom
data class TargetArea(val xRange: IntProgression, val yRange: IntProgression) {
val top = if (yRange.first > yRange.last) yRange.first else yRange.last
val left = xRange.first
val bottom = if (yRange.first < yRange.last) yRange.first else yRange.last
val right = xRange.last
fun isWithinArea(position: Point) = xRange.contains(position.x) && yRange.contains(position.y)
}
data class VelocityMetadata(val initialVelocity: Point, val maxHeight: Int)
private fun increasingRangeBetween(start: Int, end: Int) = if (start < end) (start..end) else (end..start)
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 3,473 | AdventOfCode2021 | MIT License |
src/main/kotlin/28-aug.kt | aladine | 276,334,792 | false | {"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511} | class Solution28Aug {
fun findRightInterval(intervals: Array<IntArray>): IntArray {
val ans: MutableList<Int> = MutableList<Int>(intervals.size) {-1}
val newIntervals = intervals.withIndex().map { c ->
intArrayOf(c.index, c.value[0])
}.sortedBy { it[1] }
for(i in newIntervals.size-1 downTo 0){
val ele = newIntervals[i]
for(j in i+1 until newIntervals.size){
val idx = newIntervals[j][0]
if (intervals[ele[0]][1] <= intervals[idx][0]){
ans[ele[0]] = idx
break
}
}
}
return ans.toIntArray()
}
}
/*val ret = IntArray(intervals.size) { -1 }
val intervalsSorted = ArrayList<IntArray>()
//start,index
for (i in intervals.indices) {
intervalsSorted.add(intArrayOf(intervals[i][0], i))
}
intervalsSorted.sortWith(Comparator<IntArray> { o1, o2 ->
if (o1[0] < o2[0]) {
-1
} else if (o1[0] > o2[0]) {
1
} else {
if (o1[1] < o2[1]) {
-1
} else {
1
}
}
})
for (i in intervals.indices) {
var start = 0
var end = intervals.size - 1
var findIndex = -1
while (start <= end) {
val mid = (start + end) / 2
if (intervalsSorted[mid][0] < intervals[i][1]) {
start = mid + 1
} else if (intervalsSorted[mid][0] >= intervals[i][1]) {
if (intervalsSorted[mid][1] != i) {
end = mid - 1
findIndex = intervalsSorted[mid][1]
} else {
start = mid + 1
}
}
}
ret[i] = findIndex
}
return ret
}
*/ | 0 | C++ | 1 | 1 | 54b7f625f6c4828a72629068d78204514937b2a9 | 2,003 | awesome-leetcode | Apache License 2.0 |
src/year2022/day23/Day23.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day23
import Point2D
import readInputFileByYearAndDay
import readTestFileByYearAndDay
enum class Direction(val offset: Point2D) {
N(Point2D(0, -1)),
NE(Point2D(1, -1)),
E(Point2D(1, 0)),
SE(Point2D(1, 1)),
S(Point2D(0, 1)),
SW(Point2D(-1, 1)),
W(Point2D(-1, 0)),
NW(Point2D(-1, -1));
}
fun toCheck(direction: Direction): List<Direction> = when (direction) {
Direction.N -> listOf(Direction.N, Direction.NE, Direction.NW)
Direction.E -> listOf(Direction.E, Direction.NE, Direction.SE)
Direction.S -> listOf(Direction.S, Direction.SE, Direction.SW)
else -> listOf(Direction.W, Direction.SW, Direction.NW)
}
data class Elf(var position: Point2D) {
var proposal: Point2D = position
fun performMove(): Point2D {
position = proposal
proposal = position
return position
}
fun propose(direction: Direction): Point2D {
proposal = position + direction.offset
return proposal
}
fun surroundingsInDirection(direction: Direction) =
toCheck(direction).map { it.offset + position }
fun surroundings() = sequence {
for (i in -1..1)
for (j in -1..1)
if (!(i == 0 && j == 0))
yield(Point2D(position.x + i, position.y + j))
}
}
fun main() {
fun hasNearbyElves(elf: Elf, elfPositions: Array<BooleanArray>): Boolean =
elf.surroundings().map { elfPositions[it.y][it.x] }.count { it } > 0
fun initializeElves(
parsedInput: Array<List<String>>,
buffer: Int
): MutableList<Elf> {
val elves = mutableListOf<Elf>() // easy iteration over elves
parsedInput.forEachIndexed { indexY, strings ->
strings.forEachIndexed { indexX, s ->
if (s == "#") elves.add(Elf(Point2D(indexX + buffer, indexY + buffer)))
}
}
return elves
}
// return true if someone moved, false if not
fun simulateRound(
dimYNew: Int,
dimXNew: Int,
elves: MutableList<Elf>,
checkOrder: MutableList<Direction>
): Boolean {
val elfPositions = Array(dimYNew) { BooleanArray(dimXNew) { false } } // easy elf position lookup
elves.forEach { elfPositions[it.position.y][it.position.x] = true }
val elvesWithNeighbours = elves.filter { elf -> hasNearbyElves(elf, elfPositions) }
if (elvesWithNeighbours.isEmpty()) return false
// compute proposals
val proposals = Array(dimYNew) { IntArray(dimXNew) { 0 } } // store proposals
elvesWithNeighbours
.forEach { elf ->
for (direction in checkOrder) {
val hasNoElves = elf.surroundingsInDirection(direction)
.map { point -> elfPositions[point.y][point.x] }
.count { !it } == 3
if (hasNoElves) {
val (x, y) = elf.propose(direction)
proposals[y][x] += 1
break
}
}
}
// find proposals with duplicate targets, then make elves not move
val duplicates = mutableListOf<Point2D>()
proposals.forEachIndexed { y, line ->
line.forEachIndexed { x, i ->
if (i > 1) duplicates.add(Point2D(x, y))
}
}
elvesWithNeighbours.forEach { elf -> if (duplicates.contains(elf.proposal)) elf.proposal = elf.position }
// move elves with unique targets
elvesWithNeighbours.forEach { elf -> elf.performMove() }
elves.forEach { elf -> elfPositions[elf.position.y][elf.position.x] = true }
// change priority of directions for next iteration
checkOrder.add(checkOrder.first())
checkOrder.removeAt(0)
return true
}
fun part1(input: List<String>): Int {
val parsedInput = input.map { it.split("") }
.map { it.drop(1) }
.map { it.dropLast(1) }
.toTypedArray()
// big brain assumption
// in 10 moves, the field cannot extend by more than 10 in each direction
val buffer = 10
val dimYNew = parsedInput.size + 2 * buffer
val dimXNew = parsedInput[0].size + 2 * buffer
val elves = initializeElves(parsedInput, buffer) // easy iteration over elves
val checkOrder = mutableListOf(Direction.N, Direction.S, Direction.W, Direction.E)
repeat(10) {
simulateRound(dimYNew, dimXNew, elves, checkOrder)
}
val minX = elves.minOf { it.position.x }
val minY = elves.minOf { it.position.y }
val maxX = elves.maxOf { it.position.x }
val maxY = elves.maxOf { it.position.y }
return ((maxX - minX + 1) * (maxY - minY + 1)) - elves.size
}
fun part2(input: List<String>): Int {
val parsedInput = input.map { it.split("") }
.map { it.drop(1) }
.map { it.dropLast(1) }
.toTypedArray()
// big brain assumption
// the field will not extend by more than 1000 in each direction
val buffer = 1000
val dimYNew = parsedInput.size + 2 * buffer
val dimXNew = parsedInput[0].size + 2 * buffer
val checkOrder = mutableListOf(Direction.N, Direction.S, Direction.W, Direction.E)
val elves = initializeElves(parsedInput, buffer) // easy iteration over elves
var round = 1
while (simulateRound(dimYNew, dimXNew, elves, checkOrder)) round++
return round
}
val testInput = readTestFileByYearAndDay(2022, 23)
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInputFileByYearAndDay(2022, 23)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 5,816 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/day05/SupplyStacks.kt | iamwent | 572,947,468 | false | {"Kotlin": 18217} | package day05
import readText
import java.util.*
class SupplyStacks(
private val name: String
) {
private fun read(): Pair<List<Stack<Char>>, List<Step>> {
val (stacks, steps) = readText(name).split("\n\n")
return readStacks(stacks) to readSteps(steps)
}
private fun readStacks(input: String): List<Stack<Char>> {
val crateIndex = mutableListOf<Int>()
val result = mutableListOf<Stack<Char>>()
input.split("\n")
.asReversed()
.forEachIndexed { i, stack ->
if (i == 0) {
stack.forEachIndexed { index, char ->
if (char.isDigit()) {
crateIndex.add(index)
result.add(Stack<Char>())
}
}
return@forEachIndexed
}
crateIndex.forEachIndexed { index, i ->
if (stack.length > i && stack[i].isLetter()) {
result[index].push(stack[i])
}
}
}
return result
}
private fun readSteps(steps: String): List<Step> {
return steps.split("\n")
.map { step ->
val (moves, from, to) = step.split(" ")
.chunked(2)
.map { it.last().toInt() }
return@map Step(moves, from, to)
}
}
fun part1(): String {
val (stacks, steps) = read()
steps.forEach { step ->
repeat(step.moves) {
val crate = stacks[step.from - 1].pop()
stacks[step.to - 1].push(crate)
}
}
return stacks.map { it.peek() }.joinToString("")
}
fun part2(): String {
val (stacks, steps) = read()
val temp = Stack<Char>()
steps.forEach { step ->
repeat(step.moves) {
val crate = stacks[step.from - 1].pop()
temp.push(crate)
}
repeat(step.moves) {
val crate = temp.pop()
stacks[step.to - 1].push(crate)
}
}
return stacks.map { it.peek() }.joinToString("")
}
}
data class Step(
val moves: Int,
val from: Int,
val to: Int
)
| 0 | Kotlin | 0 | 0 | 77ce9ea5b227b29bc6424d9a3bc486d7e08f7f58 | 2,340 | advent-of-code-kotlin | Apache License 2.0 |
src/y2016/Day10.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.readInput
interface NumberGiver {
fun getNumberFor(target: Int): Int
}
data class Input(val n: Int) : NumberGiver {
override fun getNumberFor(target: Int): Int {
return n
}
}
data class Bot(
val id: Int,
val inputMap: Map<Int, List<NumberGiver>>,
val lowTarget: Int,
val highTarget: Int
) : NumberGiver {
private var inputValues: List<Int>? = null
override fun getNumberFor(target: Int): Int {
if (inputValues == null) {
inputValues = inputMap[this.id]!!.map { it.getNumberFor(this.id) }
}
return when (target) {
lowTarget -> inputValues!!.min()
highTarget -> inputValues!!.max()
else -> error("$target not a valid target for ${this.id} with targets $lowTarget and $highTarget")
}
}
override fun toString(): String {
return "$id, $lowTarget, $highTarget"
}
}
object Day10 {
private fun parse(input: List<String>): Map<Int, List<NumberGiver>> {
val inputBots = mutableMapOf<Int, MutableList<NumberGiver>>()
input.forEach { line ->
val els = line.split(" ")
if (els[0] == "value") {
val newInput = Input(els[1].toInt())
val target = els.last().toInt()
addNewNumberGiverToBotMap(inputBots, target, newInput)
} else {
val id = els[1].toInt()
val lowTarget = if (els[5] == "output") -els[6].toInt() - 5000 else els[6].toInt()
val highTarget = if (els[10] == "output") -els.last().toInt() - 5000 else els.last().toInt()
val newBot = Bot(
id,
inputBots,
lowTarget,
highTarget
)
addNewNumberGiverToBotMap(inputBots, lowTarget, newBot)
addNewNumberGiverToBotMap(inputBots, highTarget, newBot)
}
}
return inputBots
}
private fun addNewNumberGiverToBotMap(
bots: MutableMap<Int, MutableList<NumberGiver>>,
target: Int,
new: NumberGiver
) {
if (bots[target] == null) {
bots[target] = mutableListOf(new)
} else {
bots[target]!!.add(new)
}
}
fun part1(input: List<String>, cmp1: Int, cmp2: Int): Set<Int> {
val botMap = parse(input)
val botLookup = botMap.values.flatten().filterIsInstance<Bot>().associateBy { it.id }
val trace1 = getTrace(botMap, botLookup, cmp1)
val trace2 = getTrace(botMap, botLookup, cmp2)
return trace1.intersect(trace2)
}
private fun getTrace(botMap: Map<Int, List<NumberGiver>>, botLookup: Map<Int, Bot>, n: Int): Set<Int> {
val start = botMap.entries.first { entry ->
entry.value.any { it is Input && it.n == n }
}.key
println("first bot for $n: $start")
val trace = mutableSetOf(start)
var bot = botLookup[start]
while (bot != null) {
bot = if (bot.getNumberFor(bot.lowTarget) == n) {
botLookup[bot.lowTarget]
} else {
botLookup[bot.highTarget]
}
bot?.id?.let { trace.add(it) }
}
return trace
}
fun part2(input: List<String>): Int {
val botMap = parse(input)
val botLookup = botMap.values.flatten().filterIsInstance<Bot>().associateBy { it.id }
val botZero = botLookup.values.first { it.lowTarget == -5000 || it.highTarget == -5000 }
val botOne = botLookup.values.first { it.lowTarget == -5001 || it.highTarget == -5001 }
val botTwo = botLookup.values.first { it.lowTarget == -5002 || it.highTarget == -5002 }
return botZero.getNumberFor(-5000) * botOne.getNumberFor(-5001) * botTwo.getNumberFor(-5002)
}
}
fun main() {
val testInput = """
value 5 goes to bot 2
bot 2 gives low to bot 1 and high to bot 0
value 3 goes to bot 1
bot 1 gives low to output 1 and high to bot 0
bot 0 gives low to output 2 and high to output 0
value 2 goes to bot 2
""".trimIndent().split("\n")
println("------Tests------")
println(Day10.part1(testInput, 5, 2))
println(Day10.part2(testInput))
println("------Real------")
val input = readInput("resources/2016/day10")
println(Day10.part1(input, 61, 17))
println(Day10.part2(input))
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 4,471 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2020/Day23.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 23 - Crab Cups
* Problem Description: http://adventofcode.com/2020/day/23
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day23/
*/
package com.ginsberg.advent2020
class Day23(private val input: String) {
fun solvePart1(roundsToPlay: Int): String =
Cups(input)
.playRounds(roundsToPlay)
.toString()
fun solvePart2(roundsToPlay: Int): Long =
Cups(input, 1_000_000)
.playRounds(roundsToPlay)
.nextAsList(2)
.map { it.value.toLong() }
.product()
private class Cups(order: String, numberOfCups: Int = order.length) {
val cups: List<Cup> = List(numberOfCups+1) { Cup(it) }
var currentCup: Cup = cups[order.first().asInt()]
init {
val cupIdsInOrder = order.map { it.asInt() } + (order.length + 1 .. numberOfCups)
cupIdsInOrder
.map { cups[it] }
.fold(cups[order.last().asInt()]) { previous, cup ->
cup.also { previous.next = cup }
}
cups[cupIdsInOrder.last()].next = cups[cupIdsInOrder.first()]
}
fun playRounds(numRounds: Int): Cup {
repeat(numRounds) {
playRound()
}
return cups[1]
}
private fun playRound() {
val next3: List<Cup> = currentCup.nextAsList(3)
val destination = calculateDestination(next3.map { it.value }.toSet())
moveCups(next3, destination)
currentCup = currentCup.next
}
private fun moveCups(cupsToInsert: List<Cup>, destination: Cup) {
val prevDest = destination.next
currentCup.next = cupsToInsert.last().next
destination.next = cupsToInsert.first()
cupsToInsert.last().next = prevDest
}
private fun calculateDestination(exempt: Set<Int>): Cup {
var dest = currentCup.value - 1
while(dest in exempt || dest == 0) {
dest = if(dest == 0) cups.size-1 else dest -1
}
return cups[dest]
}
}
private class Cup(val value: Int) {
lateinit var next: Cup
fun nextAsList(n: Int): List<Cup> =
(1 .. n).runningFold(this) { cur, _ -> cur.next }.drop(1)
override fun toString(): String = buildString {
var current = this@Cup.next
while(current != this@Cup) {
append(current.value.toString())
current = current.next
}
}
}
}
| 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 2,682 | advent-2020-kotlin | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/Day22.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 22: Reactor Reboot
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.extractGroups
import dev.paulshields.aoc.common.readFileAsStringList
import kotlin.math.max
import kotlin.math.min
fun main() {
println(" ** Day 22: Reactor Reboot ** \n")
val rebootInstructions = readFileAsStringList("/Day22RebootInstructions.txt")
val onCubeCount = runRebootInstructions(rebootInstructions, -50..50)
println("There are $onCubeCount cubes turned on after the reboot instructions (within range) are executed.")
val fullOnCubeCount = runRebootInstructions(rebootInstructions)
println("There are $fullOnCubeCount cubes turned on when the complete list of instructions is executed.")
}
/**
* This uses the concept of negative volume to handle the large amount of cubes being worked with here.
* If a 9x9x9 range overlaps with another 3x3x3 range by 1 cube, it will add both 3x3x3 ranges to the areas list,
* plus a "negative range" of 1, to give the correct number of on cubes count of 53 (27+27-1).
*/
fun runRebootInstructions(rawInstructions: List<String>, areaLimit: IntRange? = null): Long {
val instructions = areaLimit?.let {
val parsedInstructions = parseInstructions(rawInstructions)
limitInstructionRangeTo(it, parsedInstructions)
} ?: parseInstructions(rawInstructions)
val areas = mutableListOf<Region3D>()
instructions.forEach { instruction ->
areas.addAll(areas.mapNotNull { it.overlappingRegion(instruction.region)?.toInvertedRegion() })
if (instruction.action == RebootAction.ON) {
areas.add(instruction.region)
}
}
return areas.sumOf { it.size }
}
private fun parseInstructions(instructions: List<String>): List<RebootInstruction> {
val instructionParser = Regex("(on|off) x=([-\\d]+)..([-\\d]+),y=([-\\d]+)..([-\\d]+),z=([-\\d]+)..([-\\d]+)")
return instructions.map {
val parsedInstruction = instructionParser.extractGroups(it)
val action = if (parsedInstruction.first() == "on") RebootAction.ON else RebootAction.OFF
val xRange = parsedInstruction[1].toInt()..parsedInstruction[2].toInt()
val yRange = parsedInstruction[3].toInt()..parsedInstruction[4].toInt()
val zRange = parsedInstruction[5].toInt()..parsedInstruction[6].toInt()
RebootInstruction(action, xRange, yRange, zRange)
}
}
private fun limitInstructionRangeTo(areaLimit: IntRange, instructions: List<RebootInstruction>): List<RebootInstruction> {
return instructions.mapNotNull {
val xRangeIntersection = areaLimit.intersectRange(it.region.xRange)
val yRangeIntersection = areaLimit.intersectRange(it.region.yRange)
val zRangeIntersection = areaLimit.intersectRange(it.region.zRange)
if (xRangeIntersection != null && yRangeIntersection != null && zRangeIntersection != null) {
RebootInstruction(it.action, xRangeIntersection, yRangeIntersection, zRangeIntersection)
} else null
}
}
class RebootInstruction(val action: RebootAction, xRange: IntRange, yRange: IntRange, zRange: IntRange) {
val region = Region3D(xRange, yRange, zRange)
}
open class Region3D(val xRange: IntRange, val yRange: IntRange, val zRange: IntRange) {
open val size by lazy { xRange.count().toLong() * yRange.count().toLong() * zRange.count().toLong() }
open fun overlappingRegion(region: Region3D): Region3D? {
val xOverlap = xRange.intersectRange(region.xRange)
val yOverlap = yRange.intersectRange(region.yRange)
val zOverlap = zRange.intersectRange(region.zRange)
return if (xOverlap != null && yOverlap != null && zOverlap != null) {
Region3D(xOverlap, yOverlap, zOverlap)
} else null
}
open fun toInvertedRegion(): Region3D = NegativeRegion3D(xRange, yRange, zRange)
}
class NegativeRegion3D(xRange: IntRange, yRange: IntRange, zRange: IntRange) : Region3D(xRange, yRange, zRange) {
override val size by lazy { super.size * -1 }
override fun overlappingRegion(region: Region3D) = super.overlappingRegion(region)?.toInvertedRegion()
override fun toInvertedRegion() = Region3D(xRange, yRange, zRange)
}
enum class RebootAction {
ON, OFF
}
private fun IntRange.intersectRange(other: IntRange): IntRange? {
val startOfRange = max(this.first, other.first)
val endOfRange = min(this.last, other.last)
return if (endOfRange < startOfRange) null else startOfRange..endOfRange
}
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 4,490 | AdventOfCode2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DesignFoodRatingSystem.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
import java.util.TreeSet
/**
* 2353. Design a Food Rating System
* @see <a href="https://leetcode.com/problems/design-a-food-rating-system">Source</a>
*/
interface FoodRatings {
fun changeRating(food: String, newRating: Int)
fun highestRated(cuisine: String): String
}
class FoodRatingsPriorityQueue(foods: Array<String>, cuisines: Array<String>, ratings: IntArray) : FoodRatings {
// Map food with its rating.
private var foodRatingMap: MutableMap<String, Int> = HashMap()
// Map food with the cuisine it belongs to.
private var foodCuisineMap: MutableMap<String, String> = HashMap()
// Store all food of a cuisine in a priority queue (to sort them on ratings/name)
// Priority queue element -> Food: (foodRating, foodName)
private var cuisineFoodMap: MutableMap<String, PriorityQueue<Food>> = HashMap()
init {
for (i in foods.indices) {
// Store 'rating' and 'cuisine' of the current 'food' in 'foodRatingMap' and 'foodCuisineMap' maps.
foodRatingMap[foods[i]] = ratings[i]
foodCuisineMap[foods[i]] = cuisines[i]
// Insert the '(rating, name)' element into the current cuisine's priority queue.
cuisineFoodMap.computeIfAbsent(
cuisines[i],
) { PriorityQueue() }.add(
Food(
ratings[i],
foods[i],
),
)
}
}
override fun changeRating(food: String, newRating: Int) {
// Update food's rating in the 'foodRating' map.
foodRatingMap[food] = newRating
// Insert the '(new food rating, food name)' element into the respective cuisine's priority queue.
val cuisineName = foodCuisineMap[food]
cuisineFoodMap[cuisineName]?.add(Food(newRating, food))
}
override fun highestRated(cuisine: String): String {
// Get the highest rated 'food' of 'cuisine'.
var highestRated: Food = cuisineFoodMap[cuisine]?.peek() ?: return ""
// If the latest rating of 'food' doesn't match with the 'rating' on which it was sorted in the priority queue,
// then we discard this element from the priority queue.
while (foodRatingMap[highestRated.foodName] != highestRated.foodRating) {
cuisineFoodMap[cuisine]?.poll()
highestRated = cuisineFoodMap[cuisine]?.peek() ?: return ""
}
// Return the name of the highest-rated 'food' of 'cuisine'.
return highestRated.foodName
}
internal class Food(
var foodRating: Int, // store the food's name.
var foodName: String,
) : Comparable<Food> {
// Implement the compareTo method for comparison
override fun compareTo(other: Food): Int {
// If food ratings are the same, sort based on their names
// (lexicographically smaller name food will be on top)
if (foodRating == other.foodRating) {
return foodName.compareTo(other.foodName)
}
// Sort based on food rating (bigger rating food will be on top)
return -1 * foodRating.compareTo(other.foodRating)
}
}
}
class FoodRatingsSortedSet(foods: Array<String>, cuisines: Array<String>, ratings: IntArray) : FoodRatings {
// Map food with its rating.
private val foodRatingMap: MutableMap<String, Int> = HashMap()
// Map food with cuisine it belongs to.
private val foodCuisineMap: MutableMap<String, String> = HashMap()
// Store all food of a cuisine in set (to sort them on ratings/name)
// Set element -> Pair: (-1 * foodRating, foodName)
private val cuisineFoodMap: MutableMap<String, TreeSet<Pair<Int, String>>> = HashMap()
init {
foodRatings(foods, cuisines, ratings)
}
override fun changeRating(food: String, newRating: Int) {
// Fetch cuisine name for food.
val cuisineName = foodCuisineMap[food]
// Find and delete the element from the respective cuisine's set.
val cuisineSet = cuisineFoodMap.getOrDefault(cuisineName, TreeSet())
val oldElement: Pair<Int, String> = Pair(-foodRatingMap.getOrDefault(food, 0), food)
cuisineSet.remove(oldElement)
// Update food's rating in 'foodRating' map.
foodRatingMap[food] = newRating
// Insert the '(-1 * new rating, name)' element in the respective cuisine's set.
cuisineSet.add(Pair(-newRating, food))
}
override fun highestRated(cuisine: String): String {
val highestRated = cuisineFoodMap.getOrDefault(cuisine, TreeSet()).first()
// Return name of the highest rated 'food' of 'cuisine'.
return highestRated.second
}
private fun foodRatings(foods: Array<String>, cuisines: Array<String>, ratings: IntArray) {
for (i in foods.indices) {
// Store 'rating' and 'cuisine' of current 'food' in 'foodRatingMap' and 'foodCuisineMap' maps.
foodRatingMap[foods[i]] = ratings[i]
foodCuisineMap[foods[i]] = cuisines[i]
// Insert the '(-1 * rating, name)' element in the current cuisine's set.
cuisineFoodMap
.computeIfAbsent(
cuisines[i],
) {
TreeSet<Pair<Int, String>>(
java.util.Comparator { a: Pair<Int, String>, b: Pair<Int, String> ->
val compareByRating = a.first.compareTo(b.first)
if (compareByRating == 0) {
// If ratings are equal, compare by food name (in ascending order).
return@Comparator a.second.compareTo(b.second)
}
compareByRating
},
)
}
.add(Pair(-ratings[i], foods[i]))
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 6,598 | kotlab | Apache License 2.0 |
src/Day04.kt | cak | 573,455,947 | false | {"Kotlin": 8236} | fun main() {
fun part1(input: List<String>): Int {
val data = input.map { j ->
j.split(",")
.map { k ->
k.split("-")
.map { it.toInt() }
}
.map { (it.first()..it.last()).toList() }
}.filter { it.first().containsAll(it.last()) || it.last().containsAll(it.first()) }
return data.size
}
fun part2(input: List<String>): Int {
val data = input.map { j ->
j.split(",")
.map { k ->
k.split("-")
.map { it.toInt() }
}
.map { (it.first()..it.last()).toList() }
}.filter {
it.first().intersect(it.last().toSet()).toSet().isNotEmpty()
}
return data.size
}
val testInput = getTestInput()
check(part1(testInput) == 2)
val input = getInput()
println(part1(input))
check(part2(testInput) == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | cab2dffae8c1b78405ec7d85e328c514a71b21f1 | 1,024 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | rdbatch02 | 575,174,840 | false | {"Kotlin": 18925} | import java.util.EmptyStackException
import java.util.Stack
import kotlin.Error
data class CrateMove(val quantity: Int, val source: Int, val dest: Int)
fun main() {
fun parseCurrentStacks(input: List<String>): List<Stack<String>> {
val endLineIdx = input.indexOfFirst { it.isEmpty() }
val endLine = input[endLineIdx - 1]
val numberOfStacks = endLine.trim().split(" ").last().toInt()
val stacks: List<Stack<String>> = List(numberOfStacks) { Stack() }
input.subList(0, endLineIdx).reversed().forEach {line ->
Regex("(^\\s{3}|\\s{4}|[A-Z])").findAll(line).toList().forEachIndexed { index, matchResult ->
if (matchResult.value.isNotBlank()) {
stacks[index].push(matchResult.value)
}
}
}
return stacks
}
fun parseMoves(input: List<String>): List<CrateMove> {
val separatorLineIdx = input.indexOfFirst { it.isEmpty() }
val moveList = input.subList(separatorLineIdx + 1, input.size)
return moveList.map {
val matchedValues = Regex("move (\\d+) from (\\d+) to (\\d+)").find(it)?.groupValues ?: throw Error("Error parsing moves")
CrateMove(matchedValues[1].toInt(), matchedValues[2].toInt(), matchedValues[3].toInt())
}
}
fun printStacks(input: List<Stack<String>>) {
val stacks = input.toList() // Make deep copy
var currentDepth = stacks.maxOf { it.size }
while (stacks.last().isNotEmpty()) {
stacks.forEach {
if (it.size < currentDepth) {
print(" ")
}
else {
print(it.pop() + " ")
}
}
println("")
currentDepth--
}
println("1 2 3 4 5 6 7 8 9")
}
fun part1(input: List<String>): List<Stack<String>> {
val stacks = parseCurrentStacks(input)
val moves = parseMoves(input)
moves.forEach { move ->
for (i in 0 until move.quantity) {
stacks[move.dest - 1].push(stacks[move.source - 1].pop())
}
}
return stacks
}
fun part2(input: List<String>): List<Stack<String>> {
val stacks = parseCurrentStacks(input)
val moves = parseMoves(input)
moves.forEach { move ->
val moveStack = Stack<String>()
for (i in 0 until move.quantity) {
moveStack.push(stacks[move.source - 1].pop())
}
while (moveStack.isNotEmpty()) {
stacks[move.dest - 1].push(moveStack.pop())
}
}
return stacks
}
val input = readInput("Day05")
println("Part 1: ")
printStacks(part1(input))
println("Part 2: ")
printStacks(part2(input))
}
| 0 | Kotlin | 0 | 1 | 330a112806536910bafe6b7083aa5de50165f017 | 2,844 | advent-of-code-kt-22 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/HighFive.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.extensions.second
import java.util.PriorityQueue
import java.util.TreeMap
private const val CAPACITY = 5
private const val SIZE = 2
fun interface HighFiveStrategy {
operator fun invoke(items: Array<IntArray>): Array<IntArray>
}
class HighFivePriorityQueue : HighFiveStrategy {
override operator fun invoke(items: Array<IntArray>): Array<IntArray> {
val map: TreeMap<Int, PriorityQueue<Int>> = TreeMap<Int, PriorityQueue<Int>>()
for (item in items) {
val id = item.first()
val score = item.second()
if (!map.containsKey(id)) {
val pq: PriorityQueue<Int> = PriorityQueue<Int>(CAPACITY)
pq.offer(score)
map[id] = pq
} else {
val pq: PriorityQueue<Int> = map[id] ?: break
pq.offer(score)
if (pq.size > CAPACITY) {
pq.poll()
}
map[id] = pq
}
}
val res = Array(map.size) { IntArray(SIZE) }
for ((index, id) in map.keys.withIndex()) {
res[index][0] = id
val pq: PriorityQueue<Int> = map[id] ?: break
var sum = 0
val size: Int = pq.size
while (pq.isNotEmpty()) {
sum += pq.poll()
}
res[index][1] = sum / size
}
return res
}
}
class HighFiveSort : HighFiveStrategy {
override operator fun invoke(items: Array<IntArray>): Array<IntArray> {
items.sortWith { t1, t2 ->
// put item[id, score] with same id together
// for each id/student, item[id, score] is ordered by score (increasing)
if (t1[0] == t2[0]) {
t2[1] - t1[1]
} else {
t1[0] - t2[0]
}
}
val s: Int = items.size
// The list temp helps to calculate how many students/ids are there
val temp: MutableList<IntArray> = ArrayList()
var i = 0
while (i < s) {
val id = items[i][0]
var count = CAPACITY
var sum = 0
while (i < s && count-- > 0) {
sum += items[i][1]
i++
}
temp.add(intArrayOf(id, sum / CAPACITY))
// skip scores that are not the 'HighFive' for a student
while (i < s && items[i][0] == id) i++
}
val size = temp.size
val res = Array(size) { IntArray(SIZE) }
for (j in 0 until size) {
res[j] = temp[j]
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,279 | kotlab | Apache License 2.0 |
src/Day11.kt | aneroid | 572,802,061 | false | {"Kotlin": 27313} | class Day11(input: List<String>) {
private var worryReducer = { it: Long -> it / 3 }
private val monkeys: List<Monkey> = parseInput(input)
private fun printMonkeyItems(round: Int = 0) {
if (round != 0) {
println("After round $round:")
}
monkeys.forEachIndexed { index, monkey ->
println("Monkey $index: ${monkey.itemLevels} | ${monkey.inspected}")
}
println()
}
private fun doRound() {
monkeys.forEach { monkey ->
monkey.see().map { monkey.`do`(it) }
}
}
private fun Monkey.see() =
buildList {
while (itemLevels.isNotEmpty()) {
inspected++
itemLevels.removeFirst().let(changeLevel).let(worryReducer).also(::add)
}
}
private fun Monkey.`do`(level: Long) {
val throwTo = if (level % testDivBy == 0L) throwTrue else throwFalse
monkeys[throwTo].itemLevels.addLast(level)
}
private fun solve(repetitions: Int): Long {
printMonkeyItems()
repeat(repetitions) {
doRound()
// printMonkeyItems(it + 1)
}
printMonkeyItems()
return monkeys.map(Monkey::inspected).sortedDescending().take(2).map(Int::toLong).reduce(Long::times)
}
fun partOne(): Long = solve(20)
fun partTwo(repetitions: Int): Long {
val factor = monkeys.map(Monkey::testDivBy).also { println(it) }.reduce(Int::times)
println("Factor: $factor")
worryReducer = { it % factor }
return solve(repetitions)
}
private companion object {
class Monkey(
val itemLevels: ArrayDeque<Long>,
val changeLevel: (Long) -> Long,
val testDivBy: Int,
val throwTrue: Int,
val throwFalse: Int,
var inspected: Int = 0,
)
fun parseInput(input: List<String>) =
input.chunked(7).map { lines ->
Monkey(
lines[1].substringAfter("items: ").split(", ").map(String::toLong).let(::ArrayDeque),
lines[2].substringAfter("= ").toOperation(),
lines[3].substringAfter("by ").toInt(),
lines[4].substringAfter("monkey ").toInt(),
lines[5].substringAfter("monkey ").toInt(),
)
}
fun String.toOperation(): (Long) -> Long {
val arg1 = substringBefore(" ").toLongOrNull()
val arg2 = substringAfterLast(" ").toLongOrNull()
val operator: (Long, Long) -> Long = when (substringAfter(" ").substringBefore(" ")) {
"+" -> Long::plus
"-" -> Long::minus
"*" -> Long::times
"/" -> Long::div
else -> throw IllegalArgumentException("Unknown operation: $this")
}
return { old: Long -> operator(arg1 ?: old, arg2 ?: old) }
}
}
}
fun main() {
val testInput = readInput("Day11_test")
val input = readInput("Day11")
println("part One:")
assertThat(Day11(testInput).partOne()).isEqualTo(10605)
println("actual: ${Day11(input).partOne()}\n")
println("part Two:")
assertThat(Day11(testInput).partTwo(20)).isEqualTo(99 * 103)
assertThat(Day11(testInput).partTwo(1_000)).isEqualTo(5204 * 5192)
assertThat(Day11(testInput).partTwo(2_000)).isEqualTo(10419 * 10391)
assertThat(Day11(testInput).partTwo(10_000)).isEqualTo(52166 * 52013L)
println("actual: ${Day11(input).partTwo(10_000)}\n")
}
| 0 | Kotlin | 0 | 0 | cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd | 3,664 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/day02/Day02.kt | violabs | 576,367,139 | false | {"Kotlin": 10620} | package day02
import readInput
fun main() {
test1("day-02-test-input-01", 15)
test2("day-02-test-input-01", 12)
}
private fun test1(filename: String, expected: Int) {
val input = readInput("day02/$filename")
val actual: Int = runGuessingGame(input)
println("EXPECT: $expected")
println("ACTUAL: $actual")
check(expected == actual)
}
private fun test2(filename: String, expected: Int) {
val input = readInput("day02/$filename")
val actual: Int = runKnownGame(input)
println("EXPECT: $expected")
println("ACTUAL: $actual")
check(expected == actual)
}
enum class Shape(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
companion object {
val symbolMap: Map<String, Shape> = mapOf(
"A" to ROCK,
"X" to ROCK,
"B" to PAPER,
"Y" to PAPER,
"C" to SCISSORS,
"Z" to SCISSORS
)
fun findShape(opponentShape: Shape, outcome: Outcome): Shape = when (outcome) {
Outcome.LOSE -> findShapeForLose(opponentShape)
Outcome.DRAW -> opponentShape
Outcome.WIN -> findShapeForWin(opponentShape)
}
private fun findShapeForLose(opponentShape: Shape): Shape = when (opponentShape) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
private fun findShapeForWin(opponentShape: Shape): Shape = when (opponentShape) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
}
enum class Outcome(val score: Int) {
LOSE(0),
DRAW(3),
WIN(6);
companion object {
val symbolMap: Map<String, Outcome> = mapOf(
"X" to LOSE,
"Y" to DRAW,
"Z" to WIN
)
fun findOutcome(opponentShape: Shape, selfShape: Shape): Outcome = when (opponentShape) {
Shape.ROCK -> findOutcomeAgainstRock(selfShape)
Shape.PAPER -> findOutcomeAgainstPaper(selfShape)
Shape.SCISSORS -> findOutcomeAgainstScissors(selfShape)
}
private fun findOutcomeAgainstRock(selfShape: Shape): Outcome = when (selfShape) {
Shape.ROCK -> DRAW
Shape.PAPER -> WIN
Shape.SCISSORS -> LOSE
}
private fun findOutcomeAgainstPaper(selfShape: Shape): Outcome = when (selfShape) {
Shape.ROCK -> LOSE
Shape.PAPER -> DRAW
Shape.SCISSORS -> WIN
}
private fun findOutcomeAgainstScissors(selfShape: Shape): Outcome = when (selfShape) {
Shape.ROCK -> WIN
Shape.PAPER -> LOSE
Shape.SCISSORS -> DRAW
}
}
}
private fun runGuessingGame(input: List<String>): Int {
return input
.asSequence()
.map { it.split(" ") }
.map(::GuessedRound)
.map(GuessedRound::score)
.sum()
}
class GuessedRound(selections: List<String>) {
private val opponentShape: Shape = Shape.symbolMap[selections[0]] ?: throw Exception("Missing opponent selection")
private val myShape: Shape = Shape.symbolMap[selections[1]] ?: throw Exception("Missing my selection")
private val outcome: Outcome = Outcome.findOutcome(opponentShape, myShape)
val score: Int = myShape.score + outcome.score
}
private fun runKnownGame(input: List<String>): Int {
return input
.asSequence()
.map { it.split(" ") }
.map(::KnownRound)
.map(KnownRound::score)
.sum()
}
class KnownRound(selections: List<String>) {
private val opponentShape: Shape = Shape.symbolMap[selections[0]] ?: throw Exception("Missing opponent selection")
private val outcome: Outcome = Outcome.symbolMap[selections[1]] ?: throw Exception("Missing outcome")
private val myShape: Shape = Shape.findShape(opponentShape, outcome)
val score: Int = myShape.score + outcome.score
} | 0 | Kotlin | 0 | 0 | be3d6bb2aef1ebd44bbd8e62d3194c608a5b3cc1 | 3,932 | AOC-2022 | Apache License 2.0 |
RomanToInteger.kt | ncschroeder | 604,822,497 | false | {"Kotlin": 19399} | /*
https://leetcode.com/problems/roman-to-integer/
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is
before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
- I can be placed before V (5) and X (10) to make 4 and 9.
- X can be placed before L (50) and C (100) to make 40 and 90.
- C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
*/
fun romanToInt(s: String): Int {
// First, identify the subtraction sequences in s. Remove them and increment subtractionSequencesSum by their values.
// Then, get the sum of the corresponding values for the numerals in updatedNumeral and add that to substractionSequencesSum.
var updatedNumeral = s
var subtractionSequencesSum = 0
arrayOf(
Pair("IV", 4),
Pair("IX", 9),
Pair("XL", 40),
Pair("XC", 90),
Pair("CD", 400),
Pair("CM", 900)
)
.forEach { (subtractionSequence, value) ->
if (subtractionSequence in updatedNumeral) {
subtractionSequencesSum += value
updatedNumeral = updatedNumeral.replace(subtractionSequence, "")
}
}
val numeralValues =
mapOf(
'I' to 1,
'V' to 5,
'X' to 10,
'L' to 50,
'C' to 100,
'D' to 500,
'M' to 1000
)
return subtractionSequencesSum + updatedNumeral.sumOf(numeralValues::getValue)
} | 0 | Kotlin | 0 | 0 | c77d0c8bb0595e61960193fc9b0c7a31952e8e48 | 2,098 | Coding-Challenges | MIT License |
src/main/kotlin/com/github/shmvanhouten/adventofcode/day11/ChipAndGeneratorDistributor.kt | SHMvanHouten | 109,886,692 | false | {"Kotlin": 616528} | package com.github.shmvanhouten.adventofcode.day11
class ChipAndGeneratorDistributor (var elevatorLvl: Int = 1){
private val AMOUNT_OF_STEPS_IT_TAKES_TO_MOVE_FIRST_TWO_SETS_OF_COMPONENTS_UP_ONE_FLOOR = 5
private val STEPS_PER_SET_OF_COMPONENTS = 4
fun findQuickestWayToTop(floorsInput: Map<Int, Pair<List<Chip>, List<Generator>>>): Int {
var stepCounter = 0
var floors = floorsInput
while(floors.count { it.value.first.isNotEmpty() || it.value.second.isNotEmpty() } > 1){
if(elevatorLvl - 1 > 0 && floors[elevatorLvl - 1]!!.isNotEmpty()){
//go down to fetch next component
val unconnectedComponents: List<Component> = floors[elevatorLvl]!!.findUnmatchedComponents()
if(unconnectedComponents.isEmpty()){
// move down the first generator
}else {
//check if the components counterpart is down, otherwise is not relevant
}
elevatorLvl--
}else{
// bring up 2 components
moveUpComponent(floors, elevatorLvl)
elevatorLvl++
}
stepCounter++
}
val floorAllComponentsAreOn: Int? = floors.keys.find { floors[it]!!.isNotEmpty() }
val amountOfElementTypes = floors[floorAllComponentsAreOn]!!.first.size
val amountOfStepsToTheTop = 4 - floorAllComponentsAreOn!!
return stepCounter + (AMOUNT_OF_STEPS_IT_TAKES_TO_MOVE_FIRST_TWO_SETS_OF_COMPONENTS_UP_ONE_FLOOR
+ STEPS_PER_SET_OF_COMPONENTS * (amountOfElementTypes - 2)) * amountOfStepsToTheTop
}
private fun moveUpComponent(floors: Map<Int, Pair<List<Chip>, List<Generator>>>, elevatorLvl: Int) {
val componentsWithCounterPartsOnNextLvl = floors[elevatorLvl]!!.getComponentsPairedWithOtherLvl(floors[elevatorLvl + 1]!!)
when {
componentsWithCounterPartsOnNextLvl.size >= 2 -> {/*move the first 2 of these up*/}
componentsWithCounterPartsOnNextLvl.size == 1 -> {}
else -> {}
}
}
}
private fun Pair<List<Component>, List<Component>>.getComponentsPairedWithOtherLvl(other: Pair<List<Component>, List<Component>>): List<Component> {
val pairedChips = this.first.filter { isLinkedComponentInOtherList(it, other.second) }
val pairedGenerator = this.second.filter { isLinkedComponentInOtherList(it, other.first) }
return pairedChips.union(pairedGenerator).toList()
}
private fun Pair<List<Component>, List<Component>>.findUnmatchedComponents(): List<Component> {
val unpairedChips = this.first.filterNot { isLinkedComponentInOtherList(it, this.second) }
val unpairedGenerators = this.second.filterNot { isLinkedComponentInOtherList(it, this.first) }
return unpairedChips.union(unpairedGenerators).toList()
}
fun isLinkedComponentInOtherList(component: Component, otherComponents: List<Component>): Boolean =
otherComponents.any { it.elementType == component.elementType }
private fun Pair<List<Component>, List<Component>>.isNotEmpty(): Boolean =
this.first.isNotEmpty() || this.second.isNotEmpty()
| 0 | Kotlin | 0 | 0 | a8abc74816edf7cd63aae81cb856feb776452786 | 3,168 | adventOfCode2016 | MIT License |
src/main/kotlin/day20.kt | p88h | 317,362,882 | false | null | internal fun bswap(code: Int): Int {
return (0 until 10).fold(0) { r, i -> r * 2 + if (code and (1 shl i) != 0) 1 else 0 }
}
internal val monster = arrayListOf(
" @ ".toCharArray(),
"* __ __ ()>".toCharArray(),
" \\ / \\ / \\ / ".toCharArray()
)
internal data class Tile(val id: Long, var area: ArrayList<CharArray>, val dim: Int = 10) {
init {
if (area.isEmpty()) area = ArrayList((0 until dim).map { CharArray(dim) { ' ' } })
}
fun code(side: Char): Int {
when (side) {
'T' -> return (0 until 10).fold(0) { r, i -> r * 2 + if (area[0][i] == '#') 1 else 0 }
'R' -> return (0 until 10).fold(0) { r, i -> r * 2 + if (area[i][9] == '#') 1 else 0 }
'B' -> return (0 until 10).fold(0) { r, i -> r * 2 + if (area[9][i] == '#') 1 else 0 }
'L' -> return (0 until 10).fold(0) { r, i -> r * 2 + if (area[i][0] == '#') 1 else 0 }
}
throw IllegalArgumentException()
}
fun scan(pattern: List<CharArray>): Int {
var cnt = 0
for (y in 0..dim - pattern.size) {
for (x in 0..dim - pattern[0].size) {
var match = true
for (i in pattern.indices) {
for (j in pattern[i].indices) {
if (pattern[i][j] != ' ' && area[y + i][x + j] == '.') match = false
}
}
if (match) {
for (i in pattern.indices) {
for (j in pattern[i].indices) {
if (pattern[i][j] != ' ') area[y + i][x + j] = pattern[i][j]
}
}
cnt++
}
}
}
return cnt
}
fun rotate() {
var rot = ArrayList<CharArray>(area.size)
for (i in area.indices) {
rot.add(CharArray(area[i].size))
for (j in area.indices) rot[i][j] = area[(dim - 1) - j][i]
}
area = rot
}
fun flipX() {
for (i in area.indices) area[i].reverse()
}
fun flipY() {
area.reverse()
}
fun align(side: Char, expected: Int) {
while (code(side) != expected) {
if (code(side) == bswap(expected)) when (side) {
'L', 'R' -> flipY()
'T', 'B' -> flipX()
} else rotate()
}
}
var neighbors = ArrayList<Int>()
var pos = Point(0, 0)
var cache = HashSet<Int>()
}
fun main(args: Array<String>) {
val fmt = "Tile (\\d+):".toRegex()
var sides = arrayListOf('L', 'T', 'B', 'R')
var tiles = allBlocks(args, "day20.in").map {
val lines = it.split('\n')
val id = fmt.matchEntire(lines.first())!!.groupValues[1].toLong()
Tile(id, ArrayList<CharArray>(lines.subList(1, 11).map { it.toCharArray() }))
}
var codes = HashMap<Int, Int>()
for (i in tiles.indices) {
for (side in sides) {
var code = tiles[i].code(side)
if (codes.containsKey(code)) {
tiles[i].neighbors.add(codes[code]!!)
tiles[codes[code]!!].neighbors.add(i)
}
tiles[i].cache.add(code)
codes[code] = i
code = bswap(code)
tiles[i].cache.add(code)
codes[code] = i
}
}
println(tiles.fold(1L) { r, t -> if (t.neighbors.size == 2) r * t.id else r })
var cur = tiles.indices.fold(0) { r, t -> if (tiles[t].neighbors.size < tiles[r].neighbors.size) t else r }
val nnc = tiles[cur].neighbors.flatMap { tiles[it].cache }.toHashSet()
val lc = tiles[cur].code('L')
if (nnc.contains(lc)) tiles[cur].flipX()
val tc = tiles[cur].code('T')
if (nnc.contains(tc)) tiles[cur].flipY()
var visited = arrayListOf(cur)
while (true) {
val rc = tiles[cur].code('R')
cur = tiles[cur].neighbors.firstOrNull { tiles[it].cache.contains(rc) } ?: break
tiles[cur].align('L', rc)
tiles[cur].pos.x = visited.size
visited.add(cur)
}
var idx = 0
while (visited.size < tiles.size) {
cur = visited[idx]
val bc = tiles[cur].code('B')
val next = tiles[cur].neighbors.first { tiles[it].cache.contains(bc) }
tiles[next].align('T', bc)
tiles[next].pos = tiles[cur].pos + Point(0, 1)
visited.add(next)
idx += 1
}
var map = Tile(0, ArrayList(), 8 * Math.sqrt(tiles.size.toDouble()).toInt())
println("Building map dim=${map.dim}")
for (t in tiles.indices) for (y in 1..8) for (x in 1..8) {
map.area[tiles[t].pos.y * 8 + y - 1][tiles[t].pos.x * 8 + x - 1] = tiles[t].area[y][x]
}
for (t in 1..7) {
val cnt = map.scan(monster)
println("try $t: $cnt")
if (cnt > 0) break
if (t == 4) map.flipY() else map.rotate()
}
for (k in 0 until map.dim) println(map.area[k])
println(map.area.map { it.count { c -> c == '#' } }.sum())
}
| 0 | Kotlin | 0 | 5 | 846ad4a978823563b2910c743056d44552a4b172 | 5,014 | aoc2020 | The Unlicense |
src/main/kotlin/daythree/DayThree.kt | pauliancu97 | 619,525,509 | false | null | package daythree
import getLines
private fun getItemPriority(char: Char): Int =
if (char.isLowerCase()) {
char.code - 'a'.code + 1
} else {
char.code - 'A'.code + 27
}
private fun getMissplacedPackagePriority(rucksack: String): Int {
val firstCompartmentItems = rucksack.substring(0 until (rucksack.length / 2)).toSet()
val secondCompartmentItems = rucksack.substring((rucksack.length / 2) until rucksack.length).toSet()
val firstCommonItem = (firstCompartmentItems intersect secondCompartmentItems).first()
return getItemPriority(firstCommonItem)
}
private fun getTotalPriorities(rucksacks: List<String>) =
rucksacks.sumOf { getMissplacedPackagePriority(it) }
private fun solvePartOne() {
val rucksacks = getLines("day_3.txt")
println(getTotalPriorities(rucksacks))
}
private fun getPriorityForGroup(group: List<String>): Int {
var currentSet = group.first().toSet()
for (rucksack in group.drop(1)) {
val distinctItems = rucksack.toSet()
currentSet = currentSet intersect distinctItems
}
return getItemPriority(currentSet.first())
}
private fun getTotalPriorityForGroups(rucksacks: List<String>, groupSize: Int): Int {
var totalPriority = 0
var currentRucksacks = rucksacks
while (currentRucksacks.isNotEmpty()) {
val priority = getPriorityForGroup(currentRucksacks.take(groupSize))
totalPriority += priority
currentRucksacks = currentRucksacks.drop(groupSize)
}
return totalPriority
}
private fun solvePartTwo() {
val rucksacks = getLines("day_3.txt")
println(getTotalPriorityForGroups(rucksacks, 3))
}
fun main() {
//solvePartOne()
solvePartTwo()
} | 0 | Kotlin | 0 | 0 | 78af929252f094a34fe7989984a30724fdb81498 | 1,709 | advent-of-code-2022 | MIT License |
src/day04/Day04.kt | marcBrochu | 573,884,748 | false | {"Kotlin": 12896} | package day04
import readInput
data class Range(val min:Int, val max: Int) {
fun fullyContains(otherRange: Range): Boolean =
this.min <= otherRange.min && this.max >= otherRange.max
fun overlap(otherRange: Range): Boolean =
(this.min >= otherRange.min && this.min <= otherRange.max)
|| (this.max >= otherRange.min && this.max <= otherRange.max)
|| fullyContains(otherRange)
}
fun main() {
fun parseInput(input: List<String>) = input.map {
val firstSection = it.substringBefore(",")
val secondSection = it.substringAfter(",")
Pair(
Range(
firstSection.substringBefore("-").toInt(),
firstSection.substringAfter("-").toInt()
),
Range(
secondSection.substringBefore("-").toInt(),
secondSection.substringAfter("-").toInt()
)
)
}
fun part1(input: List<String>): Int {
return parseInput(input).count { pair ->
pair.first.fullyContains(pair.second) || pair.second.fullyContains(pair.first)
}
}
fun part2(input: List<String>): Int {
return parseInput(input).count { pair ->
pair.first.overlap(pair.second)
}
}
val input = readInput("day04/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 8d4796227dace8b012622c071a25385a9c7909d2 | 1,384 | advent-of-code-kotlin | Apache License 2.0 |
src/main/java/com/ncorti/aoc2021/Exercise04.kt | cortinico | 433,486,684 | false | {"Kotlin": 36975} | package com.ncorti.aoc2021
object Exercise04 {
private fun getInput(): Pair<List<Int>, List<Array<IntArray>>> =
getInputAsTest("04") { split("\n") }.let { lines ->
val calls = lines[0].split(",").map(String::toInt)
val boards =
lines
.asSequence()
.drop(2)
.map(String::trim)
.filter(String::isNotBlank)
.withIndex()
.groupBy { line -> line.index / 5 }
.map { (_, lines) ->
Array(5) { i ->
val line = lines[i].value.split(" ").filter(String::isNotBlank)
IntArray(5) { j -> line[j].toInt() }
}
}
.toList()
calls to boards
}
private fun checkBingo(board: Array<IntArray>, row: Int, col: Int): Boolean =
board[row].all { it == -1 } || board.map { it[col] }.all { it == -1 }
fun part1(): Int {
val (calls, boards) = getInput()
calls.forEach { call ->
boards.forEach { board ->
val row: Int = board.indexOfFirst { row -> call in row }
val col: Int = if (row == -1) -1 else board[row].indexOfFirst { it == call }
if (row != -1 && col != -1) {
board[row][col] = -1
if (checkBingo(board, row, col)) {
return call * board.sumOf { it.filter { it != -1 }.sum() }
}
}
}
}
error("Bingo never happened!")
}
fun part2(): Int {
val (calls, boardsArray) = getInput()
val boards = boardsArray.toMutableList()
calls.forEach { call ->
val boardsToRemove = mutableSetOf<Array<IntArray>>()
for (i in boards.indices) {
val board = boards[i]
val row: Int = board.indexOfFirst { row -> call in row }
val col: Int = if (row == -1) -1 else board[row].indexOfFirst { it == call }
if (row != -1 && col != -1) {
board[row][col] = -1
if (checkBingo(board, row, col)) {
if (boards.size == 1) {
return call * board.sumOf { it.filter { it != -1 }.sum() }
} else {
boardsToRemove.add(board)
}
}
}
}
boardsToRemove.forEach { boards.remove(it) }
}
error("Last board not found!")
}
}
fun main() {
println(Exercise04.part1())
println(Exercise04.part2())
}
| 0 | Kotlin | 0 | 4 | af3df72d31b74857201c85f923a96f563c450996 | 2,775 | adventofcode-2021 | MIT License |
src/Day02.kt | Iamlooker | 573,103,288 | false | {"Kotlin": 5744} | fun main() {
/**
*
* Part 1:
* A or X -> Rock -> 1
* B or Y -> Paper -> 2
* C or Z -> Scissor -> 3
*
* Part 2:
* X -> Lose -> 0
* Y -> Draw -> 3
* Z -> Win -> 6
*/
val pointsTable = mapOf(
'A' to 1, 'B' to 2, 'C' to 3
)
val part1YourPointTable = mapOf(
'X' to 1, 'Y' to 2, 'Z' to 3
)
fun rockPaperScissorPart1(opponent: Char, yourMove: Char): Int = when (opponent) {
'A' -> part1YourPointTable[yourMove]!!.plus(
when (yourMove) {
'X' -> 3
'Y' -> 6
'Z' -> 0
else -> -1
}
)
'B' -> part1YourPointTable[yourMove]!!.plus(
when (yourMove) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> -1
}
)
'C' -> part1YourPointTable[yourMove]!!.plus(
when (yourMove) {
'X' -> 6
'Y' -> 0
'Z' -> 3
else -> -1
}
)
else -> -1
}
fun rockPaperScissorPart2(opponent: Char, situation: Char): Int = when (opponent) {
'A' -> when (situation) {
'X' -> pointsTable['C']!!.plus(0)
'Y' -> pointsTable['A']!!.plus(3)
'Z' -> pointsTable['B']!!.plus(6)
else -> -1
}
'B' -> when (situation) {
'X' -> pointsTable['A']!!.plus(0)
'Y' -> pointsTable['B']!!.plus(3)
'Z' -> pointsTable['C']!!.plus(6)
else -> -1
}
'C' -> when (situation) {
'X' -> pointsTable['B']!!.plus(0)
'Y' -> pointsTable['C']!!.plus(3)
'Z' -> pointsTable['A']!!.plus(6)
else -> -1
}
else -> -1
}
fun part1(input: List<String>): Int = input.sumOf {
rockPaperScissorPart1(it.first(), it.last())
}
fun part2(input: List<String>): Int = input.sumOf {
rockPaperScissorPart2(it.first(), it.last())
}
// val testInput = readInput("Day02_test")
// println(part2(testInput))
// val input = readInput("Day02")
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 91a335428a99db2f2b1fd5c5f51a6b1e55ae2245 | 2,232 | aoc-2022-kotlin | Apache License 2.0 |
src/Day04.kt | yeung66 | 574,904,673 | false | {"Kotlin": 8143} | fun main() {
fun parse(input: String): List<List<List<Int>>> {
return input.lines().map { line -> line.split(",").map { range -> range.split("-").map {it.toInt()}} }.toList()
}
fun part1(input: List<List<List<Int>>>): Int {
return input.map {
val (a, b) = it
if (a[0] >= b[0] && a[1] <= b[1] || b[0] >= a[0] && b[1] <= a[1]) 1 else 0
}.sum()
}
fun part2(input: List<List<List<Int>>>): Int {
return input.map {
val (a, b) = it
if (a[1] < b[0] || b[1] < a[0]) 0 else 1
}.sum()
}
val input = parse(readInput("4"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 554217f83e81021229759bccc8b616a6b270902c | 684 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day08.kt | andydenk | 573,909,669 | false | {"Kotlin": 24096} | fun main() {
// 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("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<String>): Int {
return TreetopLocator.forInput(input).locateVisibleTrees().size
}
private fun part2(input: List<String>): Int {
return TreetopLocator.forInput(input).highestScenicScore()
}
private class TreetopLocator(val treeMap: Map<Pair<X, Y>, Tree>, val arrayDimension: Int) {
private val visibleTrees: MutableSet<Pair<X, Y>> = mutableSetOf()
fun locateVisibleTrees(): Set<Pair<X, Y>> {
var highestFromLeft: Int
var highestFromRight: Int
var highestFromTop: Int
var highestFromBottom: Int
for (i in 0..arrayDimension) {
highestFromLeft = -1
highestFromRight = -1
highestFromTop = -1
highestFromBottom = -1
for (j in 0..arrayDimension) {
highestFromLeft = handleDirection(highestSoFar = highestFromLeft, x = j, y = i)
highestFromRight = handleDirection(highestSoFar = highestFromRight, x = arrayDimension - j, y = i)
highestFromTop = handleDirection(highestSoFar = highestFromTop, x = i, y = j)
highestFromBottom = handleDirection(highestSoFar = highestFromBottom, x = i, y = arrayDimension - j)
if (highestFromLeft == 9 && highestFromRight == 9 && highestFromTop == 9 && highestFromBottom == 9) {
break //possibly we can exit early
}
}
}
return visibleTrees
}
fun highestScenicScore(): Int {
return treeMap.maxOf { it.value.calculateScenicScore() }
}
private fun Tree.calculateScenicScore(): Int {
var leftSpace = 0
var rightSpace = 0
var topSpace = 0
var bottomSpace = 0
var leftFree = true
var rightFree = true
var topFree = true
var bottomFree = true
for (i in 1 until arrayDimension) {
rightFree = checkVisibility(x = x + i, y = y).takeIf { rightFree }?.apply { rightSpace++ } ?: rightFree
leftFree = checkVisibility(x = x - i, y = y).takeIf { leftFree }?.apply { leftSpace++ } ?: leftFree
topFree = checkVisibility(x = x, y = y + i).takeIf { topFree }?.apply { topSpace++ } ?: topFree
bottomFree = checkVisibility(x = x, y = y - i).takeIf { bottomFree }?.apply { bottomSpace++ } ?: bottomFree
}
return leftSpace * rightSpace * topSpace * bottomSpace
}
private fun Tree.checkVisibility(x: Int, y: Int): Boolean {
return if (x <= 0 || y <= 0 || x >= arrayDimension || y >= arrayDimension) {
false
} else {
treeMap.getValue(x to y).height < height
}
}
private fun handleDirection(x: Int, y: Int, highestSoFar: Int): Int {
if (highestSoFar == 9) { //can't get any higher
return highestSoFar
}
val location = x to y
val tree = treeMap.getValue(location)
return if (tree.height > highestSoFar) {
visibleTrees.add(location)
return tree.height
} else {
highestSoFar
}
}
companion object {
fun forInput(treeGrid: List<String>): TreetopLocator {
val treeMap: Map<Pair<X, Y>, Tree> = treeGrid
.flatMapIndexed { y, line ->
line.toList()
.mapIndexed { x, height -> (x to y) to Tree(x, y, height.digitToInt()) }
}.associate { it }
return TreetopLocator(treeMap = treeMap, arrayDimension = treeGrid.size - 1)
}
}
}
private typealias X = Int
private typealias Y = Int
private data class Tree(val x: Int, val y: Int, val height: Int)
| 0 | Kotlin | 0 | 0 | 1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1 | 4,007 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/kr/co/programmers/P81302.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/363
class P81302 {
fun solution(places: Array<Array<String>>): IntArray {
val answer = IntArray(places.size)
for (i in places.indices) answer[i] = place(places[i])
return answer
}
private fun place(place: Array<String>): Int {
val box = Array(9) { CharArray(9) { 'X' } }.apply {
for (r in 0 until 5) {
for (c in 0 until 5) {
this[r + 2][c + 2] = place[r][c]
}
}
}
for (r in 2 until box.size - 2) {
for (c in 2 until box[r].size - 2) {
if (check(box, r, c)) return 0
}
}
return 1
}
private fun check(box: Array<CharArray>, r: Int, c: Int): Boolean {
if (box[r][c] != 'P') return false
return when { // box[r][c] == 'P'
box[r - 1][c] == 'P' -> true
box[r][c + 1] == 'P' -> true
box[r + 1][c] == 'P' -> true
box[r][c - 1] == 'P' -> true
box[r - 2][c] == 'P' && box[r - 1][c] == 'O' -> true
box[r][c + 2] == 'P' && box[r][c + 1] == 'O' -> true
box[r + 2][c] == 'P' && box[r + 1][c] == 'O' -> true
box[r][c - 2] == 'P' && box[r][c - 1] == 'O' -> true
box[r - 1][c - 1] == 'P' && (box[r - 1][c] != 'X' || box[r][c - 1] != 'X') -> return true
box[r - 1][c + 1] == 'P' && (box[r - 1][c] != 'X' || box[r][c + 1] != 'X') -> return true
box[r + 1][c + 1] == 'P' && (box[r + 1][c] != 'X' || box[r][c + 1] != 'X') -> return true
box[r + 1][c - 1] == 'P' && (box[r + 1][c] != 'X' || box[r][c - 1] != 'X') -> return true
else -> false
}
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,791 | algorithm | MIT License |
year2022/src/main/kotlin/net/olegg/aoc/year2022/day15/Day15.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2022.day15
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.year2022.DayOf2022
import kotlin.math.abs
/**
* See [Year 2022, Day 15](https://adventofcode.com/2022/day/15)
*/
object Day15 : DayOf2022(15) {
private val PATTERN = "^Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)$".toRegex()
override fun first(): Any? {
val tuples = lines
.mapNotNull { PATTERN.find(it) }
.map { match -> match.destructured.toList().map { it.toInt() } }
.map { coords ->
val sensor = Vector2D(coords[0], coords[1])
val beacon = Vector2D(coords[2], coords[3])
Triple(sensor, beacon, (sensor - beacon).manhattan())
}
val beacons = tuples.map { it.second }.toSet()
val sensors = tuples.map { it.first to it.third }
val maxDist = tuples.maxOf { it.third } + 1
val minX = tuples.minOf { minOf(it.first.x, it.second.x) } - maxDist
val maxX = tuples.maxOf { maxOf(it.first.x, it.second.x) } + maxDist
val y = 2000000
return (minX..maxX)
.asSequence()
.map { Vector2D(it, y) }
.filterNot { it in beacons }
.count { point ->
sensors.any {
(it.first - point).manhattan() <= it.second
}
}
}
override fun second(): Any? {
val tuples = lines
.mapNotNull { PATTERN.find(it) }
.map { match -> match.destructured.toList().map { it.toInt() } }
.map { coords ->
val sensor = Vector2D(coords[0], coords[1])
val beacon = Vector2D(coords[2], coords[3])
Triple(sensor, beacon, (sensor - beacon).manhattan())
}
val beacons = tuples.map { it.second }.toSet()
val sensors = tuples.map { it.first to it.third }
val from = 0
val to = 4000000
val range = (from..to)
return range
.asSequence()
.mapNotNull { y ->
val events = sensors
.flatMap { sensor ->
val dy = abs(sensor.first.y - y)
val dx = sensor.second - dy
if (dx >= 0) {
listOf(
Pair(sensor.first.x - dx, 1),
Pair(sensor.first.x + dx + 1, -1),
)
} else {
emptyList()
}
}
.sortedBy { it.first }
events.drop(1)
.asSequence()
.runningFold(events.first()) { acc, value ->
value.first to acc.second + value.second
}
.firstOrNull { it.second == 0 }
?.takeIf { it.first in range }
?.let { Vector2D(it.first, y) }
?.takeIf { it !in beacons }
}
.first()
.let { it.x * 4000000L + it.y }
}
}
fun main() = SomeDay.mainify(Day15)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,757 | adventofcode | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem2101/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2101
/**
* LeetCode page: [2101. Detonate the Maximum Bombs](https://leetcode.com/problems/detonate-the-maximum-bombs/);
*/
class Solution {
/* Complexity:
* Time O(N^3) and Space O(N^2) where N is the size of bombs;
*/
fun maximumDetonation(bombs: Array<IntArray>): Int {
val bombAdjacencyInIndex = bombAdjacencyInIndex(bombs)
var result = 0
for (sourceBombIndex in bombs.indices) {
val numDetonatedBombs = numDetonatedBombs(sourceBombIndex, bombs, bombAdjacencyInIndex)
if (result < numDetonatedBombs) {
result = numDetonatedBombs
}
}
return result
}
private fun bombAdjacencyInIndex(bombs: Array<IntArray>): List<List<Int>> {
val result = List(bombs.size) { mutableListOf<Int>() }
for (i in bombs.indices) {
for (j in i + 1 until bombs.size) {
if (inRange(bombs[i], bombs[j])) {
result[i].add(j)
}
if (inRange(bombs[j], bombs[i])) {
result[j].add(i)
}
}
}
return result
}
private fun inRange(sourceBomb: IntArray, nearbyBomb: IntArray): Boolean {
val (sourceX, sourceY, sourceRadius) = sourceBomb
val (nearbyX, nearbyY, _) = nearbyBomb
val distanceSquare = square(sourceX - nearbyX) + square(sourceY - nearbyY)
return distanceSquare <= square(sourceRadius)
}
private fun square(a: Int): Long {
return a.toLong() * a
}
private fun numDetonatedBombs(
sourceBombIndex: Int,
bombs: Array<IntArray>,
bombAdjacencyInIndex: List<List<Int>>,
hasBeenDetonated: BooleanArray = BooleanArray(bombs.size)
): Int {
if (hasBeenDetonated[sourceBombIndex]) {
return 0
}
hasBeenDetonated[sourceBombIndex] = true
var result = 1
val adjacentBombIndices = bombAdjacencyInIndex[sourceBombIndex]
for (index in adjacentBombIndices) {
result += numDetonatedBombs(index, bombs, bombAdjacencyInIndex, hasBeenDetonated)
}
return result
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,231 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day08.kt | acrab | 573,191,416 | false | {"Kotlin": 52968} | import com.google.common.truth.Truth.assertThat
fun main() {
fun isVisible(height: Int, x: Int, y: Int, map: List<List<Int>>): Boolean {
//edge trees are always visible
if (x == 0 || x == map.size - 1 || y == 0 || y == map[x].size - 1) {
return true
}
//check up
var visibleUp = true
for (i in x - 1 downTo 0) {
if (map[i][y] >= height) visibleUp = false
}
//check down
var visibleDown = true
for (i in x + 1 until map.size) {
if (map[i][y] >= height) visibleDown = false
}
//check left
var visibleLeft = true
for (i in y - 1 downTo 0) {
if (map[x][i] >= height) visibleLeft = false
}
//check right
var visibleRight = true
for (i in y + 1 until map.size) {
if (map[x][i] >= height) visibleRight = false
}
return visibleDown || visibleUp || visibleLeft || visibleRight
}
fun part1(input: List<String>): Int {
//Convert them all to integers
val map = input.map { line -> line.map { it.digitToInt() } }
val visibility = map.mapIndexed { x, rows -> rows.mapIndexed { y, tree -> isVisible(tree, x, y, map) } }
return visibility.sumOf { line -> line.count { it } }
}
fun calculateVisibility(height: Int, x: Int, y: Int, map: List<List<Int>>): Int {
//check up
var visibleUp = 0
for (i in x - 1 downTo 0) {
visibleUp += 1
if (map[i][y] >= height) break
}
//check down
var visibleDown = 0
for (i in x + 1 until map.size) {
visibleDown += 1
if (map[i][y] >= height) break
}
//check left
var visibleLeft = 0
for (i in y - 1 downTo 0) {
visibleLeft += 1
if (map[x][i] >= height) break
}
//check right
var visibleRight = 0
for (i in y + 1 until map.size) {
visibleRight += 1
if (map[x][i] >= height) break
}
return visibleDown * visibleUp * visibleLeft * visibleRight
}
fun part2(input: List<String>): Int {
//Convert them all to integers
val map = input.map { line -> line.map { it.digitToInt() } }
val visibility =
map.mapIndexed { x, rows -> rows.mapIndexed { y, tree -> calculateVisibility(tree, x, y, map) } }
return visibility.maxOf { line -> line.max() }
}
val testInput = readInput("Day08_test")
assertThat(part1(testInput)).isEqualTo(21)
val input = readInput("Day08")
println(part1(input))
assertThat(part2(testInput)).isEqualTo(8)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0be1409ceea72963f596e702327c5a875aca305c | 2,752 | aoc-2022 | Apache License 2.0 |
kotlin-practice/src/main/kotlin/exercise/collection/CollectionOperators2.kt | nicolegeorgieva | 590,020,790 | false | {"Kotlin": 120359} | package exercise.collection
fun main() {
val salesData = listOf<Sale>(
Sale("Meat", 7.0, 10),
Sale("Fish", 5.0, 5),
Sale("Snack", 3.0, 2),
Sale("Bread", 1.0, 5),
Sale("Nuts", 2.0, 9),
Sale("Chocolate", 3.0, 5)
)
println(calculateTotalProfit(salesData, 1.0))
}
/*
You are given a list of sales data represented as objects with the following
properties: productName (String), price (Double), and quantitySold (Int).
Your task is to create a Kotlin program that performs various operations on the list using collection operators.
*/
data class Sale(
val productName: String,
val price: Double,
val quantitySold: Int
)
fun calculateTotalRevenue(salesData: List<Sale>): Double {
return salesData.sumOf { it.price * it.quantitySold }
}
fun findMostSoldProduct(salesData: List<Sale>): String {
return try {
salesData.maxBy { it.quantitySold }.productName
} catch (e: Exception) {
"Invalid data"
}
}
fun filterSalesByPriceRange(salesData: List<Sale>, minPrice: Double, maxPrice: Double): List<String> {
return salesData.filter { it.price in minPrice..maxPrice }
.sortedByDescending { it.price }
.map { "${it.productName}: ${it.price}" }
}
fun findTopNSellingProducts(salesData: List<Sale>, topN: Int): List<String> {
return salesData.sortedByDescending { it.quantitySold }
.take(topN)
.map { "${it.productName}: ${it.quantitySold} sold" }
}
enum class PriceCategory {
Low,
Medium,
High
}
data class SaleWithProfit(
val saleData: Sale,
val profit: Double
)
fun calculatePriceCategory(price: Double): PriceCategory {
return when (price) {
in 0.0..2.0 -> PriceCategory.Low
in 2.01..3.0 -> PriceCategory.Medium
else -> PriceCategory.High
}
}
fun groupByPriceCategory(salesData: List<Sale>): Map<PriceCategory, List<Sale>> {
return salesData.groupBy { calculatePriceCategory(it.price) }
}
fun calculateTotalProfit(salesData: List<Sale>, fixedCostPerProduct: Double): List<String> {
return salesData.map {
SaleWithProfit(saleData = it, profit = (it.price * it.quantitySold) - (fixedCostPerProduct * it.quantitySold))
}
.map {
"${it.saleData.productName} - ${it.profit} profit"
}
} | 0 | Kotlin | 0 | 1 | c96a0234cc467dfaee258bdea8ddc743627e2e20 | 2,324 | kotlin-practice | MIT License |
src/Day02.kt | LesleySommerville-Ki | 577,718,331 | false | {"Kotlin": 9590} | fun main() {
val part1Scoring: Map<String, Int> =
mapOf(
"A X" to 1 + 3, // rock = 1
"A Y" to 2 + 6, // paper = 2
"A Z" to 3 + 0, // scissors = 3
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 1 + 6,
"C Y" to 2 + 0,
"C Z" to 3 + 3,
)
val part2Scoring: Map<String, Int> =
mapOf(
"A X" to 3 + 0,
"A Y" to 1 + 3,
"A Z" to 2 + 6,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 2 + 0,
"C Y" to 3 + 3,
"C Z" to 1 + 6,
)
fun part1(input: List<String>): Int {
return input.sumOf { part1Scoring[it] ?: 0 }
}
fun part2(input: List<String>): Int {
return input.sumOf { part2Scoring[it] ?: 0 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | ea657777d8f084077df9a324093af9892c962200 | 1,138 | AoC | Apache License 2.0 |
src/2021/Day15_1.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
val grid = ArrayList<ArrayList<Int>>()
File("input/2021/day15").forEachLine { line ->
grid.add(ArrayList<Int>().apply { addAll(line.toList().map { it.digitToInt() }) })
}
fun ArrayList<Pair<Int, Pair<Int, Int>>>.addFor(y: Int, x: Int, from: ArrayList<ArrayList<Int>>) = add(Pair(from[y][x], Pair(y,x)))
fun ArrayList<ArrayList<Int>>.neighbours(y: Int, x: Int): ArrayList<Pair<Int, Pair<Int, Int>>> {
val row = get(y)
val nList = ArrayList<Pair<Int, Pair<Int, Int>>>()
if (y == 0) {
if (x == 0) {
nList.addFor(y, x+1, this)
} else if (x == row.size -1) {
nList.addFor(y, x-1, this)
} else {
nList.addFor(y, x-1, this)
nList.addFor(y, x+1, this)
}
nList.addFor(y+1, x, this)
} else if (y == size-1) {
if (x == row.size-1) {
nList.addFor(y, x-1, this)
} else if (x == 0) {
nList.addFor(y, x+1, this)
} else {
nList.addFor(y, x-1, this)
nList.addFor(y, x+1, this)
}
nList.addFor(y-1, x, this)
} else {
if (x > 0 && x < row.size-1) {
nList.addFor(y, x-1, this)
nList.addFor(y, x+1, this)
} else if (x == 0) {
nList.addFor(y, x+1, this)
} else if (x == row.size-1) {
nList.addFor(y, x-1, this)
}
nList.addFor(y+1, x, this)
nList.addFor(y-1, x, this)
}
return nList
}
println()
var y = 0
var x = 0
var cameFrom = Pair(0,0)
var distance = 0
var steps = 0
var stack = ArrayList<Pair<Int, Pair<Int, Int>>>()
val distances = ArrayList<ArrayList<Int>>()
val originMap = ArrayList<ArrayList<Int>>()
val visited = ArrayList<ArrayList<Boolean>>()
val yMax = grid.size-1
val xMax = grid[0].size-1
for (y in 0..yMax) {
val row = grid[y].map { 0 }
distances.add(ArrayList<Int>().apply { addAll(row) })
originMap.add(ArrayList<Int>().apply { addAll(row) })
visited.add(ArrayList<Boolean>().apply { addAll(row.map { false }) })
}
grid.forEach { println(it) }
println()
distances.forEach { println(it) }
while (y != yMax && x != xMax && steps < 2) {
if (x < xMax) {
if (distances[y][x+1] > grid[y][x+1]+distances[y][x] && !visited[y][x+1]) {
distances[y][x+1] = grid[y][x + 1] + distances[y][x]
originMap[y][x+1] = np.ravel_multi_index([x, y], (max_val, max_val))
}
}
# move to x-1,y
if x>0:
if distances[x-1,y]>grid[x-1,y]+distances[x,y] and not visited[x-1,y]:
distances[x-1,y]=grid[x-1,y]+distances[x,y]
originMap[x-1,y]=np.ravel_multi_index([x,y], (max_val,max_val))
# move to x,y+1
if y < max_val-1:
if distances[x,y+1]>grid[x,y+1]+distances[x,y] and not visited[x,y+1]:
distances[x,y+1]=grid[x,y+1]+distances[x,y]
originMap[x,y+1]=np.ravel_multi_index([x,y], (max_val,max_val))
# move to x,y-1
if y>0:
if distances[x,y-1]>grid[x,y-1]+distances[x,y] and not visited[x,y-1]:
distances[x,y-1]=grid[x,y-1]+distances[x,y]
originMap[x,y-1]=np.ravel_multi_index([x,y], (max_val,max_val))
steps++
} | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 3,142 | adventofcode | MIT License |
src/main/kotlin/day2.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | private val testInput1 = """
forward 5
down 5
forward 8
up 3
down 8
forward 2
""".trimIndent()
private fun tests() {
assertEquals(part1(parseInput(testInput1)), 150)
assertEquals(part2(parseInput(testInput1)), 900)
}
private fun main() {
tests()
val input = readInputFile("input2")
val commands = parseInput(input)
println("part1: ${part1(commands)}")
println("part2: ${part2(commands)}")
println("day2")
}
private fun part2(commands: List<SubmarineCommand>): Int {
val finalPosition = Submarine(0, 0, 0).foldWithTransformations(commands, ::executeCommand2)
return finalPosition.x * finalPosition.y
}
private fun part1(commands: List<SubmarineCommand>): Int {
val finalPosition = Submarine(0, 0, 0).foldWithTransformations(commands, ::executeCommand)
return finalPosition.x * finalPosition.y
}
sealed interface SubmarineCommand
data class Down(val amount: Int) : SubmarineCommand
data class Up(val amount: Int) : SubmarineCommand
data class Forward(val amount: Int) : SubmarineCommand
private data class Submarine(val x: Int, val y: Int, val aim: Int) // todo should we work with longs?
private fun executeCommand2(submarine: Submarine, command: SubmarineCommand) = with(submarine) {
when (command) {
is Down -> copy(aim = aim + command.amount)
is Forward -> copy(x = x + command.amount, y = y + aim * command.amount)
is Up -> copy(aim = aim - command.amount)
}
}
private fun executeCommand(submarine: Submarine, command: SubmarineCommand) = with(submarine) {
when (command) {
is Down -> copy(y = y + command.amount)
is Forward -> copy(x = x + command.amount)
is Up -> copy(y = y - command.amount)
}
}
private fun parseInput(string: String): List<SubmarineCommand> =
string.lines().map { parseCommand(it) }
private fun parseCommand(string: String): SubmarineCommand {
val s = string.split(" ")
require(s.size == 2)
val command = s[0]
val amount = s[1].toInt()
return when (command) {
F -> Forward(amount)
D -> Down(amount)
U -> Up(amount)
else -> error("cant $command")
}
}
private const val F = "forward"
private const val D = "down"
private const val U = "up"
| 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 2,271 | AOC-2021 | MIT License |
src/main/kotlin/Day2.kt | Ostkontentitan | 434,500,914 | false | {"Kotlin": 73563} | import kotlin.math.abs
fun puzzleDayTwoPartOne() {
val inputs = readInput(2)
val position = inputs.fold(Position()) { acc, item ->
val number = getNumber(item)
when (getDirection(item)) {
Direction.UP -> acc.copy(height = acc.height + number)
Direction.DOWN -> acc.copy(height = acc.height - number)
Direction.FORWARD -> acc.copy(distance = acc.distance + number)
}
}
println(abs(position.height * position.distance))
}
fun puzzleDayTwoPartTwo() {
val inputs = readInput(2)
val navigationalState = inputs.fold(NavigationalState()) { acc, item ->
val number = getNumber(item)
when (getDirection(item)) {
Direction.UP -> acc.copy(aim = acc.aim - number)
Direction.DOWN -> acc.copy(aim = acc.aim + number)
Direction.FORWARD -> acc.copy(distance = acc.distance + number, height = acc.height + acc.aim * number)
}
}
println(abs(navigationalState.height * navigationalState.distance))
}
fun getDirection(input: String): Direction = when {
input.startsWith("forward") -> Direction.FORWARD
input.startsWith("up") -> Direction.UP
input.startsWith("down") -> Direction.DOWN
else -> throw IllegalArgumentException("Unhandled direction $input")
}
fun getNumber(input: String): Int {
val numberIndex = input.indexOf(" ") + 1
return input[numberIndex].toString().toInt()
}
data class Position(val height: Int = 0, val distance: Int = 0)
data class NavigationalState(val height: Int = 0, val distance: Int = 0, val aim: Int = 0)
enum class Direction {
UP, DOWN, FORWARD;
}
| 0 | Kotlin | 0 | 0 | e0e5022238747e4b934cac0f6235b92831ca8ac7 | 1,644 | advent-of-kotlin-2021 | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2023/Day06.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2023
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 6: Wait For It](https://adventofcode.com/2023/day/6).
*/
object Day06 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2023/Day06")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val times = Regex("\\d+").findAll(input[0]).map { it.value.toLong() }.toList()
val recordDistances = Regex("\\d+").findAll(input[1]).map { it.value.toLong() }.toList()
val races = times.zip(recordDistances).map { (time, recordDistance) -> Race(time, recordDistance) }
return races.map { race ->
var waysToWin = 0
for (holdingTime in 1..<race.time) {
val boatDistance = (race.time - holdingTime) * holdingTime
if (boatDistance > race.recordDistance) waysToWin++
}
waysToWin
}.fold(1) { acc, i -> acc * i }
}
fun part2(input: List<String>): Int {
val time = Regex("\\d+").findAll(input[0]).map { it.value }.joinToString("").toLong()
val recordDistance = Regex("\\d+").findAll(input[1]).map { it.value }.joinToString("").toLong()
val race = Race(time, recordDistance)
var waysToWin = 0
for (holdingTime in 1..<race.time) {
val boatDistance = (race.time - holdingTime) * holdingTime
if (boatDistance > race.recordDistance) waysToWin++
}
return waysToWin
}
private data class Race(val time: Long, val recordDistance: Long)
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 1,713 | advent-of-code | MIT License |
src/Day01.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | const val PART1_EXPECTED_HIGHEST_CALORIES = 24000
const val PART2_EXPECTED_HIGHEST_3_CALORIES_SUM = 45000
const val PART2_TOP_ELF_COUNT = 3
fun main() {
fun elfTotals(input: List<String>, idx: Int = 0, elfAmount: Int = 0, totals: List<Int> = emptyList()): List<Int> {
if (idx >= input.size) return totals + elfAmount
return elfTotals(
input,
idx + 1,
if (input[idx].isBlank()) 0 else elfAmount + input[idx].toInt(),
if (input[idx].isBlank()) totals + elfAmount else totals
)
}
fun part1(input: List<String>): Int {
return elfTotals(input).maxOf { it }
}
fun part2(input: List<String>): Int {
val elfTotals = elfTotals(input)
return elfTotals.sortedDescending().take(PART2_TOP_ELF_COUNT).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == PART1_EXPECTED_HIGHEST_CALORIES)
check(part2(testInput) == PART2_EXPECTED_HIGHEST_3_CALORIES_SUM)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
// fun part1(input: List<String>): Int {
// var currentMax = 0
// var elfTotal = 0
// input.forEach {
// if (it.isBlank()) {
// if (elfTotal > currentMax) {
// currentMax = elfTotal
// }
// elfTotal = 0
// } else {
// elfTotal += it.toInt()
// }
// }
// return currentMax
// }
//
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 1,593 | aoc-2022-in-kotlin | Apache License 2.0 |
day12/src/main/kotlin/App.kt | ascheja | 317,918,055 | false | null | package net.sinceat.aoc2020.day12
import kotlin.math.abs
fun main() {
println(readInstructions("testinput.txt").calculateManhattanDistancePart1())
println(readInstructions("input.txt").calculateManhattanDistancePart1())
println(readInstructions("testinput.txt").calculateManhattanDistancePart2())
println(readInstructions("input.txt").calculateManhattanDistancePart2())
}
fun List<Instruction>.calculateManhattanDistancePart1(): Int {
var facing = 90
var xDistance = 0
var yDistance = 0
for (instruction in this) {
when (instruction) {
is Forward -> when (facing) {
0 -> yDistance += instruction.distance
90 -> xDistance += instruction.distance
180 -> yDistance -= instruction.distance
270 -> xDistance -= instruction.distance
}
is TurnLeft -> {
val rawFacing = facing - instruction.degrees
facing = if (rawFacing < 0) {
rawFacing + 360
} else rawFacing
}
is TurnRight -> {
val rawFacing = facing + instruction.degrees
facing = if (rawFacing >= 360) {
rawFacing % 360
} else rawFacing
}
is North -> yDistance += instruction.distance
is East -> xDistance += instruction.distance
is South -> yDistance -= instruction.distance
is West -> xDistance -= instruction.distance
}
}
return abs(xDistance) + abs(yDistance)
}
data class Point(val x: Int, val y: Int)
fun Point.north(amount: Int) = Point(x, y + amount)
fun Point.east(amount: Int) = Point(x + amount, y)
fun Point.south(amount: Int) = Point(x, y - amount)
fun Point.west(amount: Int) = Point(x - amount, y)
fun Point.rotateLeft() = Point(-y, x)
fun Point.rotateRight() = Point(y, -x)
fun List<Instruction>.calculateManhattanDistancePart2(): Int {
var waypoint = Point(10, 1)
var xDistance = 0
var yDistance = 0
for (instruction in this) {
when (instruction) {
is Forward -> {
xDistance += waypoint.x * instruction.distance
yDistance += waypoint.y * instruction.distance
}
is TurnLeft -> repeat(instruction.degrees / 90) {
waypoint = waypoint.rotateLeft()
}
is TurnRight -> repeat(instruction.degrees / 90) {
waypoint = waypoint.rotateRight()
}
is North -> waypoint = waypoint.north(instruction.distance)
is East -> waypoint = waypoint.east(instruction.distance)
is South -> waypoint = waypoint.south(instruction.distance)
is West -> waypoint = waypoint.west(instruction.distance)
}
}
return abs(xDistance) + abs(yDistance)
}
sealed class Instruction
class Forward(val distance: Int) : Instruction()
class TurnLeft(val degrees: Int) : Instruction()
class TurnRight(val degrees: Int) : Instruction()
class North(val distance: Int) : Instruction()
class East(val distance: Int) : Instruction()
class South(val distance: Int) : Instruction()
class West(val distance: Int) : Instruction()
fun readInstructions(fileName: String): List<Instruction> {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
lines.filter(String::isNotBlank).map { line ->
val instructionType = line[0]
val instructionArgument = line.removePrefix(instructionType.toString()).toInt()
when (instructionType) {
'F' -> Forward(instructionArgument)
'L' -> TurnLeft(instructionArgument)
'R' -> TurnRight(instructionArgument)
'N' -> North(instructionArgument)
'E' -> East(instructionArgument)
'S' -> South(instructionArgument)
'W' -> West(instructionArgument)
else -> TODO("unhandled instruction type '$instructionType'")
}
}.toList()
}
}
| 0 | Kotlin | 0 | 0 | f115063875d4d79da32cbdd44ff688f9b418d25e | 4,114 | aoc2020 | MIT License |
src/Day02.kt | jwklomp | 572,195,432 | false | {"Kotlin": 65103} | fun main() {
val moveScoreMap1 = mapOf(
"A X" to 3+1, "A Y" to 6+2, "A Z" to 0+3,
"B X" to 0+1, "B Y" to 3+2, "B Z" to 6+3,
"C X" to 6+1, "C Y" to 0+2, "C Z" to 3+3
)
val moveScoreMap2 = mapOf(
"A X" to 3+0, "A Y" to 1+3, "A Z" to 2+6,
"B X" to 1+0, "B Y" to 2+3, "B Z" to 3+6,
"C X" to 2+0, "C Y" to 3+3, "C Z" to 1+6
)
fun part1(input: List<String>): Int =
input.sumOf { moveScoreMap1.getOrDefault(it, 0) }
fun part2(input: List<String>): Int =
input.sumOf { moveScoreMap2.getOrDefault(it, 0) }
val testInput = readInput("Day02_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1b1121cfc57bbb73ac84a2f58927ab59bf158888 | 783 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day21/a/day21a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day21.a
import readInputLines
import shouldBe
fun main() {
val r = read()
val answer = (evaluate(r) as Num).value
shouldBe(63119856257960, answer)
}
fun evaluate(e: Expr): Expr {
if (e is Op) {
val a = evaluate(e.a)
val b = evaluate(e.b)
if (a is Num && b is Num) {
val n = when (e.op) {
"*" -> a.value * b.value
"+" -> a.value + b.value
"-" -> a.value - b.value
"/" -> a.value / b.value
else -> return Op(a,b,e.op)
}
return Num(n)
} else {
return Op(a,b,e.op)
}
} else {
return e
}
}
open class Expr {
open fun any(function: (e: Expr) -> Boolean): Boolean {
return function(this)
}
}
class Num(val value: Long): Expr() {
override fun toString(): String {
return value.toString()
}
}
class Op(
var a: Expr,
val b: Expr,
val op: String
): Expr() {
override fun any(function: (e: Expr) -> Boolean): Boolean {
return function(this) || a.any(function) || b.any(function)
}
override fun toString(): String {
return "($a$op$b)"
}
}
fun read(): Op {
val sym = HashMap<String, Expr>()
val lines = readInputLines(21).filter { it.isNotBlank() }
val set = HashSet(lines)
while (set.isNotEmpty()) {
val it = set.iterator()
while (it.hasNext()) {
val s = it.next()
val r = s.split(":")
val name = r[0]
val e = r[1].substring(1)
if (e.matches(Regex("-?[0-9]+"))) {
sym[name] = Num(e.toLong())
it.remove()
} else {
val t = e.split(" ")
val a = sym[t[0]]
val b = sym[t[2]]
val op = t[1]
if (a != null && b != null) {
sym[name] = Op(a, b, op)
it.remove()
}
}
}
}
return sym["root"] as Op
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 2,065 | advent-of-code-2022 | Apache License 2.0 |
src/Day19.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | import kotlin.math.max
fun main() {
class State(var oreRobot: Int, var clayRobot: Int, var obsidianRobot: Int, var geodeRobot: Int,
var ore: Int, var clay: Int, var obsidian: Int, var geode: Int, var t: Int)
fun parseBlueprint(input: String): MutableMap<String, MutableMap<String, Int>> {
val ruleMap = mutableMapOf<String, MutableMap<String, Int>>()
for (rule in input.split(":")[1].split(" Each ").subList(1, 5)){
ruleMap[rule.split(" ")[0]] = mutableMapOf<String, Int>()
val elems = rule.split(" ")
for ((index, elem) in elems.withIndex()){
if (elem.toIntOrNull() != null){
ruleMap[rule.split(" ")[0]]?.set(elems[index+1].replace(".", ""), elem.toInt())
}
}
}
return ruleMap
}
fun State.print(){
println("oreRobot: ${this.oreRobot} clayRobot: ${this.clayRobot} obsRobot: ${this.obsidianRobot} geodeRobot: ${this.geodeRobot}")
println("ore: ${this.ore} clay: ${this.clay} obsidian: ${this.obsidian} geode: ${this.geode}; t = ${this.t}")
println("---------------------")
}
fun part12(input: List<String>){
var geodes = mutableListOf<Int>()
for (blueprint in input.take(3)){
val ruleMap = parseBlueprint(blueprint)
var initState = State(oreRobot = 1, clayRobot = 0, obsidianRobot = 0, geodeRobot = 0,
ore = 0, clay = 0, obsidian = 0, geode = 0, t=0)
var stateQueue = mutableListOf(initState)
var maxGeode = 0
var maxState = State(oreRobot = 0, clayRobot = 0, obsidianRobot = 0, geodeRobot = 0,
ore = 0, clay = 0, obsidian = 0, geode = 0, t=0)
var time = 0
val visited = hashSetOf<List<Int>>()
val maxOreRobots = listOf(ruleMap["geode"]?.get("ore")!!,
ruleMap["obsidian"]?.get("ore")!!,
ruleMap["clay"]?.get("ore")!!,
ruleMap["ore"]?.get("ore")!!).max()
while (stateQueue.isNotEmpty()){
var currentState = stateQueue.removeFirst()
if (visited.contains(listOf(currentState.oreRobot, currentState.clayRobot, currentState.obsidianRobot, currentState.geodeRobot,
currentState.ore, currentState.clay, currentState.obsidian, currentState.geode))) continue
visited.add(listOf(currentState.oreRobot, currentState.clayRobot, currentState.obsidianRobot, currentState.geodeRobot,
currentState.ore, currentState.clay, currentState.obsidian, currentState.geode))
if (currentState.t == 33) {
break
}
if (currentState.t > time) {
time = currentState.t
}
if (currentState.t == 31 && currentState.geodeRobot == 0) continue
if (currentState.t == 30 && currentState.obsidianRobot == 0) continue
if (currentState.t == 29 && currentState.clayRobot == 0) continue
var timeLeft = 31 - currentState.t
if ((currentState.obsidian + currentState.obsidianRobot*timeLeft + (timeLeft-1)*(timeLeft)/2 < ruleMap["geode"]?.get("obsidian")!!) && (currentState.geodeRobot == 0)) {
continue
}
if (currentState.geode > maxGeode) {
maxState = State(currentState.oreRobot, currentState.clayRobot,
currentState.obsidianRobot, currentState.geodeRobot,
currentState.ore, currentState.clay, currentState.obsidian, currentState.geode, currentState.t)
maxGeode = currentState.geode
}
else if ((currentState.geode < maxGeode) && (currentState.t >= maxState.t)) {continue}
if (currentState.t == 32) {
continue
}
currentState.print()
var OreTillEnd = listOf(ruleMap["geode"]?.get("ore")!! + ruleMap["obsidian"]?.get("ore")!! + ruleMap["clay"]?.get("ore")!!).max()*(24-currentState.t)
var ClayTillEnd = (ruleMap["obsidian"]?.get("clay")!!)*(24-currentState.t)
var ObsidianTillEnd = (ruleMap["geode"]?.get("obsidian")!!)*(24-currentState.t)
if (currentState.ore + currentState.oreRobot*(24 - currentState.t) < OreTillEnd
|| currentState.clay + currentState.clayRobot*(24 - currentState.t) < ClayTillEnd
|| currentState.obsidian + currentState.obsidianRobot*(24 - currentState.t) < ObsidianTillEnd) {
stateQueue.add(
State(
oreRobot = currentState.oreRobot,
clayRobot = currentState.clayRobot,
obsidianRobot = currentState.obsidianRobot,
geodeRobot = currentState.geodeRobot,
ore = currentState.ore + currentState.oreRobot,
clay = currentState.clay + currentState.clayRobot,
obsidian = currentState.obsidian + currentState.obsidianRobot,
geode = currentState.geode + currentState.geodeRobot,
t = currentState.t + 1
)
)
}
if ((currentState.ore >= (ruleMap["geode"]?.get("ore") ?: 0))
&& (currentState.obsidian >= (ruleMap["geode"]?.get("obsidian") ?: 0))){
stateQueue.add(State(
oreRobot = currentState.oreRobot,
clayRobot = currentState.clayRobot,
obsidianRobot = currentState.obsidianRobot,
geodeRobot = currentState.geodeRobot+1,
ore = currentState.ore+currentState.oreRobot - ruleMap["geode"]?.get("ore")!!,
clay = currentState.clay+currentState.clayRobot,
obsidian = currentState.obsidian+currentState.obsidianRobot - ruleMap["geode"]?.get("obsidian")!!,
geode = currentState.geode + currentState.geodeRobot,
t = currentState.t+1))
continue
}
if ((currentState.ore >= (ruleMap["obsidian"]?.get("ore") ?: 0))
&& (currentState.clay >= (ruleMap["obsidian"]?.get("clay") ?: 0))
&& (currentState.obsidianRobot < (ruleMap["geode"]?.get("obsidian") ?: 0))){
stateQueue.add(State(
oreRobot = currentState.oreRobot,
clayRobot = currentState.clayRobot,
obsidianRobot = currentState.obsidianRobot+1,
geodeRobot = currentState.geodeRobot,
ore = currentState.ore+currentState.oreRobot - ruleMap["obsidian"]?.get("ore")!!,
clay = currentState.clay+currentState.clayRobot - ruleMap["obsidian"]?.get("clay")!!,
obsidian = currentState.obsidian+currentState.obsidianRobot,
geode = currentState.geode + currentState.geodeRobot,
t = currentState.t+1))
}
if ((currentState.ore >= (ruleMap["clay"]?.get("ore") ?: 0))
&& (currentState.clayRobot < (ruleMap["obsidian"]?.get("clay") ?: 0))){
stateQueue.add(State(
oreRobot = currentState.oreRobot,
clayRobot = currentState.clayRobot+1,
obsidianRobot = currentState.obsidianRobot,
geodeRobot = currentState.geodeRobot,
ore = currentState.ore+currentState.oreRobot - ruleMap["clay"]?.get("ore")!!,
clay = currentState.clay+currentState.clayRobot,
obsidian = currentState.obsidian+currentState.obsidianRobot,
geode = currentState.geode + currentState.geodeRobot,
t = currentState.t+1))
}
if ((currentState.ore >= (ruleMap["ore"]?.get("ore") ?: 0))
&& (currentState.oreRobot < maxOreRobots)) {
stateQueue.add(State(oreRobot = currentState.oreRobot+1,
clayRobot = currentState.clayRobot,
obsidianRobot = currentState.obsidianRobot,
geodeRobot = currentState.geodeRobot,
ore = currentState.ore+currentState.oreRobot - ruleMap["ore"]?.get("ore")!!,
clay = currentState.clay+currentState.clayRobot,
obsidian = currentState.obsidian+currentState.obsidianRobot,
geode = currentState.geode + currentState.geodeRobot,
t = currentState.t+1))
}
}
println("max state")
maxState.print()
geodes.add(maxState.geode)
}
println(geodes)
println(geodes.mapIndexed { index, i -> i*(index+1) }.toList().sum())
}
val testInput = readInput("Day19")
// println(parseBlueprint(testInput[0]))
part12(testInput)
} | 0 | Kotlin | 0 | 0 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 9,457 | aoc22 | Apache License 2.0 |
src/DayTwo.kt | P-ter | 572,781,029 | false | {"Kotlin": 18422} | fun main() {
fun partOne(input: List<String>): Int {
val resultMap = buildMap {
put(Pair("A", "X"), 3)
put(Pair("A", "Y"), 6)
put(Pair("A", "Z"), 0)
put(Pair("B", "X"), 0)
put(Pair("B", "Y"), 3)
put(Pair("B", "Z"), 6)
put(Pair("C", "X"), 6)
put(Pair("C", "Y"), 0)
put(Pair("C", "Z"), 3)
}
val point = buildMap {
put("X", 1)
put("Y", 2)
put("Z", 3)
}
val total = input.fold(0) { acc, pair ->
val (opponent, myMove) = pair.split(" ")
var point = point[myMove] ?: 0
point += resultMap[Pair(opponent, myMove)] ?: 0
acc + point
}
return total
}
fun partTwo(input: List<String>): Int {
val resultMap = buildMap {
put(Pair("A", "X"), 3)
put(Pair("A", "Y"), 1)
put(Pair("A", "Z"), 2)
put(Pair("B", "X"), 1)
put(Pair("B", "Y"), 2)
put(Pair("B", "Z"), 3)
put(Pair("C", "X"), 2)
put(Pair("C", "Y"), 3)
put(Pair("C", "Z"), 1)
}
val point = buildMap {
put("X", 0)
put("Y", 3)
put("Z", 6)
}
val total = input.fold(0) { acc, pair ->
val (opponent, myMove) = pair.split(" ")
var point = point[myMove] ?: 0
point += resultMap[Pair(opponent, myMove)] ?: 0
acc + point
}
return total
}
val input = readInput("daytwo")
println(partOne(input))
println(partTwo(input))
}
| 0 | Kotlin | 0 | 1 | e28851ee38d6de5600b54fb884ad7199b44e8373 | 1,685 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day02/Day02.kt | RegBl | 573,086,350 | false | {"Kotlin": 11359} | package day02
import readInput
fun main() {
val input = readInput("\\day02\\Day02")
val testInput = readInput("\\day02\\Day02_test")
val contestantChoices = inputListToContestantChoicesList(input)
val contestantScores = contestantChoicesToContestantScores(contestantChoices)
// Part 1
println(contestantChoices)
println(contestantScores)
println(contestantScores.last().sum())
// Part 2
}
enum class CHOICE {ROCK, PAPER, SCISSORS, DEPENDENT}
enum class STRATEGY {WIN, LOSE, DRAW, NORMAL}
data class PlayerRound(var choice: CHOICE, val strategy: STRATEGY)
fun contestantChoicesToContestantScores(choices: List<List<PlayerRound>>): List<List<Int>> {
val firstContestantScores = mutableListOf<Int>()
val secondContestantScores = mutableListOf<Int>()
choices.first().zip(choices.last()) { first, last ->
val scores = compareChoices(first, last)
firstContestantScores.add(scores.first)
secondContestantScores.add(scores.second)
}
return listOf(firstContestantScores, secondContestantScores)
}
fun compareChoices(first: PlayerRound, last: PlayerRound): Pair<Int, Int> {
val firstChoiceNumValue = first.choice.ordinal + 1
val lastChoiceNumValue = last.choice.ordinal + 1
return when (last.strategy) {
STRATEGY.NORMAL -> {
when (Pair(first.choice, last.choice)) {
// Tie conditions
(Pair(CHOICE.ROCK, CHOICE.ROCK)),
(Pair(CHOICE.SCISSORS, CHOICE.SCISSORS)),
(Pair(CHOICE.PAPER, CHOICE.PAPER)) -> Pair((firstChoiceNumValue + 3),(lastChoiceNumValue + 3))
// Loss/win conditions
(Pair(CHOICE.ROCK, CHOICE.PAPER)),
(Pair(CHOICE.PAPER, CHOICE.SCISSORS)),
(Pair(CHOICE.SCISSORS, CHOICE.ROCK)) -> Pair(firstChoiceNumValue, (lastChoiceNumValue + 6))
// Win/loss conditions
(Pair(CHOICE.ROCK, CHOICE.SCISSORS)),
(Pair(CHOICE.PAPER, CHOICE.ROCK)),
(Pair(CHOICE.SCISSORS, CHOICE.PAPER)) -> Pair((firstChoiceNumValue + 6), lastChoiceNumValue)
else -> throw Exception()
}
}
STRATEGY.WIN -> {
when (first.choice) {
CHOICE.ROCK -> last.choice = CHOICE.PAPER
CHOICE.PAPER -> last.choice = CHOICE.SCISSORS
CHOICE.SCISSORS -> last.choice = CHOICE.ROCK
else -> throw Exception()
}
Pair((first.choice.ordinal + 1), (last.choice.ordinal + 1 + 6))
}
STRATEGY.LOSE -> {
when (first.choice) {
CHOICE.ROCK -> last.choice = CHOICE.SCISSORS
CHOICE.PAPER -> last.choice = CHOICE.ROCK
CHOICE.SCISSORS -> last.choice = CHOICE.PAPER
else -> throw Exception()
}
Pair((first.choice.ordinal + 1 + 6), (last.choice.ordinal + 1))
}
STRATEGY.DRAW -> {
when (first.choice) {
CHOICE.ROCK -> last.choice = CHOICE.ROCK
CHOICE.PAPER -> last.choice = CHOICE.PAPER
CHOICE.SCISSORS -> last.choice = CHOICE.SCISSORS
else -> throw Exception()
}
Pair((first.choice.ordinal + 1 + 3), (last.choice.ordinal + 1 + 3))
}
}
}
fun translateChoice(choice: String): PlayerRound {
return when (choice) {
"A" -> PlayerRound(CHOICE.ROCK, STRATEGY.NORMAL)
"B" -> PlayerRound(CHOICE.PAPER, STRATEGY.NORMAL)
"C" -> PlayerRound(CHOICE.SCISSORS, STRATEGY.NORMAL)
"X" -> PlayerRound(CHOICE.DEPENDENT, STRATEGY.LOSE)
"Y" -> PlayerRound(CHOICE.DEPENDENT, STRATEGY.DRAW)
"Z" -> PlayerRound(CHOICE.DEPENDENT, STRATEGY.WIN)
else -> throw Exception("Unknown input")
}
}
fun inputListToContestantChoicesList(input: List<String>): List<List<PlayerRound>> {
val firstContestantChoices = mutableListOf<PlayerRound>()
val secondContestantChoices = mutableListOf<PlayerRound>()
input.forEach {round ->
val test = round.split(" ")
firstContestantChoices.add(translateChoice(test.first()))
secondContestantChoices.add(translateChoice(test.last()))
}
return listOf(firstContestantChoices, secondContestantChoices)
} | 0 | Kotlin | 0 | 0 | bd45eb4378d057267823dcc72ad958492f7056ff | 4,336 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Droplets.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | fun main() = Droplets.solve()
private object Droplets {
fun solve() {
val input = readInput()
val droplet = Droplet(input)
println("total surface area ${droplet.surfaceArea1()}")
println("outside surface area ${droplet.surfaceArea2()}")
}
private fun readInput(): List<Pos> = generateSequence(::readLine).map {
val parts = it.split(",").map { it.toInt(10) }
Pos(parts[0], parts[1], parts[2])
}.toList()
data class Pos(val x: Int, val y: Int, val z: Int) {
fun sides() = listOf(
Pos(x + 1, y, z), Pos(x - 1, y, z),
Pos(x, y + 1, z), Pos(x, y - 1, z),
Pos(x, y, z + 1), Pos(x, y, z - 1)
)
}
class Droplet(val points: List<Pos>) {
fun surfaceArea1(): Int {
var area = 0
val pointSet = points.toSet()
for (point in points) {
area += 6 - point.sides().count { pointSet.contains(it) }
}
// println("${joined.size} $area")
return area
}
fun surfaceArea2(): Int {
val minX = points.minOf { it.x }
val maxX = points.maxOf { it.x }
val minY = points.minOf { it.y }
val maxY = points.maxOf { it.y }
val minZ = points.minOf { it.z }
val maxZ = points.maxOf { it.z }
val xRange = (minX - 1)..(maxX + 1)
val yRange = (minY - 1)..(maxY + 1)
val zRange = (minZ - 1)..(maxZ + 1)
println("$xRange $yRange $zRange")
val outsideCells = mutableSetOf<Pos>()
val pointsSet = points.toSet()
val q = mutableListOf(Pos(xRange.start, yRange.start, zRange.start))
while (q.isNotEmpty()) {
val cell = q.removeFirst()
if (cell in pointsSet || cell in outsideCells) {
continue
}
outsideCells.add(cell)
q.addAll(cell.sides().filter { it.x in xRange && it.y in yRange && it.z in zRange })
}
var result = 0
for (point in pointsSet) {
result += point.sides().count { it in outsideCells }
}
return result
}
}
} | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 2,276 | aoc2022 | MIT License |
src/main/kotlin/org/sjoblomj/adventofcode/GeneticAlgorithm.kt | sjoblomj | 161,537,410 | false | null | package org.sjoblomj.adventofcode
/**
* A Genetic Algorithm is inspired by natural selection and evolution to find solutions to a problem. A list of possible
* solutions are evaluated, and the ones giving the best result are selected as the basis for creating new solutions,
* which are hopefully even better. In each iteration of the algorithm, the solutions are ranked using a Fitness
* Function which gives each solution a Score, denoting how well it performs.
*
* A possible solution is referred to as an Individual, and a list of solutions is called a Population.
*
* A Population is initialised and evaluated using the Fitness Function. The best Individuals are selected and breed
* a new set of Individuals. Some random mutations are introduced in order for the algorithm not to converge at a
* suboptimal local minimum. This new set of Individuals are ranked using the Fitness Function, until it is determined
* that the algorithm converges. When that happens, the current population is returned, sorted by their Fitness Score.
*/
interface GeneticAlgorithm<Individual> {
/**
* Will generate a population (list of Individuals) that consists of the Individuals who are the fittest.
* The result is calculated by using the standard Genetic Algorithm.
*/
fun generateGeneticSolution(): List<Individual> {
var population: List<Individual> = initialisePopulation()
var fitnessScore: List<Pair<Individual, Score>> = calculateFitnessFunction(population)
while (!populationHasConverged(fitnessScore)) {
population = performSelection(fitnessScore)
population = performCrossover(population)
population = performMutation(population)
fitnessScore = calculateFitnessFunction(population)
}
return fitnessScore.sortedBy { it.second }.map { it.first }
}
/**
* Initialise the population.
*/
fun initialisePopulation(): List<Individual>
/**
* This function will assign a Score to each Individual in the population, denoting how good that individual is.
* The lower the Score, the better the solution.
*/
fun calculateFitnessFunction(population: List<Individual>): List<Pair<Individual, Score>>
/**
* Returns true when the population is considered to have converged. This will make the algorithm return the
* best population.
*/
fun populationHasConverged(population: List<Pair<Individual, Score>>): Boolean
/**
* Given a list of Individuals and their Scores, this will pick a subset of the population.
*/
fun performSelection(fitnessScore: List<Pair<Individual, Score>>): List<Individual>
/**
* Generate a new solution from the Individuals that were selected to pass their genes on to the next generation.
* Individuals will be selected to breed children, until we have reached a population of the size we want.
*/
fun performCrossover(selectedPopulation: List<Individual>): List<Individual>
/**
* To prevent the algorithm from getting stuck in a suboptimal local minimum, we inflict random mutations to
* some Individuals in the population.
*/
fun performMutation(population: List<Individual>): List<Individual>
}
/**
* A number denoting how fit an Individual is. The lower the score, the better.
*/
typealias Score = Double
| 0 | Kotlin | 0 | 0 | 80db7e7029dace244a05f7e6327accb212d369cc | 3,273 | adventofcode2018 | MIT License |
src/Day03.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | fun main() {
fun Char.priority(): Int = when {
isUpperCase() -> code - 'A'.code + 27
else -> code - 'a'.code + 1
}
fun part1(input: List<String>): Int {
return input.sumOf { row ->
val (a, b) = row.chunked(row.length / 2)
a.asSequence().first { b.contains(it) }.priority()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { rows ->
val (a, b, c) = rows
a.asSequence().first { b.contains(it) && c.contains(it) }.priority()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157) { "part1 check failed" }
check(part2(testInput) == 70) { "part2 check failed" }
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 900 | aoc2022 | Apache License 2.0 |
src/Day07.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | import kotlin.LazyThreadSafetyMode.NONE
fun main() {
class File(
val name: String,
val size: Int
) {
override fun toString() = name
}
class Directory(
val name: String,
val parent: Directory?,
val dirs: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf(),
) {
override fun toString() = name
fun walkDirs(cb: (Directory) -> Unit) {
cb(this)
for (dir in dirs) {
dir.walkDirs(cb)
}
}
val size: Int by lazy(NONE) { files.sumOf { it.size } + dirs.sumOf { it.size } }
}
fun parseFs(input: List<String>): Directory {
val root = Directory("/", null)
var cd = root
var i = 0
while (i in input.indices) {
val line = input[i]
val parts = line.split(' ')
check(parts[0] == "$")
when {
parts[1] == "ls" -> {
while (++i in input.indices && !input[i].startsWith("$")) {
val (sizeOrDir, name) = input[i].split(" ")
if (sizeOrDir == "dir") {
cd.dirs += Directory(name, cd)
} else {
cd.files += File(name, sizeOrDir.toInt())
}
}
}
parts[1] == "cd" -> {
cd = when (val name = parts[2]) {
"/" -> root
".." -> cd.parent!!
else -> cd.dirs.first { it.name == name }
}
i++
}
else -> throw IllegalStateException()
}
}
return root
}
fun part1(input: List<String>): Int {
val root = parseFs(input)
var sum = 0
root.walkDirs {
val size = it.size
if (size < 100000) sum += size
}
return sum
}
fun part2(input: List<String>): Int {
val root = parseFs(input)
val usedSpace = root.size
val freeSpace = 70_000_000 - usedSpace
val reqFreeSpace = 30_000_000
val requiredSize = reqFreeSpace - freeSpace
val candidates = mutableListOf<Directory>()
root.walkDirs {
if (it.size >= requiredSize) candidates += it
}
return candidates.minOf { it.size }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 2,800 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/aoc22/Day02.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc22
import aoc22.Day02Common.summed
import aoc22.Day02Common.toRoundsUsing
import aoc22.DomainRPS.Outcome
import aoc22.DomainRPS.Outcome.*
import aoc22.DomainRPS.Play
import aoc22.DomainRPS.Play.*
import aoc22.DomainRPS.Round
import aoc22.DomainRPS.points
import aoc22.DomainRPS.toOutcome
import common.Year22
object Day02: Year22 {
fun List<String>.part1(): Int = toRoundsUsing(Day02Part1::toPlays).summed()
fun List<String>.part2(): Int = toRoundsUsing(Day02Part2::toPlaysForOutcome).summed()
}
object Day02Common {
fun List<String>.toRoundsUsing(toPlays: Keys.() -> Plays): Rounds =
with(Day02Parser) { toKeys() }.toPlays().map { it.toRound() }
private fun Pair<Play, Play>.toRound() = Round(first, second)
fun List<Round>.summed() = map { it.toOutcome().points() + it.yourPlay.points() }.sum()
}
private val theirPlayMap = mapOf("A" to Rock, "B" to Paper, "C" to Scissors)
object Day02Part1 {
private val yourPlayMap = mapOf("X" to Rock, "Y" to Paper, "Z" to Scissors)
fun toPlays(keys: Keys): Plays =
keys.map { (theirKey, yourKey) ->
theirPlayMap[theirKey]!! to yourPlayMap[yourKey]!!
}
}
object Day02Part2 {
private val yourOutcomeMap = mapOf("X" to Lose, "Y" to Draw, "Z" to Win)
fun toPlaysForOutcome(keys: Keys): Plays =
keys.map { (theirKey, yourKey) ->
theirPlayMap[theirKey]!!.let { theirPlay ->
theirPlay to theirPlay.playFor(yourOutcomeMap[yourKey]!!)
}
}
private fun Play.playFor(outcome: Outcome): Play =
Play.values().first { Round(this, it).toOutcome() == outcome }
}
object Day02Parser {
fun List<String>.toKeys(): Keys = map { it.split(" ").run { this[0] to this[1] } }
}
private typealias Keys = List<Pair<String, String>>
private typealias Plays = List<Pair<Play, Play>>
private typealias Rounds = List<Round>
object DomainRPS {
enum class Play {
Rock, Paper, Scissors
}
fun Play.points(): Int =
when (this) {
Rock -> 1
Paper -> 2
Scissors -> 3
}
private fun Play.beats(): Play =
when (this) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
data class Round(val theirPlay: Play, val yourPlay: Play)
fun Round.toOutcome(): Outcome =
when {
yourPlay.beats() == theirPlay -> Win
yourPlay == theirPlay -> Draw
else -> Lose
}
enum class Outcome { Win, Lose, Draw }
fun Outcome.points(): Int =
when (this) {
Win -> 6
Draw -> 3
Lose -> 0
}
} | 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 2,732 | aoc | Apache License 2.0 |
grind-75-kotlin/src/main/kotlin/FirstBadVersion.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | /**
* You are a product manager and currently leading a team to develop a new product.
* Unfortunately, the latest version of your product fails the quality check.
* Since each version is developed based on the previous version, all the versions after a bad version are also bad.
*
* Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one,
* which causes all the following ones to be bad.
*
* You are given an API bool isBadVersion(version) which returns whether version is bad.
* Implement a function to find the first bad version. You should minimize the number of calls to the API.
*
*
*
* Example 1:
*
* Input: n = 5, bad = 4
* Output: 4
* Explanation:
* call isBadVersion(3) -> false
* call isBadVersion(5) -> true
* call isBadVersion(4) -> true
* Then 4 is the first bad version.
* Example 2:
*
* Input: n = 1, bad = 1
* Output: 1
*
*
* Constraints:
*
* 1 <= bad <= n <= 2^31 - 1
* @see <a href="https://leetcode.com/problems/first-bad-version/">LeetCode</a>
*
* The isBadVersion API is defined in the parent class VersionControl.
* fun isBadVersion(version: Int) : Boolean {}
*/
class Solution : VersionControl() {
override fun firstBadVersion(n: Int): Int {
return recursivelyFindFirstBadVersion(1, n)
}
private fun recursivelyFindFirstBadVersion(start: Int, end: Int): Int {
if (start == end) {
return start
}
val mid = start + (end - start) / 2
return if (isBadVersion(mid)) {
recursivelyFindFirstBadVersion(start, mid)
} else {
recursivelyFindFirstBadVersion(mid + 1, end)
}
}
}
abstract class VersionControl {
abstract fun firstBadVersion(n: Int): Int
fun isBadVersion(version: Int): Boolean {
return version > 0
}
}
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 1,829 | grind-75 | Apache License 2.0 |
src/main/kotlin/Day02.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | fun main() {
val ROCK_ENEMY = 'A'
val PAPER_ENEMY = 'B'
val SCISSORS_ENEMY = 'C'
val enemyChoiceMap = mapOf(
Pair(ROCK_ENEMY, Choice.ROCK),
Pair(PAPER_ENEMY, Choice.PAPER),
Pair(SCISSORS_ENEMY, Choice.SCISSORS)
)
val choiceScores = mapOf(
Pair(Choice.ROCK, 1),
Pair(Choice.PAPER, 2),
Pair(Choice.SCISSORS, 3)
)
val looseMap = mapOf(
Pair(Choice.ROCK, Choice.SCISSORS),
Pair(Choice.PAPER, Choice.ROCK),
Pair(Choice.SCISSORS, Choice.PAPER),
)
val winMap = mapOf(
Pair(Choice.SCISSORS, Choice.ROCK),
Pair(Choice.ROCK, Choice.PAPER),
Pair(Choice.PAPER, Choice.SCISSORS),
)
val resultScoreMap = mapOf(
Pair(Result.LOOSE, 0),
Pair(Result.DRAW, 3),
Pair(Result.WIN, 6)
)
fun part1(input: List<String>): Int {
val ROCK_ME = 'X'
val PAPER_ME = 'Y'
val SCISSORS_ME = 'Z'
val myChoiceMap = mapOf(
Pair(ROCK_ME, Choice.ROCK),
Pair(PAPER_ME, Choice.PAPER),
Pair(SCISSORS_ME, Choice.SCISSORS)
)
var score = 0
for (line in input) {
val splitLine = line.split(' ')
val enemyChoice = enemyChoiceMap.get(splitLine[0].get(0))
val myChoice = myChoiceMap.get(splitLine[1].get(0))
score += choiceScores.getOrDefault(myChoice, 0)
if (enemyChoice == myChoice) {
score += resultScoreMap.getOrDefault(Result.DRAW, 0)
continue
}
val myLooseChoice = looseMap.getOrDefault(enemyChoice, Choice.ROCK)
if (myChoice == myLooseChoice) {
continue
}
val myWinChoice = winMap.getOrDefault(enemyChoice, Choice.ROCK)
if (myChoice == myWinChoice) {
score += 6
continue
}
}
return score
}
fun part2(input: List<String>): Int {
val LOOSE = 'X'
val DRAW = 'Y'
val WIN = 'Z'
val resultMap = mapOf(
Pair(LOOSE, Result.LOOSE),
Pair(DRAW, Result.DRAW),
Pair(WIN, Result.WIN)
)
var score = 0
for (line in input) {
val splitLine = line.split(' ')
val enemyChoice = enemyChoiceMap.getOrDefault(splitLine[0].get(0), Choice.ROCK)
val wantedResult = resultMap.get(splitLine[1].get(0))
var myChoice = Choice.ROCK
if (wantedResult == Result.DRAW) {
myChoice = enemyChoice
}
if (wantedResult == Result.LOOSE) {
myChoice = looseMap.getOrDefault(enemyChoice, Choice.ROCK)
}
if (wantedResult == Result.WIN) {
myChoice = winMap.getOrDefault(enemyChoice, Choice.ROCK)
}
score += choiceScores.getOrDefault(myChoice, 0)
score += resultScoreMap.getOrDefault(wantedResult, 0)
}
return score
}
val input = readFileAsList("Day02")
println(part1(input))
println(part2(input))
}
enum class Choice {
ROCK,
PAPER,
SCISSORS
}
enum class Result {
WIN,
LOOSE,
DRAW
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 3,279 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/leetcode/monthly_challenges/2021/april/alien_dictionary/Main.kt | frikit | 254,842,734 | false | null | package com.leetcode.monthly_challenges.`2021`.april.alien_dictionary
fun main() {
println("Test case 1:")
println(Solution().isAlienSorted(arrayOf("hello", "leetcode"), "hlabcdefgijkmnopqrstuvwxyz"))//true
println()
println("Test case 2:")
println(Solution().isAlienSorted(arrayOf("word", "world", "row"), "worldabcefghijkmnpqstuvxyz"))//false
println()
println("Test case 3:")
println(Solution().isAlienSorted(arrayOf("apple", "app"), "abcdefghijklmnopqrstuvwxyz"))//false
println()
}
//class Solution {
// fun isAlienSorted(words: Array<String>, order: String): Boolean {
// val dictionary = order.toCharArray().mapIndexed { index, c -> c to index }.toMap()
//
// for (word in words) {
// var lastMaxIndex = -1
// for (char in word.toCharArray()) {
// val currIdx = dictionary[char] ?: return false
// if (currIdx >= lastMaxIndex) {
// lastMaxIndex = currIdx
// } else {
// return false
// }
// }
// }
//
// return true
// }
//}
class Solution {
var mapping = IntArray(26)
fun isAlienSorted(words: Array<String>, order: String): Boolean {
for (i in order.indices) mapping[order[i] - 'a'] = i
for (i in 1 until words.size) if (bigger(words[i - 1], words[i])) return false
return true
}
fun bigger(s1: String, s2: String): Boolean {
val n = s1.length
val m = s2.length
var i = 0
while (i < n && i < m) {
if (s1[i] != s2[i]) return mapping[s1[i] - 'a'] > mapping[s2[i] - 'a']
++i
}
return n > m
}
}
| 0 | Kotlin | 0 | 0 | dda68313ba468163386239ab07f4d993f80783c7 | 1,720 | leet-code-problems | Apache License 2.0 |
src/Day24.kt | Jintin | 573,640,224 | false | {"Kotlin": 30591} | import java.util.LinkedList
fun main() {
var width = 0
var height = 0
fun checkBlockPosition(x: Int, y: Int, value: Char, map: List<List<Char>>): Boolean {
val w = width - 2
val h = height - 2
return map[1 + ((x - 1 + w) % w)][1 + ((y - 1 + h) % h)] == value
}
fun check(map: List<List<Char>>, x: Int, y: Int, diffX: Int, diffY: Int): Boolean {
if (x < 0 || x >= map.size || y < 0 || y >= map[0].size) {
return false
}
if (map[x][y] == '#') {
return false
}
if (x == 0 || x == width - 1) {
return true
}
if (checkBlockPosition(x - diffX, y, 'v', map)) {
return false
}
if (checkBlockPosition(x + diffX, y, '^', map)) {
return false
}
if (checkBlockPosition(x, y - diffY, '>', map)) {
return false
}
if (checkBlockPosition(x, y + diffY, '<', map)) {
return false
}
return true
}
fun iterate(start: Pair<Int, Int>, goal: Pair<Int, Int>, offset: Int, map: List<List<Char>>): Int {
val q = LinkedList<Pair<Int, Int>>()
q.offer(start)
var step = offset
while (!q.isEmpty()) {
var size = q.size
val set = mutableSetOf<Pair<Int, Int>>()
while (size-- > 0) {
val current = q.poll()
val x = current.first
val y = current.second
val diffX = (step + 1) % (width - 2)
val diffY = (step + 1) % (height - 2)
if (x == goal.first && y == goal.second) {
return step
}
if (check(map, x - 1, y, diffX, diffY)) {
set.add(Pair(x - 1, y))
}
if (check(map, x + 1, y, diffX, diffY)) {
set.add(Pair(x + 1, y))
}
if (check(map, x, y - 1, diffX, diffY)) {
set.add(Pair(x, y - 1))
}
if (check(map, x, y + 1, diffX, diffY)) {
set.add(Pair(x, y + 1))
}
if (check(map, x, y, diffX, diffY)) {
set.add(Pair(x, y))
}
}
q.addAll(set)
step++
}
return -1
}
fun part1(input: List<String>): Int {
val map = input.map { line -> line.map { it } }
return iterate(Pair(0, 1), Pair(width - 1, height - 2), 0, map)
}
fun part2(input: List<String>): Int {
val map = input.map { line -> line.map { it } }
val start = Pair(0, 1)
val end = Pair(width - 1, height - 2)
val a = iterate(start, end, 0, map)
val b = iterate(end, start, a, map)
val c = iterate(start, end, b, map)
println("$a $b $c")
return c
}
val input = readInput("Day24")
width = input.size
height = input[0].length
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 4aa00f0d258d55600a623f0118979a25d76b3ecb | 3,077 | AdventCode2022 | Apache License 2.0 |
src/main/kotlin/days/Solution23.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.Point2D
import adventOfCode.util.plus
import kotlin.math.max
typealias TrailMap = Map<Point2D, Map<Point2D, Int>>
private val directions = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)
private val slopeToDirection = listOf('v', '>', '^', '<').zip(directions).toMap()
object Solution23 : Solution<Triple<TrailMap, Point2D, Point2D>>(AOC_YEAR, 23) {
override fun getInput(handler: InputHandler): Triple<TrailMap, Point2D, Point2D> {
val grid = handler.getInput("\n")
val digraph = mutableMapOf<Point2D, MutableMap<Point2D, Int>>().withDefault { mutableMapOf() }
val start = 0 to 1
val end = grid.size - 1 to grid[0].length - 2
val seen = mutableSetOf<Point2D>()
val queue = ArrayDeque<Triple<Int, Point2D, Point2D>>()
queue.add(Triple(0, start, start))
while (queue.isNotEmpty()) {
val (n, curr, junction) = queue.removeLast()
var paths = 0
val nextPoints = mutableListOf<Point2D>()
for (d in directions) {
val (ii, jj) = curr + d
if (ii !in grid.indices || jj !in grid[0].indices) continue
val c = grid[ii][jj]
if (c == '#') continue
paths++
if (ii to jj in seen) continue
val slopeDirection = slopeToDirection[c]
if (slopeDirection != null && d != slopeDirection) continue
nextPoints.add(ii to jj)
}
if (paths > 2 || curr == end) {
val adjs = digraph.getValue(junction)
adjs[curr] = n
digraph[junction] = adjs
nextPoints.forEach { queue.add(Triple(1, it, curr)) }
} else {
seen.add(curr)
nextPoints.forEach { queue.add(Triple(n + 1, it, junction)) }
}
}
val (firstJunction, startCost) = digraph.getValue(start).entries.first()
val (lastJunction, endCost) = digraph.entries.first { end in it.value }.let { it.key to it.value.getValue(end) }
digraph.remove(start)
digraph.entries.forEach { (node, adjs) ->
if (node == firstJunction) adjs.keys.forEach { adjs.merge(it, startCost, Int::plus) }
if (lastJunction in adjs) adjs.merge(lastJunction, endCost, Int::plus)
}
return Triple(digraph, firstJunction, lastJunction)
}
private fun TrailMap.findLongestPath(start: Point2D, end: Point2D): Int {
var ret = 0
val queue = ArrayDeque<Triple<Int, Point2D, Set<Point2D>>>()
queue.add(Triple(0, start, setOf(start)))
while (queue.isNotEmpty()) {
val (cost, curr, seen) = queue.removeLast()
if (curr == end) ret = max(ret, cost)
else this.getValue(curr).entries
.filter { it.key !in seen }
.forEach { (adj, edgeCost) -> queue.add(Triple(cost + edgeCost, adj, seen + adj)) }
}
return ret
}
private fun TrailMap.toGraph(): TrailMap {
val graph = mutableMapOf<Point2D, Map<Point2D, Int>>().withDefault { mapOf() }
this.entries.forEach { (node, adjs) ->
adjs.entries.forEach { (adj, cost) ->
graph[node] = graph.getValue(node) + (adj to cost)
graph[adj] = graph.getValue(adj) + (node to cost)
}
}
return graph
}
override fun solve(input: Triple<TrailMap, Point2D, Point2D>): PairOf<Int> {
val (digraph, start, end) = input
val ans1 = digraph.findLongestPath(start, end)
val ans2 = digraph.toGraph().findLongestPath(start, end)
return ans1 to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 3,817 | Advent-of-Code-2023 | MIT License |
kotlin/src/com/leetcode/64_MinimumPathSum.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
import kotlin.math.min
//Partial sum vector. Time: O(n*m). Space: O(m)
private class Solution64 {
fun minPathSum(grid: Array<IntArray>): Int {
val waveGrid = IntArray(grid[0].size)
for (i in grid.indices) {
for (j in grid[i].indices) {
waveGrid[j] = when {
j == 0 -> waveGrid[j]
i == 0 -> waveGrid[j - 1]
else -> min(waveGrid[j], waveGrid[j - 1])
} + grid[i][j]
}
}
return waveGrid.last()
}
}
//Partial sum matrix. Time: O(n*m). Space: O(n*m)
private class Solution64old1 {
fun minPathSum(grid: Array<IntArray>): Int {
val waveGrid = Array(grid.size) { IntArray(grid[it].size) }
for (i in grid.indices) {
for (j in grid[i].indices) {
waveGrid[i][j] = when {
i == 0 && j == 0 -> 0
i == 0 -> waveGrid[i][j - 1]
j == 0 -> waveGrid[i - 1][j]
else -> min(waveGrid[i - 1][j], waveGrid[i][j - 1])
} + grid[i][j]
}
}
return waveGrid.last().last()
}
}
fun main() {
println(Solution64().minPathSum(arrayOf(
intArrayOf(1,3,1),
intArrayOf(1,5,1),
intArrayOf(4,2,1)
)))
} | 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 1,351 | problemsolving | Apache License 2.0 |
src/Day16.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | import java.time.Duration
import java.time.Instant
import java.util.*
import kotlin.time.toKotlinDuration
private typealias Mask = Long
private typealias Position = Int
private typealias Score = Int
fun main() {
fun Long.get(i: Int) = (this shr i) and 1 == 1L
fun Long.set(i: Int) = this or (1L shl i)
fun part1(input: List<String>): Int {
val n = input.size
val p = "Valve (?<name>.*) has flow rate=(?<rate>.*); tunnels? leads? to valves? (?<valves>.*)".toPattern()
val rates = input.map { s -> p.matcher(s).also { it.find() }.group("rate")!!.toInt() }.toIntArray()
var start = -1
val edges = run {
val names = input.map { s -> p.matcher(s).also { it.find() }.group("name")!! }
start = names.indexOf("AA")
input.map { s ->
p.matcher(s).also { it.find() }
.group("valves")!!
.split(", ")
.map { names.indexOf(it) }
.toIntArray()
}.toTypedArray()
}
val dist = Array(n) { IntArray(n) { Int.MAX_VALUE } }.apply {
for (i in 0 until n) this[i][i] = 0
for (i in 0 until n) for (to in edges[i]) this[i][to] = 1
for (i in 0 until n) for (to in edges[i]) this[to][i] = 1
for (k in 0 until n) {
for (i in 0 until n) {
for (j in 0 until n) {
if (this[i][k] != Int.MAX_VALUE && this[k][j] != Int.MAX_VALUE) {
this[i][j] = minOf(this[i][j], this[i][k] + this[k][j])
}
}
}
}
}
var dp = HashMap<Pair<Int, Long>, Int>() // {pos, used} => score
dp[start to 0L] = 0
var maxScore = -1
val startTime = Instant.now()
fun spent() = Duration.between(startTime, Instant.now()).toKotlinDuration().toIsoString()
for (time in 29 downTo 1) {
println("(${spent()}) Time $time")
val dp1 = HashMap<Pair<Int, Long>, Int>()
fun update(pos: Int, used: Long, score: Int) {
dp1.merge(pos to used, score, ::maxOf)
if (score > maxScore) {
maxScore = score
println("(${spent()}) Updated max score: $maxScore")
}
}
for ((k, score) in dp) {
val (pos, used) = k
if (((used shr pos) and 1L) == 0L) {
update(pos, used or (1L shl pos), score + time * rates[pos])
}
for (to in edges[pos]) {
update(to, used, score)
}
}
val toRemove = mutableListOf<Pair<Int, Long>>()
val entries = dp1.entries
.sortedBy { it.key.second }
.groupBy { it.key.first }
.mapValues { (_, v) ->
v.associate { entry -> entry.key.second to entry.value }
}
for ((pos, v) in entries) {
val curEntries = v.toList()
outer@ for (curIndex in curEntries.indices) {
val x = curEntries[curIndex]
for (j in curIndex + 1 until curEntries.size) {
val y = curEntries[j]
if (x.second or y.second == y.second) {
var addition = 0
for (i in 0 until n) {
if (!x.first.get(i) && y.first.get(i)) {
val m = maxOf(0, time - dist[pos][i])
addition += m * rates[i]
}
}
if (x.second + addition < y.second) {
toRemove += pos to x.first
continue@outer
}
}
}
}
}
for (r in toRemove) requireNotNull(dp1.remove(r))
dp = dp1
}
return maxScore
}
fun part2(input: List<String>): Int {
class Part2Solver {
private val n = input.size
private val startTime = Instant.now()
private fun spent() = Duration.between(startTime, Instant.now()).toKotlinDuration().toIsoString()
private var maxScore = -1
private val p =
"Valve (?<name>.*) has flow rate=(?<rate>.*); tunnels? leads? to valves? (?<valves>.*)".toPattern()
private val rates = input.map { s -> p.matcher(s).also { it.find() }.group("rate")!!.toInt() }.toIntArray()
private var start = -1
private val edges = run {
val names = input.map { s -> p.matcher(s).also { it.find() }.group("name")!! }
start = names.indexOf("AA")
input.map { s ->
p.matcher(s).also { it.find() }
.group("valves")!!
.split(", ")
.map { names.indexOf(it) }
.toIntArray()
}.toTypedArray()
}
private val dist = Array(n) { IntArray(n) { Int.MAX_VALUE } }.apply {
for (i in 0 until n) this[i][i] = 0
for (i in 0 until n) for (to in edges[i]) this[i][to] = 1
for (i in 0 until n) for (to in edges[i]) this[to][i] = 1
for (k in 0 until n) {
for (i in 0 until n) {
for (j in 0 until n) {
if (this[i][k] != Int.MAX_VALUE && this[k][j] != Int.MAX_VALUE) {
this[i][j] = minOf(this[i][j], this[i][k] + this[k][j])
}
}
}
}
}
private val dp = Array(n) { Array(n) { HashMap<Mask, Position>() } }.apply {
this[start][start][0L] = 0
}
private val dp1 = Array(n) { Array(n) { HashMap<Mask, Position>() } }
private fun update(pos1: Position, pos2: Position, used: Mask, score: Score) {
val current = dp1[minOf(pos1, pos2)][maxOf(pos1, pos2)]
val prev = current[used]
if (prev == null || prev < score) {
current[used] = score
if (score > maxScore) {
maxScore = score
println("(${spent()}) Updated max score: $maxScore")
}
}
}
fun solve(): Int {
for (time in 25 downTo 1) {
println("(${spent()}) Time $time")
for (i in 0 until n) for (j in 0 until n) dp1[i][j] = HashMap()
for (pos1 in 0 until n) {
val rate1 = rates[pos1]
val edges1 = edges[pos1]
for (pos2 in pos1 until n) {
val rate2 = rates[pos2]
val edges2 = edges[pos2]
for ((used, score) in dp[pos1][pos2]) {
if (!used.get(pos1)) {
val extra = if (used.get(pos2) || pos1 == pos2) 0 else rate2
update(pos1, pos2, used.set(pos1).set(pos2), score + time * (rate1 + extra))
for (to2 in edges2) {
update(pos1, to2, used.set(pos1), score + time * rate1)
}
}
if (!used.get(pos2)) {
for (to1 in edges1) {
update(to1, pos2, used.set(pos2), score + time * rate2)
}
}
for (to1 in edges1) {
for (to2 in edges2) {
update(to1, to2, used, score)
}
}
}
}
}
for (pos1 in 0 until n) {
val dist1 = dist[pos1]
for (pos2 in pos1 until n) {
val current = dp1[pos1][pos2]
val entries = current.entries
.sortedBy(MutableMap.MutableEntry<Mask, Score>::key)
for (big in entries.indices) {
val (maskBig, scoreBig) = entries[big]
for (small in 0 until big) {
val (maskSmall, scoreSmall) = entries[small]
if ((maskSmall or maskBig) == maskBig && scoreSmall >= scoreBig) {
current.remove(entries[big].key)
break
}
}
}
val dist2 = dist[pos2]
for ((mask, score) in current.entries.toList()) {
var extra = 0
for (i in 0 until n) {
if (!mask.get(i)) {
val minDist = minOf(dist1[i], dist2[i])
extra += maxOf((time - 1 - minDist) * rates[i], 0)
}
}
if (score + 500 < maxScore || score + extra < maxScore) {
current.remove(mask)
}
}
}
}
for (i in 0 until n) for (j in 0 until n) dp[i][j] = dp1[i][j]
}
return maxScore
}
}
return Part2Solver().solve()
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 16)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 10,773 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/schlaubi/aoc/days/Day7.kt | DRSchlaubi | 573,014,474 | false | {"Kotlin": 21541} | package dev.schlaubi.aoc.days
import dev.schlaubi.aoc.Day
import kotlin.io.path.readLines
private val cdPattern = """\$ cd (.*)""".toRegex()
private val lsPattern = """\$ ls""".toRegex()
private val filePattern = """(\d+) ((.*)(?:\.(.*))?)""".toRegex()
private data class SizedDirectory(val size: Int, val directory: FileSystemEntity.Directory)
private const val INDENT_STEP = 2
sealed interface FileSystemEntity {
val name: String
fun calculateSize(): Int
data class File(val size: Int, override val name: String) : FileSystemEntity {
override fun toString(): String = "$size $name"
override fun calculateSize(): Int = size
}
data class Directory(override val name: String, val children: List<FileSystemEntity>) : FileSystemEntity {
override fun toString(): String = toString(0)
private fun toString(indent: Int): String = buildString {
fun indent(actual: Int = indent) = if (actual > 0) append(" ".repeat(actual)) else this
indent().append("dir $name")
if (children.isNotEmpty()) {
appendLine()
children.forEach {
if (it is Directory) {
append(it.toString(indent + INDENT_STEP))
} else {
indent(indent + INDENT_STEP).appendLine(it)
}
}
}
}
override fun calculateSize(): Int = children.sumOf {
when (it) {
is Directory -> it.calculateSize()
is File -> it.size
}
}
}
}
private const val STORAGE_SPACE_90001 = 70000000
private const val OS_UPDATE_9001 = 30000000
object Day7 : Day<FileSystemEntity.Directory>() {
override val number: Int = 7
override fun prepare(): FileSystemEntity.Directory {
val lines = input.readLines().iterator()
fun doDirectory(name: String): FileSystemEntity.Directory {
val children = buildList {
while (lines.hasNext()) {
val line = lines.next()
val cdMatch = cdPattern.matchEntire(line)
when {
cdMatch != null -> {
val (destination) = cdMatch.destructured
if (destination == "..") break // no further lines will be for this directory
add(doDirectory(destination))
}
lsPattern.matches(line) -> Unit // be happy about next incoming lines
else -> {
filePattern.matchEntire(line)?.let {
val (size, fileName) = it.destructured
add(FileSystemEntity.File(size.toInt(), fileName))
}
}
}
}
}
return FileSystemEntity.Directory(name, children)
}
val firstLine = lines.next()
val (destination) = cdPattern.matchEntire(firstLine)?.destructured
?: error("Could not match first line: $firstLine")
return doDirectory(destination)
}
override fun task1(prepared: FileSystemEntity.Directory): Any =
prepared.calculateSubdirectorySizes()
// o begin, find all of the directories with a total size of at most 100000
.filter { (size) -> size <= 100000 }
.sumOf(SizedDirectory::size)
override fun task2(prepared: FileSystemEntity.Directory): Any {
val rootSize = prepared.calculateSize()
val totalSpace = STORAGE_SPACE_90001
val free = totalSpace - rootSize
val remaining = OS_UPDATE_9001 - free
return prepared.calculateSubdirectorySizes()
.asSequence()
.filter { it.size >= remaining }
.sortedBy { it.size }
.first()
.size
}
}
private fun FileSystemEntity.Directory.calculateSubdirectorySizes(): List<SizedDirectory> = children
.asSequence()
.filterIsInstance<FileSystemEntity.Directory>()
.flatMap {
(it.calculateSubdirectorySizes() + SizedDirectory(it.calculateSize(), it)).asSequence()
}
.toList()
| 1 | Kotlin | 0 | 4 | 4514e4ac86dd3ed480afa907d907e3ae26457bba | 4,373 | aoc-2022 | MIT License |
src/main/kotlin/dev/paulshields/aoc/Day13.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 13: Transparent Origami
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.Point
import dev.paulshields.aoc.common.extractGroups
import dev.paulshields.aoc.common.readFileAsString
fun main() {
println(" ** Day 13: Transparent Origami ** \n")
val pageOne = readFileAsString("/Day13ManualPageOne.txt")
val numberOfDotsAfterOneFold = countVisibleDotsAfterFold(pageOne, 1)
println("Number of dots still visible after one fold is $numberOfDotsAfterOneFold")
val foldedPaper = printPaperAfterFolds(pageOne)
println("The final folded paper:\n")
println(foldedPaper)
}
fun countVisibleDotsAfterFold(transparentPaper: String, numberOfFolds: Int? = null) =
foldPaper(transparentPaper, numberOfFolds).size
fun printPaperAfterFolds(transparentPaper: String): String {
val dotsAfterFolds = foldPaper(transparentPaper)
val width = dotsAfterFolds.maxByOrNull { it.x }?.let { it.x + 1 } ?: 0
val height = dotsAfterFolds.maxByOrNull { it.y }?.let { it.y + 1 } ?: 0
val foldedPaper = MutableList(height) { MutableList(width) { "." } }
dotsAfterFolds.forEach { foldedPaper[it.y][it.x] = "#" }
return foldedPaper.joinToString("\n") { it.joinToString("") }
}
private fun foldPaper(transparentPaper: String, numberOfFolds: Int? = null): List<Point> {
var (dots, folds) = parseTransparentPaperSheet(transparentPaper)
val foldsToPerform = folds.take(numberOfFolds ?: folds.size)
foldsToPerform.forEach { fold ->
dots = dots.map {
when (fold.direction) {
"x" -> foldDotLeft(it, fold.line)
"y" -> foldDotUp(it, fold.line)
else -> it
}
}.distinct()
}
return dots
}
private fun foldDotLeft(dot: Point, foldLine: Int) =
if (dot.x > foldLine) Point(foldLine - (dot.x - foldLine), dot.y) else dot
private fun foldDotUp(dot: Point, foldLine: Int) =
if (dot.y > foldLine) Point(dot.x, foldLine - (dot.y - foldLine)) else dot
private fun parseTransparentPaperSheet(sheet: String): Pair<List<Point>, List<Fold>> {
val foldRegex = Regex("fold along ([xy])=(\\d+)")
val (dotsSheet, foldInstructions) = sheet.split("\n\n")
val dots = dotsSheet.lines().map {
Point.fromList(it.split(",").map { it.toInt() })
}
val folds = foldInstructions
.lines()
.map { foldRegex.extractGroups(it) }
.map { (direction, line) -> Fold(line.toInt(), direction) }
return dots to folds
}
data class Fold(val line: Int, val direction: String)
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 2,559 | AdventOfCode2021 | MIT License |
src/day10/Code.kt | fcolasuonno | 221,697,249 | false | null | package day10
import java.io.File
fun main() {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2()}")
}
private val assignStructure = """value (\d+) goes to bot (\d+)""".toRegex()
private val robotStructure = """bot (\d+) gives low to (output|bot) (\d+) and high to (output|bot) (\d+)""".toRegex()
interface Operable {
fun addValue(value: Int)
}
data class Assign(val value: Int, val bot: String)
data class Output(val output: String) : Operable {
val values = mutableListOf<Int>()
override fun addValue(value: Int) {
values += value
}
}
data class Robot(val name: String, val lowOutput: Boolean, val lowNumber: String, val highOutput: Boolean, val highNumber: String) : Operable {
val values = mutableListOf<Int>()
override fun addValue(value: Int) {
values += value
if (values.size == 2) {
low.addValue(values.min()!!)
high.addValue(values.max()!!)
}
}
lateinit var low: Operable
lateinit var high: Operable
}
val outputs = mutableMapOf<String, Output>()
fun parse(input: List<String>) = input.mapNotNull {
robotStructure.matchEntire(it)?.destructured?.let {
val (bot, lowOutput, lowNumber, highOutput, highNumber) = it.toList()
Robot(bot, lowOutput == "output", lowNumber, highOutput == "output", highNumber)
}
}.associateBy { it.name }.apply {
forEach { (_, bot) ->
bot.low = if (bot.lowOutput) outputs.getOrPut(bot.lowNumber) { Output(bot.lowNumber) } else getValue(bot.lowNumber)
bot.high = if (bot.highOutput) outputs.getOrPut(bot.highNumber) { Output(bot.highNumber) } else getValue(bot.highNumber)
}
input.mapNotNull {
assignStructure.matchEntire(it)?.destructured?.let {
val (value, bot) = it.toList()
Assign(value.toInt(), bot)
}
}.forEach {
getValue(it.bot).addValue(it.value)
}
}
fun part1(input: Map<String, Robot>) = input.values.single { it.values.toSet() == setOf(61, 17) }.name
fun part2() = listOf("0", "1", "2").map { outputs.getValue(it).values.single() }.reduce { acc, i -> acc * i }
| 0 | Kotlin | 0 | 0 | 73110eb4b40f474e91e53a1569b9a24455984900 | 2,320 | AOC2016 | MIT License |
src/Day4/Day04.kt | lukeqwas | 573,403,156 | false | null | package Day5
import readInput
//data class Range(val lowerBound: Int, val upperBound: Int)
fun main() {
val testInput = readInput("Day4/Day04")
var numPairs = 0
for(input in testInput) {
// find the smallest lower bound and see if the other range falls in the smalles lower bound range
val ranges = input.split(',')
val range1 = Range(ranges[0].split('-')[0].toInt(), ranges[0].split('-')[1].toInt())
val range2 = Range(ranges[1].split('-')[0].toInt(), ranges[1].split('-')[1].toInt())
if(range1.lowerBound >= range2.lowerBound && range1.lowerBound <= range2.upperBound) {
numPairs++
} else if(range2.lowerBound >= range1.lowerBound && range2.lowerBound <= range1.upperBound) {
numPairs++
}
}
println(numPairs)
}
class Range(private val num1: Int, private val num2: Int) {
val lowerBound: Int
val upperBound: Int
init {
lowerBound = Math.min(num1, num2)
upperBound = Math.max(num1, num2)
}
fun isSmaller(otherRange: Range): Boolean {
return Math.min(this.lowerBound, this.upperBound) < Math.min(otherRange.lowerBound, otherRange.upperBound)
}
}
| 0 | Kotlin | 0 | 0 | 6174a8215f8d4dc6d33fce6f8300a4a8999d5431 | 1,202 | aoc-kotlin-2022 | Apache License 2.0 |
2023/src/main/kotlin/day1.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
fun main() {
Day1.run()
}
object Day1 : Solution<List<String>>() {
override val name = "day1"
override val parser: Parser<List<String>> = Parser.lines
private val digits = (0..9).associateBy { it.toString() }
private val words = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
)
private fun getDigit(dictionary: Map<String, Int>, line: String, index: Int): Int? {
return dictionary.entries.firstOrNull { line.substring(index).startsWith(it.key) }?.value
}
private fun solve(input: List<String>, dictionary: Map<String, Int>): Int {
return input
.sumOf { line ->
val a = line.indices.firstNotNullOf { getDigit(dictionary, line, it) }
val b = line.indices.reversed().firstNotNullOf { getDigit(dictionary, line, it) }
a * 10 + b
}
}
override fun part1(input: List<String>): Int {
return solve(input, digits)
}
override fun part2(input: List<String>): Int {
return solve(input, digits + words)
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,135 | aoc_kotlin | MIT License |
src/main/kotlin/Main.kt | nikdim03 | 620,591,512 | false | null | import kotlin.random.Random
data class Cell(val row: Int, val col: Int)
fun main() {
val gridSize = 100
val fillPercentage = listOf(50, 75)
fillPercentage.forEach { percentage ->
val grid = generateGrid(gridSize, percentage)
val path = findPathWithLeastWhiteSquares(grid)
println("Filling percentage: $percentage%")
println("Path length: ${path.size}")
println("Number of white squares: ${path.count { grid[it.row][it.col] }}")
// printGridWithPath(grid, path)
GridVisualizer(grid, path, gridSize, percentage).display()
Thread.sleep(2000)
println()
}
}
fun generateGrid(gridSize: Int, fillPercentage: Int): Array<Array<Boolean>> {
val grid = Array(gridSize) { Array(gridSize) { false } }
for (row in grid.indices) {
for (col in grid[row].indices) {
grid[row][col] = Random.nextInt(100) > fillPercentage
}
}
return grid
}
fun findPathWithLeastWhiteSquares(grid: Array<Array<Boolean>>): List<Cell> {
val gridSize = grid.size
val weights = Array(gridSize) { Array(gridSize) { Int.MAX_VALUE } }
val visited = Array(gridSize) { Array(gridSize) { false } }
val previous = mutableMapOf<Cell, Cell?>()
// Init the top row
for (col in 0 until gridSize) {
weights[0][col] = if (grid[0][col]) 1 else 0
previous[Cell(0, col)] = null
}
while (true) {
val current = findMinimumWeightCell(weights, visited)
if (current == null || current.row == gridSize - 1) {
return buildPath(previous, current)
}
visited[current.row][current.col] = true
val neighbors = listOf(
// Cell(current.row - 1, current.col),
Cell(current.row + 1, current.col),
Cell(current.row, current.col - 1),
Cell(current.row, current.col + 1)
)
for (neighbor in neighbors) {
if (isValid(grid, visited, neighbor)) {
val weight = weights[current.row][current.col] + (if (grid[neighbor.row][neighbor.col]) 1 else 0)
if (weight < weights[neighbor.row][neighbor.col]) {
weights[neighbor.row][neighbor.col] = weight
previous[neighbor] = current
}
}
}
}
}
fun findMinimumWeightCell(weights: Array<Array<Int>>, visited: Array<Array<Boolean>>): Cell? {
var minWeight = Int.MAX_VALUE
var minWeightCell: Cell? = null
for (row in weights.indices) {
for (col in weights[row].indices) {
if (!visited[row][col] && weights[row][col] < minWeight) {
minWeight = weights[row][col]
minWeightCell = Cell(row, col)
}
}
}
return minWeightCell
}
fun buildPath(previous: Map<Cell, Cell?>, lastCell: Cell?): List<Cell> {
val path = mutableListOf<Cell>()
var current = lastCell
while (current != null) {
path.add(current)
current = previous[current]
}
return path.reversed()
}
fun isValid(grid: Array<Array<Boolean>>, visited: Array<Array<Boolean>>, cell: Cell): Boolean {
val (row, col) = cell
if (row < 0 || row >= grid.size || col < 0 || col >= grid.size) return false
return !visited[row][col]
}
fun printGridWithPath(grid: Array<Array<Boolean>>, path: List<Cell>) {
for (row in grid.indices) {
for (col in grid[row].indices) {
val cell = Cell(row, col)
when {
path.contains(cell) && grid[row][col] -> print("🟥")
path.contains(cell) && !grid[row][col] -> print("🟪")
grid[row][col] -> print("⬜")
else -> print("⬛")
}
}
println()
}
} | 0 | Kotlin | 0 | 0 | 3b12afbb67f96978b4c0f451e9911389364c4f6e | 3,778 | Percolation | MIT License |
src/main/kotlin/wtf/log/xmas2021/day/day04/Day04.kt | damianw | 434,043,459 | false | {"Kotlin": 62890} | package wtf.log.xmas2021.day.day04
import wtf.log.xmas2021.Day
import wtf.log.xmas2021.util.collect.Grid
import wtf.log.xmas2021.util.collect.mapCells
import wtf.log.xmas2021.util.collect.toGrid
import java.io.BufferedReader
object Day04 : Day<Day04.Input, Int, Int> {
override fun parseInput(reader: BufferedReader): Input = Input.parse(reader)
override fun part1(input: Input): Int {
val cards = input.hands.map(::Card)
var winningValue: Int? = null
var winningCard: Card? = null
outer@ for (value in input.drawnValues) {
for (card in cards) {
if (card.mark(value)) {
winningValue = value
winningCard = card
break@outer
}
}
}
return winningValue!! * winningCard!!.sumUnmarked()
}
override fun part2(input: Input): Int {
val cards = input.hands.map(::Card)
val winningHands = mutableSetOf<Grid<Int>>()
var winningValue: Int? = null
var winningCard: Card? = null
outer@ for (value in input.drawnValues) {
for (card in cards) {
val win = card.mark(value)
if (win && card.hand !in winningHands) {
winningHands += card.hand
winningValue = value
winningCard = card
if (winningHands.size == input.hands.size) {
break@outer
}
}
}
}
return winningValue!! * winningCard!!.sumUnmarked()
}
data class Input(
val drawnValues: List<Int>,
val hands: List<Grid<Int>>,
) {
companion object {
fun parse(reader: BufferedReader): Input {
val drawnValues = reader.readLine().split(',').map { it.toInt() }
check(reader.readLine().isEmpty())
val hands = reader
.readLines()
.chunked(Card.SIZE + 1)
.map { chunk ->
chunk
.take(Card.SIZE)
.map { line ->
line.trim().split(Regex("\\s+")).map { it.toInt() }
}
.toGrid()
}
.toList()
return Input(drawnValues, hands)
}
}
}
}
class Card(
val hand: Grid<Int>,
) {
private val cells = hand.mapCells { Cell(it) }
/**
* Marks the value on this card and returns true iff this was a winning call.
*/
fun mark(value: Int): Boolean {
for (cell in cells.values) {
if (cell.value == value) {
cell.mark()
}
}
return checkMarks()
}
fun sumUnmarked(): Int = cells.values.sumOf { if (it.isMarked) 0 else it.value }
private fun checkMarks(): Boolean {
return cells.rows.any { row -> row.all { it.isMarked } } ||
cells.columns.any { column -> column.all { it.isMarked } }
}
private class Cell(
val value: Int,
) {
var isMarked: Boolean = false
private set
fun mark() {
isMarked = true
}
override fun toString(): String = if (isMarked) "[$value]" else value.toString()
}
override fun toString(): String = cells.toString()
companion object {
const val SIZE = 5
}
}
| 0 | Kotlin | 0 | 0 | 1c4c12546ea3de0e7298c2771dc93e578f11a9c6 | 3,552 | AdventOfKotlin2021 | BSD Source Code Attribution |
src/main/kotlin/graph/variation/BestShortestPath.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.Vertex
import graph.core.WeightedEdge
import graph.core.WeightedGraph
import util.INF
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.set
// given a directed, positively weighted graph G = (V, E), two vertices s, t in V,
// find the shortest path from s to t, that not only minimizes the weight,
// but also minimizes the # of edges in the path
fun <V> WeightedGraph<V, Int>.bestShortestPath(s: Vertex<V>,
t: Vertex<V>,
checkIdentity: Boolean = true)
: List<Vertex<V>> {
val dist = HashMap<Vertex<V>, Int>()
val edgeCount = HashMap<Vertex<V>, Int>()
val parent = HashMap<Vertex<V>, Vertex<V>?>()
vertices.forEach {
dist[it] = INF
edgeCount[it] = INF
parent[it] = null
}
dist[s] = 0
edgeCount[s] = 0
val minHeap = PriorityQueue<Vertex<V>>(Comparator { u, v -> dist[u]!! - dist[v]!! })
minHeap.add(s)
while (minHeap.isNotEmpty()) {
val v = minHeap.remove()
getEdgesOf(v, checkIdentity).forEach { (start, end, isDirected, weight) ->
val u = if (isDirected || start == v) end else start
if (dist[v]!! + weight!! < dist[u]!!) {
dist[u] = dist[v]!! + weight
edgeCount[u] = edgeCount[v]!! + 1
parent[u] = v
minHeap.add(u)
} else if (dist[v]!! + weight == dist[u]!! && edgeCount[v]!! + 1 < edgeCount[u]!!) {
parent[u] = v
edgeCount[u] = edgeCount[v]!! + 1
minHeap.add(u)
}
}
}
val path = ArrayList<Vertex<V>>()
var curr: Vertex<V>? = t
while (curr != null) {
path.add(curr)
curr = parent[curr]
}
return path.reversed()
}
fun main(args: Array<String>) {
val V = (0..4).map { Vertex(it) }
val E = setOf(
WeightedEdge(V[0], V[1], true, 100),
WeightedEdge(V[0], V[2], true, 20),
WeightedEdge(V[1], V[4], true, 100),
WeightedEdge(V[2], V[3], true, 20),
WeightedEdge(V[3], V[4], true, 160))
val G = WeightedGraph(V, E)
println(G.bestShortestPath(V[0], V[4]))
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,014 | AlgoKt | MIT License |
src/main/kotlin/dev/bogwalk/batch4/Problem42.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch4
import dev.bogwalk.util.maths.isTriangularNumber
import dev.bogwalk.util.maths.lcm
import kotlin.math.sqrt
/**
* Problem 42: Coded Triangle Numbers
*
* https://projecteuler.net/problem=42
*
* Goal: Given an integer, if it is a triangle number tN, return its corresponding term n;
* otherwise, return -1.
*
* Constraints: 1 <= tN <= 1e18
*
* Triangle Number Sequence: The nth term is given by -> tN = n(n + 1) / 2 ->
* 1, 3, 6, 10, 15, 21, 28, 36, 45, 55,...
*
* e.g.: N = 2
* return -1, as 2 is not a triangle number; however,
* N = 3
* return 2, as 3 is the 2nd triangle number to exist.
*/
class CodedTriangleNumbers {
/**
* SPEED (WORSE) 1.4e5ns for tN = 1e18
*/
fun triangleNumber(tN: Long): Int = getTriangleTerm(tN) ?: -1
/**
* Triangle Number Sequence follows the pattern (odd, odd, even, even,...) & each tN is the
* sum of the previous tN & the current n.
*
* Rather than brute pre-computation of all triangle numbers below 1e18, this solution is
* based on the formula:
*
* tN = n(n + 1) / 2
*
* 2tN = n(n + 1)
*
* 2tN / n = n + 1 and 2tN / (n + 1) = n, therefore:
*
* 2tN == lcm(n, n + 1) and
*
* n must at minimum be sqrt(2tN)
*/
private fun getTriangleTerm(tN: Long): Int? {
val tN2 = 2 * tN
val n = sqrt(1.0 * tN2).toLong()
return if (tN2 == lcm(n, 1 + n)) n.toInt() else null
}
/**
* Solution formula optimised by using its derived inverse top-level function.
*
* SPEED (BETTER) 2.9e4ns for tN = 1e18
*/
fun triangleNumberImproved(tN: Long): Int = tN.isTriangularNumber() ?: -1
/**
* Project Euler specific implementation that returns the count, from an input of <2000
* words, of words whose summed alphabetical character value corresponds to a triangle number.
*
* e.g. "SKY" = 19 + 11 + 25 = 55 = t_10
*/
fun countTriangleWords(words: List<String>): Int {
return words.mapNotNull { word ->
// get alphabetical position based on 'A' code = 65
val num = word.sumOf { ch -> ch.code - 64L }
num.isTriangularNumber()
}.count()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,287 | project-euler-kotlin | MIT License |
src/Day13.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | import java.io.File
import java.lang.Exception
import kotlin.math.abs
import kotlin.math.min
import kotlin.reflect.typeOf
fun main() {
fun parseArray(iterator: ListIterator<String>): List<Any> {
val result = mutableListOf<Any>()
while (iterator.hasNext()) {
val token = iterator.next()
if (token == "]") {
return result
} else if (token == ",") {
continue
} else if (token == "[") {
result.add(parseArray(iterator))
} else {
val next = iterator.next()
if (next.matches("[0-9]".toRegex())) {
result.add((token + next).toInt())
} else {
result.add(token.toInt())
iterator.previous()
}
}
}
throw Exception("ko stana tuka")
}
fun doThingy(it: String): List<Any> {
val iterator = it.split("").filter { it != "" }.listIterator()
iterator.next()
return parseArray(iterator)
}
fun parseInput(input: String): List<List<List<Any>>> {
return input.split("\n\n")
.map { tuple ->
tuple
.split("\n")
.filter { it != "" }
.map { doThingy(it) }
}
}
fun parseInput2(input: String): List<List<Any>> {
return input.replace("\n\n", "\n")
.split("\n")
.filter { it != "" }
.map { doThingy(it) }
.plus(arrayListOf(arrayListOf(arrayListOf(2))))
.plus(arrayListOf(arrayListOf(arrayListOf(6))))
}
fun areCorrectlyOrdered(a: List<Any>, b: List<Any>): Boolean? {
for (i in 0 until min(a.size, b.size)) {
if (a[i] is Int && b[i] is Int) {
if (a[i] == b[i]) {
continue
}
return (a[i] as Int) < (b[i] as Int)
} else if (a[i] is List<*> && b[i] is List<*>) {
val comparison = areCorrectlyOrdered(a[i] as List<Any>, b[i] as List<Any>)
if (comparison != null) {
return comparison
}
} else if (a[i] is Int && b[i] is List<*>) {
val comparison = areCorrectlyOrdered(listOf(a[i]), b[i] as List<Any>)
if (comparison != null) {
return comparison
}
} else if (a[i] is List<*> && b[i] is Int) {
val comparison = areCorrectlyOrdered(a[i] as List<Any>, listOf(b[i]))
if (comparison != null) {
return comparison
}
}
}
if (a.size == b.size) {
return null
}
return a.size < b.size
}
fun notALambda(index: Int, anies: List<List<Any>>): Int {
val areCorrect =
areCorrectlyOrdered(anies[0], anies[1]) ?: throw Exception("kur tate banica")
return if (areCorrect) index + 1 else 0
}
fun part1(signal: List<List<List<Any>>>): Int {
return signal.mapIndexed { index, anies ->
notALambda(index, anies)
}.sum()
}
fun part2(signal: List<List<Any>>): Int {
val sorted = signal.sortedWith(Comparator<List<Any>> { a, b ->
if (areCorrectlyOrdered(a, b) == true) -1 else 1
})
var index1 = sorted.indexOf(arrayListOf(arrayListOf(2))) + 1
var index2 = sorted.indexOf(arrayListOf(arrayListOf(6))) + 1
return index1 * index2
}
// test if implementation meets criteria from the description, like:
val testInput = parseInput(File("src", "Day13_test.txt").readText())
val testInput2 = parseInput2(File("src", "Day13_test.txt").readText())
// println(part1(testInput))
println(part2(testInput2))
val input = parseInput(File("src", "Day13.txt").readText())
// println(part1(input))
val input2 = parseInput2(File("src", "Day13.txt").readText())
println(part2(input2))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 4,073 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/valid_number/ValidNumber.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.valid_number
import datsok.shouldEqual
import org.junit.jupiter.api.Test
//
// https://leetcode.com/problems/valid-number ✅
//
// A valid number can be split up into these components (in order):
// A decimal number or an integer.
// (Optional) An 'e' or 'E', followed by an integer.
//
// A decimal number can be split up into these components (in order):
// (Optional) A sign character (either '+' or '-').
// One of the following formats:
// One or more digits, followed by a dot '.'.
// One or more digits, followed by a dot '.', followed by one or more digits.
// A dot '.', followed by one or more digits.
//
// An integer can be split up into these components (in order):
// (Optional) A sign character (either '+' or '-').
// One or more digits.
//
// For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"],
// while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].
//
// Given a string s, return true if s is a valid number.
//
// Constraints:
// 1 <= s.length <= 20
// s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.
//
class ValidNumber {
@Test fun `valid numbers`() {
listOf("2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789")
.filterNot { isNumber(it) } shouldEqual emptyList()
}
@Test fun `invalid numbers`() {
listOf("abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53")
.filter { isNumber(it) } shouldEqual emptyList()
}
@Test fun `is integer`() {
listOf("1", "123", "-123", "+123").filterNot { isNumber(it) } shouldEqual emptyList()
listOf("", "+", "123-", "1-23", "+-123").filter { isNumber(it) } shouldEqual emptyList()
}
@Test fun `is decimal`() {
listOf("1.", "123.", "1.23", "+1.23", ".123", "+.123").filterNot { isNumber(it) } shouldEqual emptyList()
listOf("+.", ".", "1.2.3").filter { isNumber(it) } shouldEqual emptyList()
}
private fun isNumber(s: String): Boolean {
val int = """[-+]?\d+"""
val decimal = """[-+]?(?:\d+\.\d*|\.\d+)"""
if (Regex(int).matches(s)) return true
if (Regex(decimal).matches(s)) return true
if (Regex("""(?x)
|(?:$int|$decimal)
|(?:[eE]$int)?
|""".trimMargin()).matches(s)) return true
return false
}
}
fun isNumber_old(s: String): Boolean {
var i = 0
fun letter(): Char =
if (i < s.length) s[i] else 0.toChar()
fun digits(): Boolean {
val match = letter() in '0'..'9'
if (!match) return false
i++
digits()
return true
}
fun exponent(): Boolean {
if (letter() != 'e') return false
i++
if (letter() == '-' || letter() == '+') i++
if (!digits()) return false
if (letter() == '.') {
i++
digits()
}
return true
}
fun factor(): Boolean {
if (letter() == '.') {
i++
return digits()
} else {
return exponent()
}
}
fun spaces(): Boolean {
if (letter() == ' ') {
i++
spaces()
}
return true
}
fun number(): Boolean {
spaces()
if (letter() == '-' || letter() == '+') i++
if (!digits()) return false
factor()
spaces()
return true
}
return number() && i == s.length
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 3,700 | katas | The Unlicense |
src/Day02.kt | revseev | 573,354,544 | false | {"Kotlin": 9868} | import GameResult.*
fun main() {
println(day2task1())
println(day2task2())
}
fun day2task1(): Int {
var userScore = 0
readInputAsSequence("Day02") {
userScore = sumOf { getScore(RPS.of(it[0]), RPS.of(it[2])) }
}
return userScore
}
fun day2task2(): Int {
var userScore = 0
readInputAsSequence("Day02") {
userScore = sumOf { getScore(RPS.of(it[0]), GameResult.of(it[2])) }
}
return userScore
}
sealed class GameResult {
abstract val score: Int
companion object {
fun of(char: Char): GameResult = when (char) {
'X' -> LOOSE
'Y' -> DRAW
'Z' -> WIN
else -> throw IllegalArgumentException("Failed to parse: $char")
}
}
object LOOSE : GameResult() {
override val score = 0
}
object DRAW : GameResult() {
override val score = 3
}
object WIN : GameResult() {
override val score = 6
}
}
sealed class RPS {
abstract val score: Int
abstract val winAgainst: RPS
abstract val looseAgainst: RPS
object ROCK : RPS() {
override val score = 1
override val winAgainst = SCISSORS
override val looseAgainst = PAPER
}
object PAPER : RPS() {
override val score = 2
override val winAgainst = ROCK
override val looseAgainst = SCISSORS
}
object SCISSORS : RPS() {
override val score = 3
override val winAgainst = PAPER
override val looseAgainst = ROCK
}
companion object {
fun of(char: Char): RPS = when (char) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> throw IllegalArgumentException("Failed to parse: $char")
}
}
}
private fun RPS.gameAgainst(other: RPS): GameResult = when (other) {
this -> DRAW
this.winAgainst -> WIN
this.looseAgainst -> LOOSE
else -> throw IllegalArgumentException("Unknown RPS: $other")
}
private fun getRPSforResult(other: RPS, result: GameResult): RPS = when (result) {
DRAW -> other
LOOSE -> other.winAgainst
WIN -> other.looseAgainst
}
fun getScore(other: RPS, my: RPS): Int {
return my.score + my.gameAgainst(other).score
}
fun getScore(other: RPS, neededResult: GameResult): Int {
return getRPSforResult(other, neededResult).score + neededResult.score
} | 0 | Kotlin | 0 | 0 | df2e12287a30a3a7bd5a026a963bcac41a730232 | 2,396 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Lesson5PrefixSums/CountDiv.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} | /**
* 100/100
* @param A
* @param B
* @param K
* @return
*/
fun solution(A: Int, B: Int, K: Int): Int {
var firstDivisible = -1
if (K == 1) { // if K is 1, all of the ints are divisible by it in range
return B - A + 1 // return ALL of them, no need to process anything
}
// In case K is greater than 1, find the first one in range that is divisible by K
for (i in A..B) {
if (i % K == 0) {
firstDivisible = i
break
}
}
// in case we found at least one, >= 0 is ‘cause 0 % K (for any K) is always 0 (divisible)
return if (firstDivisible >= 0) {
// every K-th (sort of speak) element after that in range is divisible by K
1 + (B - firstDivisible) / K
} else 0
}
/**
* Write a function:
*
* class Solution { public int solution(int A, int B, int K); }
*
* that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
*
* { i : A ≤ i ≤ B, i mod K = 0 }
*
* For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
*
* Write an efficient algorithm for the following assumptions:
*
* A and B are integers within the range [0..2,000,000,000];
* K is an integer within the range [1..2,000,000,000];
* A ≤ B.
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 1,409 | Codility-Kotlin | Apache License 2.0 |
src/questions/UniquePathsII.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
* The robot can only move either down or right at any point in time.
* The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
* Now consider if some obstacles are added to the grids. How many unique paths would there be?
* An obstacle and space is marked as 1 and 0 respectively in the grid.
*
* <img src="https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg" height="200" width="200"/>
*
* [Source](https://leetcode.com/problems/unique-paths-ii/)
*/
@UseCommentAsDocumentation
private interface UniquePathsII {
fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int
}
private class UniquePathsIINaiveApproach : UniquePathsII {
private enum class Dir { R, D }
private var answer = 0
private lateinit var grid: Array<IntArray>
override fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int {
if (obstacleGrid[obstacleGrid.lastIndex][obstacleGrid[0].lastIndex] == 1) {
return 0
}
if (obstacleGrid[0][0] == 1) {
return 0
}
this.grid = obstacleGrid
val m = obstacleGrid.size
val n = obstacleGrid[0].size
if (m == 1 && n == 1) return 1
traverse(Dir.R, 0, 0, m - 1, n - 1) // go right
traverse(Dir.D, 0, 0, m - 1, n - 1) // go down
return answer
}
private fun traverse(direction: Dir, posX: Int, posY: Int, rowMaxIndex: Int, colMaxIndex: Int) {
if (direction == Dir.R) {
val newPositionX = posX + 1
if (!canMoveHere(row = posY, col = newPositionX)) {
return
}
if (newPositionX == colMaxIndex && posY == rowMaxIndex) {
answer++
} else {
traverse(Dir.R, newPositionX, posY, rowMaxIndex, colMaxIndex)
traverse(Dir.D, newPositionX, posY, rowMaxIndex, colMaxIndex)
}
} else {
val newPositionY = posY + 1
if (!canMoveHere(row = newPositionY, col = posX)) {
return
}
if (posX == colMaxIndex && newPositionY == rowMaxIndex) {
answer++
} else {
traverse(Dir.R, posX, newPositionY, rowMaxIndex, colMaxIndex)
traverse(Dir.D, posX, newPositionY, rowMaxIndex, colMaxIndex)
}
}
}
private fun canMoveHere(row: Int, col: Int): Boolean {
val cell = this.grid.getOrNull(row)?.getOrNull(col)
if (cell == 0) return true
if (cell == 1 || cell == null) return false
return true
}
}
private class UniquePathsIINaiveArrayOfArray : UniquePathsII {
override fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int {
if (obstacleGrid[obstacleGrid.lastIndex][obstacleGrid[0].lastIndex] == 1) {
return 0
}
if (obstacleGrid[0][0] == 1) {
return 0
}
val m = obstacleGrid.size
val n = obstacleGrid[0].size
val dp = Array<IntArray>(m) {
IntArray(n) { 0 }
}
for (row in 0..dp.lastIndex) {
for (col in 0..dp[0].lastIndex) {
if (obstacleGrid[row][col] == 1) {
dp[row][col] = 0
} else if (row == 0 && col == 0) {
dp[row][col] = 1 // only one way to get to (0,0) is moving left
} else if (row == 0) {
dp[row][col] = dp[row][col - 1] // only way to get to first row is move up
} else if (col == 0) {
dp[row][col] = dp[row - 1][col] // only way to get to left col is move left
} else {
dp[row][col] = dp[row - 1][col] + dp[row][col - 1] // two ways
}
}
}
return dp[m - 1][n - 1]
}
}
fun main() {
val uniquePathCheck: (input: Array<IntArray>, expected: Int) -> Int? = { input, expected ->
UniquePathsIINaiveApproach().uniquePathsWithObstacles(input) shouldBe
UniquePathsIINaiveArrayOfArray().uniquePathsWithObstacles(input) shouldBe expected
}
uniquePathCheck.invoke(arrayOf(intArrayOf(1, 0)), 0)
run {
val input = arrayOf(
intArrayOf(0, 0),
intArrayOf(1, 1),
intArrayOf(0, 0)
)
uniquePathCheck.invoke(input, 0)
}
uniquePathCheck.invoke(
arrayOf(
intArrayOf(0, 0, 0),
intArrayOf(0, 1, 0),
intArrayOf(0, 0, 0)
),
2
)
uniquePathCheck.invoke(
arrayOf(
intArrayOf(0, 0, 0, 0),
intArrayOf(0, 1, 0, 0),
intArrayOf(0, 0, 0, 0),
intArrayOf(0, 0, 1, 0),
intArrayOf(0, 0, 0, 0),
),
7
)
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 5,023 | algorithms | MIT License |
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day18.kt | clechasseur | 567,968,171 | false | {"Kotlin": 493887} | package io.github.clechasseur.adventofcode.y2022
import io.github.clechasseur.adventofcode.util.Pt3D
import io.github.clechasseur.adventofcode.y2022.data.Day18Data
object Day18 {
private val input = Day18Data.input
private val displacements = listOf(
Pt3D(-1, 0, 0),
Pt3D(1, 0, 0),
Pt3D(0, -1, 0),
Pt3D(0, 1, 0),
Pt3D(0, 0, -1),
Pt3D(0, 0, 1)
)
fun part1(): Int = Volume(cubes = input.lines().map { it.toPt3D() }.toSet()).exposedSides
fun part2(): Int {
val volume = Volume(cubes = input.lines().map { it.toPt3D() }.toSet())
return volume.exposedSides - volume.airExposedSides
}
private class Volume(val cubes: Set<Pt3D>) {
val exposedSides: Int
get() = cubes.sumOf { exposedSidesFor(it) }
val airExposedSides: Int
get() {
val pts = cubes.flatMap { pt ->
displacements.map { pt + it }
}.filter { it !in cubes }.toSet()
val expanded = mutableSetOf<Pt3D>()
pts.forEach { pt ->
if (pt !in expanded) {
val expandedPt = expandAirPocket(pt)
if (expandedPt != null) {
expanded.addAll(expandedPt)
}
}
}
return Volume(cubes = expanded).exposedSides
}
private fun exposedSidesFor(pt: Pt3D): Int = displacements.map { pt + it }.count { adjacentPt ->
adjacentPt !in cubes
}
private fun inVoid(pt: Pt3D): Boolean = pt.x < (cubes.minOf { it.x } - 1) ||
pt.x > (cubes.maxOf { it.x } + 1) ||
pt.y < (cubes.minOf { it.y } - 1) ||
pt.y > (cubes.maxOf { it.y } + 1) ||
pt.z < (cubes.minOf { it.z } - 1) ||
pt.z > (cubes.maxOf { it.z } + 1)
private fun expandAirPocket(pt: Pt3D): Set<Pt3D>? {
val expanded = mutableSetOf(pt)
var edges = setOf(pt)
while (edges.isNotEmpty()) {
edges = edges.flatMap { edge ->
displacements.map { edge + it }
}.filter { edge ->
edge !in expanded && edge !in cubes
}.toSet()
if (edges.any { inVoid(it) }) {
return null
}
expanded.addAll(edges)
}
return expanded
}
}
private fun String.toPt3D(): Pt3D {
val (x, y, z) = split(',')
return Pt3D(x.toInt(), y.toInt(), z.toInt())
}
}
| 0 | Kotlin | 0 | 0 | 7ead7db6491d6fba2479cd604f684f0f8c1e450f | 2,675 | adventofcode2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SparseVector.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
/**
* 1570. Dot Product of Two Sparse Vectors
* @see <a href="https://leetcode.com/problems/dot-product-of-two-sparse-vectors/">Source</a>
*/
fun interface SparseVector<T> {
fun dotProduct(vec: T): Int
}
/**
* Approach 1: Non-efficient Array Approach
* Time complexity: O(n).
* Space complexity: O(1).
*/
class SparseVectorArray(val array: IntArray) : SparseVector<SparseVectorArray> {
override fun dotProduct(vec: SparseVectorArray): Int {
var result = 0
for (i in array.indices) {
result += array[i] * vec.array[i]
}
return result
}
}
/**
* Approach 2: Hash Set
* Time complexity: O(n).
* Space complexity: O(L).
*/
class SparseVectorHashSet(val array: IntArray) : SparseVector<SparseVectorHashSet> {
// Map the index to value for all non-zero values in the vector
private val mapping: MutableMap<Int, Int> = HashMap()
init {
for (i in array.indices) {
if (array[i] != 0) {
mapping[i] = array[i]
}
}
}
override fun dotProduct(vec: SparseVectorHashSet): Int {
var result = 0
for (key in mapping.keys) {
if (vec.mapping.containsKey(key)) {
result += this.mapping[key]!! * vec.mapping[key]!!
}
}
return result
}
}
/**
* Approach 3: Index-Value Pairs
*/
class SparseVectorPairs(val array: IntArray) : SparseVector<SparseVectorPairs> {
private val pairs: MutableList<IntArray> = ArrayList()
init {
for (i in array.indices) {
if (array[i] != 0) {
pairs.add(intArrayOf(i, array[i]))
}
}
}
override fun dotProduct(vec: SparseVectorPairs): Int {
var result = 0
var p = 0
var q = 0
while (p < pairs.size && q < vec.pairs.size) {
when {
pairs[p][0] == vec.pairs[q][0] -> {
result += pairs[p][1] * vec.pairs[q][1]
p++
q++
}
pairs[p][0] > vec.pairs[q][0] -> {
q++
}
else -> {
p++
}
}
}
return result
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,912 | kotlab | Apache License 2.0 |
src/Day05.kt | ManueruEd | 573,678,383 | false | {"Kotlin": 10647} | fun main() {
val day = "05"
fun part1(input: List<String>): String {
val lengthStack = 9
val stacks = List(lengthStack) { mutableListOf<Char?>() }
val a = input.takeWhile { !it.startsWith("1") }.reversed()
for (i in 0 until a[0].length) {
for (j in a){
j.getOrNull(i)?.takeIf { it.isLetter() }?.let {
stacks[i].add(it)
}
}
}
input.filter { it.startsWith("move") }
.forEach {
val x = Regex("move (\\d+) from (\\d) to (\\d)").matchEntire(it)!!
val q = x.groupValues[1].toInt()
val f = x.groupValues[2].toInt()
val t = x.groupValues[3].toInt()
for (m in 0 until q) {
val b = stacks[f - 1].removeLast()
stacks[t - 1].add(b)
}
}
val result = stacks.map { it.last{
it?.isLetter() == true
}}.joinToString("")
return result
}
fun part2(input: List<String>): String {
val lengthStack = 9
val stacks = List(lengthStack) { mutableListOf<Char?>() }
val a = input.takeWhile { !it.startsWith("1") }.reversed()
for (i in 0 until a[0].length) {
for (j in a){
j.getOrNull(i)?.takeIf { it.isLetter() }?.let {
stacks[i].add(it)
}
}
}
input.filter { it.startsWith("move") }
.forEach {
val x = Regex("move (\\d+) from (\\d) to (\\d)").matchEntire(it)!!
val q = x.groupValues[1].toInt()
val f = x.groupValues[2].toInt()
val t = x.groupValues[3].toInt()
val temp = mutableListOf<Char>()
for (m in 0 until q) {
val b = stacks[f - 1].removeLast()!!
temp.add(b)
}
stacks[t - 1].addAll(temp.reversed())
}
val result = stacks.map { it.last{
it?.isLetter() == true
}}.joinToString("")
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == "CMZ")
val input = readInput("Day$day")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 09f3357e059e31fda3dd2dfda5ce603c31614d77 | 2,398 | AdventOfCode2022 | Apache License 2.0 |
src/Day02.kt | RandomUserIK | 572,624,698 | false | {"Kotlin": 21278} | fun main() {
fun part1(input: List<Pair<Char, Char>>): Int {
val roundPoints = mapOf(
Pair('B', 'X') to 0,
Pair('C', 'Y') to 0,
Pair('A', 'Z') to 0,
Pair('A', 'X') to 3,
Pair('B', 'Y') to 3,
Pair('C', 'Z') to 3,
Pair('C', 'X') to 6,
Pair('A', 'Y') to 6,
Pair('B', 'Z') to 6,
)
// In the first part, we only need to resolve the X, Y and Z symbols
fun symbolPoints(symbol: Char): Int = symbol - 'X' + 1
fun roundPoints(opponent: Char, myself: Char): Int = roundPoints[opponent to myself] ?: error("Invalid input!")
return input.fold(0) { acc, (opponent, myself) ->
acc + symbolPoints(myself) + roundPoints(opponent, myself)
}
}
fun part2(input: List<Pair<Char, Char>>): Int {
val symbolPoints = mapOf(
Pair('A', 'Y') to 1,
Pair('B', 'X') to 1,
Pair('C', 'Z') to 1,
Pair('B', 'Y') to 2,
Pair('C', 'X') to 2,
Pair('A', 'Z') to 2,
Pair('C', 'Y') to 3,
Pair('A', 'X') to 3,
Pair('B', 'Z') to 3,
)
fun symbolPoints(opponent: Char, myself: Char): Int =
symbolPoints[opponent to myself] ?: error("Invalid input!")
fun roundPoints(action: Char): Int = (action - 'X') * 3
return input.fold(0) { acc, (opponent, action) ->
acc + symbolPoints(opponent, action) + roundPoints(action)
}
}
val input = readInput("inputs/day02_input").map { line -> Pair(line.first(), line.last()) }
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | f22f10da922832d78dd444b5c9cc08fadc566b4b | 1,416 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day10.kt | Gitvert | 433,947,508 | false | {"Kotlin": 82286} | fun day10() {
val lines: List<String> = readFile("day10.txt")
day10part1(lines)
day10part2(lines)
}
fun day10part1(lines: List<String>) {
val answer = lines.map { getCorruptedPoints(it) }.sumOf{ it }
println("10a: $answer")
}
fun day10part2(lines: List<String>) {
val incompleteLines = lines.filter { getCorruptedPoints(it) == 0 }
val incompleteLinePoints = incompleteLines.map { getIncompletePoints(it) }.sorted()
val answer = incompleteLinePoints[(incompleteLinePoints.size - 1) / 2]
println("10b: $answer")
}
fun getCorruptedPoints(line: String): Int {
val stack = ArrayDeque<Char>()
line.forEach {
if (listOf('(', '[', '{', '<').contains(it)) {
stack.add(it)
} else {
val closer = stack.removeLast()
if (chunks[closer] != it) {
when (it) {
')' -> return 3
']' -> return 57
'}' -> return 1197
'>' -> return 25137
}
}
}
}
return 0
}
fun getIncompletePoints(line: String): Long {
val stack = ArrayDeque<Char>()
var points = 0L
line.forEach {
if (listOf('(', '[', '{', '<').contains(it)) {
stack.add(it)
} else {
stack.removeLast()
}
}
while (stack.isNotEmpty()) {
val closer = chunks[stack.removeLast()]
points *= 5
when (closer) {
')' -> points += 1
']' -> points += 2
'}' -> points += 3
'>' -> points += 4
}
}
return points
}
val chunks: Map<Char, Char> = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>')
| 0 | Kotlin | 0 | 0 | 02484bd3bcb921094bc83368843773f7912fe757 | 1,720 | advent_of_code_2021 | MIT License |
src/Day02.kt | mpythonite | 572,671,910 | false | {"Kotlin": 29542} | fun main() {
fun part1(input: List<String>): Int {
var score = 0
for (i in input.indices) {
val them = input[i].first() - 'A' + 1
val me = input[i].last() - 'X' + 1
score += me
if (me == them) score += 3
if (me == them % 3 + 1) score += 6
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (i in input.indices) {
val them = input[i].first() - 'A' + 1
var me = when(input[i].last()) {
'X' -> (them + 1) % 3 + 1
'Y' -> them
'Z' -> them % 3 + 1
else -> 0
}
score += me
if (me == them) score += 3
if (me == them % 3 + 1) score += 6
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cac94823f41f3db4b71deb1413239f6c8878c6e4 | 1,125 | advent-of-code-2022 | Apache License 2.0 |
string-similarity/src/commonMain/kotlin/com/aallam/similarity/DamerauLevenshtein.kt | aallam | 597,692,521 | false | null | package com.aallam.similarity
/**
* Damerau-Levenshtein distance with transposition (*unrestricted Damerau-Levenshtein* distance).
*
* The distance is the minimum number of operations needed to transform one string into the other, where an operation
* is defined as an insertion, deletion, or substitution of a single character, or a transposition of two adjacent
* characters. It does respect triangle inequality, and is thus a metric distance.
*
* [Damerau–Levenshtein](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Distance_with_adjacent_transpositions)
*/
public class DamerauLevenshtein {
/**
* Compute the distance between strings: the minimum number of operations needed to transform one string into the
* other (insertion, deletion, substitution of a single character, or a transposition of two adjacent characters).
*
* @param first the first string to compare.
* @param second the second string to compare.
*/
public fun distance(first: CharSequence, second: CharSequence): Int {
// infinite distance is the max possible distance
val n = first.length
val m = second.length
val infinity = n + m
// create and initialize the character array indices
val charsRowIndex = mutableMapOf<Char, Int>()
for (index in first.indices) charsRowIndex[first[index]] = 0
for (char in second) charsRowIndex[char] = 0
// create the distance matrix H[0 .. first.length+1][0 .. second.length+1]
val distanceMatrix = Array(n + 2) { IntArray(m + 2) }
// initialize the left edge
for (i in first.indices) {
distanceMatrix[i + 1][0] = infinity
distanceMatrix[i + 1][1] = i
}
// initialize top edge
for (j in second.indices) {
distanceMatrix[0][j + 1] = infinity
distanceMatrix[1][j + 1] = j
}
// fill in the distance matrix
for (i in 1..n) {
var lastMatch = 0
for (j in 1..m) {
val lastRowIndex = charsRowIndex.getValue(second[j - 1])
val previousMatch = lastMatch
val cost: Int
if (first[i - 1] == second[j - 1]) {
cost = 0
lastMatch = j
} else {
cost = 1
}
val substitution = distanceMatrix[i][j] + cost
val insertion = distanceMatrix[i + 1][j] + 1
val deletion = distanceMatrix[i][j + 1] + 1
val transposition =
distanceMatrix[lastRowIndex][previousMatch] + (i - lastRowIndex - 1) + 1 + (j - previousMatch - 1)
distanceMatrix[i + 1][j + 1] = minOf(substitution, insertion, deletion, transposition)
}
charsRowIndex[first[i - 1]] = i
}
return distanceMatrix[n + 1][m + 1]
}
}
| 0 | Kotlin | 0 | 1 | 40cd4eb7543b776c283147e05d12bb840202b6f7 | 2,958 | string-similarity-kotlin | MIT License |
src/day07/Day07.kt | tobihein | 569,448,315 | false | {"Kotlin": 58721} | package template
import readInput
import java.util.*
class Day07 {
fun part1(): Int {
val readInput = readInput("day07/input")
return part1(readInput)
}
fun part2(): Int {
val readInput = readInput("day07/input")
return part2(readInput)
}
fun part1(input: List<String>): Int {
val folders = getFoldersWithSize(input)
return folders.map { it.value }.filter { it <= 100000 }.sum()
}
private fun getFoldersWithSize(input: List<String>): MutableMap<String, Int> {
val folders = mutableMapOf<String, Int>()
val stack = Stack<String>()
var currentDir: String? = null
input.forEach { it ->
when {
goToParentFolder(it) -> currentDir = stack.pop()
goToFolder(it) -> {
val dirName = it.split(" ")[2]
if (currentDir != null) {
stack.push(currentDir)
currentDir = currentDir + "_" + dirName
} else {
currentDir = dirName
}
folders.putIfAbsent(dirName, 0)
}
isDir(it) -> folders.putIfAbsent(it.split(" ")[1], 0)
isFile(it) -> {
val previousSize = folders.getOrDefault(currentDir, 0)
val currentSize = it.split(" ")[0].toInt()
val curDir = currentDir
if (curDir != null) {
folders.put(curDir, previousSize + currentSize)
}
stack.forEach {
val newSize = folders.getOrDefault(it, 0) + currentSize
folders.put(it, newSize)
}
}
}
}
return folders
}
fun part2(input: List<String>): Int {
val folders = getFoldersWithSize(input)
val usedSize = folders.getOrDefault("/", 0)
val unsedSize = 70000000 - usedSize
val sizeToDelete = 30000000 - unsedSize
return folders.toList().sortedBy { (_, v) -> v }.map { it.second }.filter { it > sizeToDelete }.first()
}
private fun goToParentFolder(s: String) = (s == "$ cd ..")
private fun goToFolder(s: String) = (s.startsWith("$ cd ") && !s.endsWith(".."))
private fun isDir(s: String) = s.startsWith("dir ")
private fun isFile(s: String) = s.split(" ")[0].matches("\\d+".toRegex())
}
| 0 | Kotlin | 0 | 0 | af8d851702e633eb8ff4020011f762156bfc136b | 2,507 | adventofcode-2022 | Apache License 2.0 |
algorithms/src/main/kotlin/com/kotlinground/algorithms/stack/dailytemperatures/dailyTemperatures.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.algorithms.stack.dailytemperatures
import java.util.Stack
/**
* To solve this problem, we will use a Monotonic Decreasing Stack. That is a stack, where all the values inside the
* stack, are ordered from largest, to smallest. Meaning, we only add to the stack when the stack is either:
*
* 1. Empty, or
* 2. If the incoming value is smaller or equal to the value on top of the stack.
*
* That means that if any incoming value is larger, we must pop values off the top of the stack, until it satisfies
* rules 1 or 2 before we can add it to our stack.
*
* It is during the popping phase, that we will do the majority of our work in solving our problem. By also adding the
* indexes with the temperature to the stack, we know where they exist in our output array, and can also use the
* indexes to gauge the relative distance in terms of days from other temperatures. So while popping them, we can
* calculate the incoming index, i minus the popped items index, i2 and overwrite the values in our output array at
* i2 with the difference, that is i-i2.
*
* Complexity Constraints:
*
* Time Complexity: O(n) where n is the length of the input, temperatures.
* Space Complexity: O(n) which will be the size of our output array, and our stack in the worst case.
*/
fun dailyTemperatures(temperatures: IntArray): IntArray {
// Here we will utilize a monotonic decreasing stack, meaning everything in the stack will be ordered from
// 'hottest' to 'coldest', and any incoming element, 'warmer' than the top of the stack, will force us to remove
// the 'colder' days from the top of our stack, and calculate the difference in how many days apart they were for
// our output array. Initialize output array of 0's the size of temperatures array. We use 0's as default, as if we
// don't find a warmer day going forward, we are to return 0 in that position instead.
val result = IntArray(temperatures.size) { 0 }
val stack = Stack<Pair<Int, Int>>()
// Loop through temperatures, tracking index, i and temperature, temp.
for ((i, temperature) in temperatures.withIndex()) {
// While the incoming temperature is 'warmer' than the temperature on top of the stack: We can start popping.
// Note our stack values are formatted with tuples in the form (index, temperature).
while (stack.size != 0 && stack.peek().second < temperature) {
// Pop temperature, tracking its index in temperatures, idx and the temperature itself.
val (idx, temp) = stack.pop()
// Add to out output at the index of the popped value, the difference of the current temperature index,
// minus popped value difference. This will be the number of days in between them.
result[idx] = i - idx
}
// Once the top of the stack is either empty or no longer has days colder than the incoming temperature, we can
// add our temperature to the stack. Again note that we are tracking index, i, and temperature, temp inside our
// stack.
stack.add(i to temperature)
}
return result
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 3,149 | KotlinGround | MIT License |
src/Day10.kt | zdenekobornik | 572,882,216 | false | null | fun main() {
fun generateValues(testInput: List<String>): List<Int> {
return testInput.flatMap { line ->
when (line) {
"noop" -> listOf(0)
else -> listOf(0, line.substring(5).toInt())
}
}.runningFold(1) { x, op -> x + op }
}
fun part1(testInput: List<String>): Int {
val values = generateValues(testInput)
return listOf(20, 60, 100, 140, 180, 220).sumOf { it * values[it - 1] }
}
fun part2(testInput: List<String>) {
(1..240).zip(generateValues(testInput))
.forEach { (cycle, x) ->
val sprite = x until (x + 3)
val position = cycle % 40
print(if (position in sprite) '▓' else '░')
if (position == 0) println()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
checkResult(part1(testInput), 13140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | f73e4a32802fa43b90c9d687d3c3247bf089e0e5 | 1,095 | advent-of-code-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.