path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/Day11.kt | pavittr | 317,532,861 | false | null | import java.io.File
import java.nio.charset.Charset
import kotlin.streams.toList
fun main() {
val testDocs = File("test/day11").readLines(Charset.defaultCharset())
val puzzles = File("puzzles/day11").readLines(Charset.defaultCharset())
fun process(text: List<String>, tolerance: Int) : Int {
val init = text.mapIndexed { y, line -> line.mapIndexed { x, char -> Seat(x, y, char == 'L', false) } }
.reduce { acc, list -> acc.union(list).toList() }
var initial = WaitingArea(init.filter { it.isSeat })
var next = initial.nextIter(initial::getNeighbours, tolerance)
var loop = 2
while (next.first) {
println("Loop $loop")
loop++
next = next.second.nextIter(next.second::getNeighbours, tolerance )
}
return next.second.seats.count { it.isOccupied }
}
println(process(testDocs, 4))
// println(process(puzzles))
fun processP2(text: List<String>, tolerance: Int) : Int {
val init = text.mapIndexed { y, line -> line.mapIndexed { x, char -> Seat(x, y, char == 'L', false) } }
.reduce { acc, list -> acc.union(list).toList() }
var initial = WaitingArea(init.filter { it.isSeat })
var next = initial.nextIter(initial::getLOSNeighbours, tolerance)
var loop = 2
while (next.first) {
println("Loop $loop")
loop++
next = next.second.nextIter(next.second::getLOSNeighbours, tolerance )
}
return next.second.seats.count { it.isOccupied }
}
println(processP2(testDocs, 5))
println(processP2(puzzles, 5))
}
private fun printChart(mesg: String, initial: WaitingArea) {
println(mesg)
for (i in 0..9) {
for (j in 0..9) {
print(initial.seats.filter { it.x == j && it.y == i }.map {
if (it.isSeat) {
if (it.isOccupied) {
"#"
} else {
"L"
}
} else {
"."
}
}.first())
}
println()
}
}
class WaitingArea(val seats: List<Seat>) {
fun nextIter(f: (Seat) -> List<Seat>, tolerance: Int): Pair<Boolean, WaitingArea> {
var changed = false
var changedCOunt = 0
val newSeats = seats.map { cellUnderRemapping ->
val occupiedNeighbours = f(cellUnderRemapping).count { it.isOccupied }
if (cellUnderRemapping.isOccupied && occupiedNeighbours >= tolerance) {
changed = true
changedCOunt++
Seat(cellUnderRemapping.x, cellUnderRemapping.y, true, false)
} else if (!cellUnderRemapping.isOccupied && occupiedNeighbours == 0) {
changed = true
changedCOunt++
Seat(cellUnderRemapping.x, cellUnderRemapping.y, true, true)
} else {
cellUnderRemapping
}
}
println("$changed: $changedCOunt")
return Pair(changed, WaitingArea(newSeats))
}
fun getNeighbours(seat: Seat): List<Seat> {
return seats.filter{it.x != seat.x || it.y != seat.y}.filter{it.x in seat.x - 1..seat.x + 1 && it.y in seat.y - 1.. seat.y + 1 }
}
fun getLOSNeighbours(seat: Seat): List<Seat> {
val topSeat = seats.filter { it.x == seat.x && it.y < seat.y }.maxByOrNull { it.y }
val right = seats.filter { it.x > seat.x && it.y == seat.y }.minByOrNull { it.x }
val bottom = seats.filter { it.x == seat.x && it.y > seat.y }.minByOrNull { it.y }
val left = seats.filter { it.x < seat.x && it.y == seat.y }.maxByOrNull { it.x }
val topRight = seats.filter {it.x - seat.x == (seat.y-it.y) && it.y < seat.y}.maxByOrNull { it.y }
val bottomRight = seats.filter {it.x - seat.x == (it.y-seat.y) && it.y > seat.y}.minByOrNull { it.y }
val bottomLeft = seats.filter {it.x - seat.x == (seat.y-it.y) && it.y > seat.y}.minByOrNull { it.y }
val topLeft = seats.filter {it.x - seat.x == (it.y-seat.y) && it.y < seat.y}.maxByOrNull { it.y }
return listOfNotNull(topSeat, right, left, bottom, topRight, bottomRight, bottomLeft, topLeft)
}
}
class Seat(val x: Int, val y: Int, val isSeat: Boolean, val isOccupied: Boolean) {
override fun toString(): String {
return "($x,$y): $isSeat $isOccupied"
}
} | 0 | Kotlin | 0 | 0 | 3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04 | 4,492 | aoc2020 | Apache License 2.0 |
src/main/kotlin/problems/Day11.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
class Day11(override val input: String) : Problem {
override val number: Int = 11
override fun runPartOne(): String {
val currentBoard = Board.fromStr(input)
var flashes = 0
repeat(100) {
flashes += currentBoard.runStep()
}
return flashes.toString()
}
override fun runPartTwo(): String {
val currentBoard = Board.fromStr(input)
var step = 0
while (true) {
step++
val flashes = currentBoard.runStep()
if (flashes == currentBoard.width * currentBoard.height)
return step.toString()
}
}
data class Board(val board: MutableList<MutableList<Int>>) {
companion object {
fun fromStr(input: String): Board {
return Board(input.lines()
.map{ line ->
line
.toCharArray()
.map{ i -> i.digitToInt() }
.toMutableList()
}.toMutableList())
}
}
val width = board.first().size
val height = board.size
fun runStep(): Int {
val toVisit = mutableListOf<Pair<Int,Int>>()
val visited = mutableSetOf<Pair<Int,Int>>()
for (m in 0 until height) {
for (n in 0 until width) {
board[m][n] += 1
if (board[m][n] > 9) {
toVisit.add(Pair(m,n))
}
}
}
var flashes = 0
while(toVisit.isNotEmpty()) {
val pointCoords = toVisit.removeAt(0)
if (visited.contains(pointCoords)) continue
flashes++
visited.add(pointCoords)
pointCoords
.neighbours()
.forEach{ neighbour ->
val (m,n) = neighbour
board[m][n] += 1
if (board[m][n] > 9) {
toVisit.add(0, neighbour)
}
}
visited.forEach { (m,n) -> board[m][n] = 0 }
}
return flashes
}
private fun Pair<Int, Int>.neighbours(): List<Pair<Int, Int>> {
return listOf(
Pair(1, 0),
Pair(1, 1),
Pair(0, 1),
Pair(-1, 1),
Pair(-1, 0),
Pair(-1, -1),
Pair(0, -1),
Pair(1, -1),
).map { (m, n) -> Pair(this.first + m, this.second + n) }
.filter { (m, n) -> m in 0 until height && n in 0 until width }
}
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 2,789 | AdventOfCode2021 | MIT License |
leetcode/src/main/kotlin/AtoiSolution.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | /**
* This was in 2020...
*
* [LeetCode](https://leetcode.com/problems/string-to-integer-atoi/)
*/
class AtoiSolution {
fun myAtoi(str: String): Int {
val numberStr =
str.trim().dropWhile { !it.isDigit() }.takeWhile { it.isDigit() }.dropWhile { it == '0' }
if (numberStr.isEmpty()) return 0
val prefix = str.subSequence(0, str.indexOf(numberStr)).filter { it != '0' }
if (prefix.count { !it.isWhitespace() } > 1) return 0
if (prefix.any { it.isLetter() || it == '.' }) return 0
if (prefix.isNotBlank() && prefix.last() == ' ') return 0
val negative = prefix.lastOrNull() == '-'
return when {
numberStr.length > 18 && negative -> Int.MIN_VALUE
numberStr.length > 18 -> Int.MAX_VALUE
negative -> Math.max(-numberStr.parse(), Int.MIN_VALUE.toLong()).toInt()
else -> Math.min(numberStr.parse(), Int.MAX_VALUE.toLong()).toInt()
}
}
private fun String.parse(): Long {
return this.reversed().foldIndexed(0L) { index, acc, char ->
acc + (char - 48).toLong() * 10.pow(index)
}
}
private fun Int.pow(index: Int): Long {
var ret = 1L
repeat(index) { ret *= this }
return ret
}
}
| 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 1,182 | advent-of-code | MIT License |
src/main/kotlin/Utils.kt | hughjdavey | 317,575,435 | false | null | import java.util.Stack
import kotlin.math.abs
fun <T> List<T>.allPairs(): List<Pair<T, T>> = this.flatMap { i -> this.map { j -> Pair(i, j) } }
fun <T> List<T>.allTriples(): List<Triple<T, T, T>> = this.flatMap { i -> this.flatMap { j -> this.map { k -> Triple(i, j, k) } } }
fun Pair<Int, Int>.add() = this.first + this.second
fun Pair<Int, Int>.mul() = this.first * this.second
fun Triple<Int, Int, Int>.add() = this.first + this.second + this.third
fun Triple<Int, Int, Int>.mul() = this.first * this.second * this.third
fun String.isIntAndInRange(start: Int, end: Int): Boolean {
val maybeInt = this.toIntOrNull() ?: return false
return maybeInt in start..end
}
enum class Direction {
NORTH, EAST, SOUTH, WEST;
fun rotate(degrees: Int): Direction {
if (abs(degrees) !in listOf(0, 90, 180, 270, 360)) {
throw IllegalArgumentException("Valid rotations are +/- 0, 90, 180, 270 and 360")
}
var newIndex = values().indexOf(this) + (degrees / 90)
while (newIndex < 0) newIndex += 4
return values()[newIndex % 4]
}
}
// todo implement getAdjacent here
interface Coord {
fun getAdjacent(): List<Coord>
}
data class Coord2(val x: Int, val y: Int) : Coord {
fun plusX(delta: Int) = copy(x = x + delta)
fun minusX(delta: Int) = copy(x = x - delta)
fun plusY(delta: Int) = copy(y = y + delta)
fun minusY(delta: Int) = copy(y = y - delta)
fun absSum() = abs(x) + abs(y)
fun diff(from: Coord2 = Coord2(0, 0)): Coord2 {
return Coord2(x - from.x, y - from.y)
}
fun manhattan(from: Coord2 = Coord2(0, 0)): Int {
return diff(from).absSum()
}
fun rotate(axis: Coord2, degrees: Int): Coord2 {
val diff: Coord2 by lazy { diff(axis) }
return when (degrees) {
360, -360 -> copy()
180, -180 -> axis.minusX(diff.x).minusY(diff.y)
90, -270 -> copy(x = axis.x + diff.y, y = axis.y - diff.x)
-90, 270 -> copy(x = axis.x - diff.y, y = axis.y + diff.x)
else -> throw IllegalArgumentException("Valid rotations are +/- 0, 90, 180, 270 and 360")
}
}
override fun getAdjacent(): List<Coord> {
return (-1..1).flatMap { dy -> (-1..1).map { dx -> copy(x = x + dx, y = y + dy) } }.filterNot { it == this }
}
}
fun List<String>.splitOnBlank(): List<List<String>> {
val lists = mutableListOf(mutableListOf<String>())
for (str in this) {
if (str.isBlank()) {
lists.add(mutableListOf())
}
else {
lists.last().add(str)
}
}
return lists
}
fun <T> stackOf(input: List<T>): Stack<T> {
val stack = Stack<T>()
input.reversed().forEach { stack.push(it) }
return stack
}
fun <T> stackOf(vararg input: T): Stack<T> {
return stackOf(input.toList())
}
data class Coord3(val x: Int, val y: Int, val z: Int) : Coord {
override fun getAdjacent(): List<Coord3> {
return (-1..1).flatMap { dz -> (-1..1).flatMap { dy -> (-1..1).map { dx ->
copy(x = x + dx, y = y + dy, z = z + dz)
} } }.filterNot { it == this }
}
}
data class Coord4(val x: Int, val y: Int, val z: Int, val w: Int): Coord {
override fun getAdjacent(): List<Coord4> {
return (-1..1).flatMap { dz -> (-1..1).flatMap { dy -> (-1..1).flatMap { dx -> (-1..1).map { dw ->
copy(x = x + dx, y = y + dy, z = z + dz, w = w + dw)
} } } }.filterNot { it == this }
}
}
| 0 | Kotlin | 0 | 1 | 63c677854083fcce2d7cb30ed012d6acf38f3169 | 3,489 | aoc-2020 | Creative Commons Zero v1.0 Universal |
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day12.kt | loehnertz | 573,145,141 | false | {"Kotlin": 53239} | package codes.jakob.aoc
import codes.jakob.aoc.shared.Grid
import codes.jakob.aoc.shared.parseGrid
import java.util.*
import java.util.Comparator.comparing
class Day12 : Solution() {
override fun solvePart1(input: String): Any {
val grid: Grid<Elevation> = input.parseGrid { Elevation(it) }
val startCell: Grid.Cell<Elevation> = grid.cells.first { it.content.value.isStart }
val validPaths: MutableSet<List<Grid.Cell<Elevation>>> = mutableSetOf()
val queue: PriorityQueue<List<Grid.Cell<Elevation>>> = PriorityQueue(comparing { it.count() })
queue.add(listOf(startCell))
while (queue.isNotEmpty()) {
val path: List<Grid.Cell<Elevation>> = queue.poll()
val lastHop: Grid.Cell<Elevation> = path.last()
val lastElevation: Elevation = lastHop.content.value
if (lastElevation.isEnd) {
validPaths += path
} else {
lastHop
.getAdjacent()
.filterNot { it in path }
.filter {
val heightDelta = it.content.value.height() - lastElevation.height()
heightDelta == 0 || heightDelta == 1 || lastElevation.isStart
}
.forEach { queue.add(path + it) }
}
}
return validPaths.minOf { it.count() } - 1
}
override fun solvePart2(input: String): Any {
TODO("Not yet implemented")
}
data class Elevation(
val letter: Char,
val isStart: Boolean = letter == 'S',
val isEnd: Boolean = letter == 'E',
) {
fun height(): Int {
return when (letter) {
'S' -> 'a'.code
'E' -> 'z'.code
else -> letter.code
}
}
}
}
fun main() = Day12().solve()
| 0 | Kotlin | 0 | 0 | ddad8456dc697c0ca67255a26c34c1a004ac5039 | 1,881 | advent-of-code-2022 | MIT License |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day20.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2022
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
import java.util.*
import kotlin.collections.ArrayDeque
open class Part20A : PartSolution() {
lateinit var numbers: ArrayDeque<Pair<Long, Int>>
var zeroIdx = 0
override fun parseInput(text: String) {
numbers = ArrayDeque()
for ((i, line) in text.trim().split("\n").withIndex()) {
numbers.addLast(Pair(line.toLong(), i))
if (line.toInt() == 0) {
zeroIdx = i
}
}
}
override fun compute(): Long {
val originalNumbers = ArrayDeque(numbers)
mix(originalNumbers)
val i = numbers.indexOf(Pair(0, zeroIdx))
val num1 = numbers[(i + 1000) % numbers.size].first
val num2 = numbers[(i + 2000) % numbers.size].first
val num3 = numbers[(i + 3000) % numbers.size].first
return num1 + num2 + num3
}
fun mix(originalNumbers: ArrayDeque<Pair<Long, Int>>) {
for (idx in numbers.indices) {
val value = originalNumbers[idx]
val num = value.first
if (num == 0L) {
continue
}
val i = numbers.indexOf(value)
Collections.rotate(numbers, -i)
numbers.removeFirst()
rotate(numbers, -num)
numbers.addFirst(value)
rotate(numbers, num)
Collections.rotate(numbers, i)
if (num < 0L) {
Collections.rotate(numbers, -1)
}
}
}
private fun rotate(list: MutableList<*>, distance: Long) {
if (distance == 0L) {
return
}
if (distance > 0) {
var todo = distance
while (todo != 0L) {
var current = todo.toInt() and Int.MAX_VALUE
if (current == 0) {
current = Int.MAX_VALUE
}
todo -= current
Collections.rotate(list, current)
}
} else {
var todo = distance
while (todo != 0L) {
val current = todo.toInt() or Int.MIN_VALUE
todo -= current
Collections.rotate(list, current)
}
}
}
override fun getExampleAnswer(): Int {
return 3
}
}
class Part20B : Part20A() {
override fun config() {
numbers = ArrayDeque(numbers.mapIndexed { i, number -> Pair(number.first * 811_589_153L, i) })
}
override fun compute(): Long {
val originalNumbers = ArrayDeque(numbers)
repeat(10) { mix(originalNumbers) }
val i = numbers.indexOf(Pair(0, zeroIdx))
val num1 = numbers[(i + 1000) % numbers.size].first
val num2 = numbers[(i + 2000) % numbers.size].first
val num3 = numbers[(i + 3000) % numbers.size].first
return num1 + num2 + num3
}
override fun getExampleAnswer(): Int {
return 1_623_178_306
}
}
fun main() {
Day(2022, 20, Part20A(), Part20B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 3,079 | advent-of-code-kotlin | MIT License |
src/main/kotlin/days/Day5.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
class Day5 : Day(5) {
override fun partOne(): Any {
val regex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex()
val lines = inputList.map {
regex.find(it)!!.groupValues.drop(1).map { it.toInt() }
.let { (x1, y1, x2, y2) -> Line(x1, y1, x2, y2) }
}
val count = Array(1000) { Array(1000) { 0 } }
var overlaps = 0
for (line in lines) {
if (line.x1 != line.x2 && line.y1 != line.y2) continue
for (x in line.x1 toward line.x2) {
for (y in line.y1 toward line.y2) {
count[x][y] += 1
if (count[x][y] == 2) {
overlaps += 1
}
}
}
}
return overlaps
}
override fun partTwo(): Any {
val regex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex()
val lines = inputList.map {
regex.find(it)!!.groupValues.drop(1).map { it.toInt() }
.let { (x1, y1, x2, y2) -> Line(x1, y1, x2, y2) }
}
val count = Array(1000) { Array(1000) { 0 } }
var overlaps = 0
for (line in lines) {
if (line.x1 != line.x2 && line.y1 != line.y2) {
// diagonal
val dy = if (line.y2 - line.y1 > 0 ) 1 else -1
var y = line.y1
for (x in line.x1 toward line.x2) {
count[x][y] += 1
if (count[x][y] == 2) {
overlaps += 1
}
y += dy
}
} else {
for (x in line.x1 toward line.x2) {
for (y in line.y1 toward line.y2) {
count[x][y] += 1
if (count[x][y] == 2) {
overlaps += 1
}
}
}
}
}
return overlaps
}
private infix fun Int.toward(to: Int): IntProgression {
val step = if (this > to) -1 else 1
return IntProgression.fromClosedRange(this, to, step)
}
data class Line(val x1: Int, val y1: Int, val x2: Int, val y2: Int)
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 2,245 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/day22/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day22
import day22.Tile.*
import util.Direction2NonDiagonal
import util.Grid
import util.Point
import util.minus
import util.mutate
import util.pathSequence
import util.plus
import util.readInput
import util.shouldBe
import util.toGrid
import java.util.LinkedList
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 6032
testInput.part2() shouldBe 5031
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private enum class Tile { Outside, Empty, Wall }
private sealed interface Instruction
private data class Turn(val left: Boolean) : Instruction
private data class Walk(val distance: Int) : Instruction
private class Input(
val grid: Grid<Tile>,
val instructions: List<Instruction>,
)
private fun <T> List<T>.intersperseAlternating(provider: (Int) -> T) =
buildList {
for ((i, v) in this@intersperseAlternating.withIndex()) {
if (i > 0) add(provider(i))
add(v)
}
}
private fun List<String>.parseInput(): Input {
val instructions = last()
.split("R")
.map { subLine ->
subLine.split("L")
.map { Walk(it.toInt()) }
.intersperseAlternating { Turn(true) }
}
.intersperseAlternating { listOf(Turn(false)) }
.flatten()
val rawGridLines = subList(0, size - 2)
val gridWidth = rawGridLines.maxOf { it.length } + 2
val teleportRow = " ".repeat(gridWidth)
val grid = rawGridLines
.map { " $it".padEnd(gridWidth, ' ') }
.mutate { it.add(0, teleportRow); it.add(teleportRow) }
.toGrid { _, _, char ->
when (char) {
' ' -> Outside
'.' -> Empty
'#' -> Wall
else -> error("unknown tile char '$char'")
}
}
return Input(grid, instructions)
}
private data class State(
val pos: Point,
val heading: Direction2NonDiagonal,
)
private fun State.performInstruction(
grid: Grid<Tile>,
instruction: Instruction,
teleportMethod: (pos: Point, heading: Direction2NonDiagonal) -> State,
): State {
return when (instruction) {
is Turn -> when (instruction.left) {
true -> copy(heading = heading.rotatedLeft())
false -> copy(heading = heading.rotatedRight())
}
is Walk -> {
var pos = pos
var heading = heading
for(n in 1..instruction.distance) {
val nextPos = pos + heading
when (grid[nextPos]) {
Empty -> pos = nextPos
Wall -> break
Outside -> {
val teleportedState = teleportMethod(pos, heading)
when (grid[teleportedState.pos]) {
Empty -> {
pos = teleportedState.pos
heading = teleportedState.heading
}
Wall -> break
Outside -> error("teleport code teleported us outside ")
}
}
}
}
State(pos, heading)
}
}
}
private fun teleportOnFlatMap(
grid: Grid<Tile>,
pos: Point,
heading: Direction2NonDiagonal,
): State {
var otherSide = pos
val opposite = heading.opposite()
do {
otherSide += opposite
} while (grid[otherSide] != Outside)
return State(otherSide + heading, heading)
}
private fun teleportOnCube(
grid: Grid<Tile>,
pos: Point,
heading: Direction2NonDiagonal,
areaSize: Int,
): State {
fun Point.areaPos() = Point((x - 1).floorDiv(areaSize), (y - 1).floorDiv(areaSize))
val stack = LinkedList<State>().also { it += State(pos, heading) }
while (true) {
val (p1, d1) = stack.last
val area = p1.areaPos()
val d2 = d1.rotatedLeft()
val p2 = p1.pathSequence(d2).first { it.areaPos() != area }
val p3 = p1.rotateLeftAround(p2)
when {
p3 in grid && grid[p3] != Outside -> {
if (stack.size == 1) return State(p3, d2)
stack.removeLast()
stack.replaceAll {
State(
pos = it.pos.rotateLeftAround(p2) - d2,
heading = it.heading.rotatedLeft(),
)
}
}
p2 in grid && grid[p2] != Outside -> stack += State(p2, d1)
else -> stack += State(p2 - d2, d2)
}
}
}
private fun Input.solve(teleportMethod: (pos: Point, heading: Direction2NonDiagonal) -> State): Int {
var state = State(
pos = Point(
grid.row(1).withIndex().first { it.value == Empty }.index,
1,
),
heading = Direction2NonDiagonal.Right,
)
for (instruction in instructions) {
state = state.performInstruction(grid, instruction, teleportMethod)
}
return state.toResultHash()
}
private fun State.toResultHash(): Int {
val (x, y) = pos
val r = when (heading) {
Direction2NonDiagonal.Right -> 0
Direction2NonDiagonal.Up -> 3
Direction2NonDiagonal.Left -> 2
Direction2NonDiagonal.Down -> 1
}
return 1000 * y + 4 * x + r
}
private fun Input.part1(): Int {
return solve { pos, heading ->
teleportOnFlatMap(grid, pos, heading)
}
}
private fun Input.part2(): Int {
val areaSize = if (grid.width > 20) 50 else 4
return solve { pos, heading ->
teleportOnCube(grid, pos, heading, areaSize)
}
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 5,788 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2016/Day02.kt | tginsberg | 74,924,040 | false | null | /*
* Copyright (c) 2016 by <NAME>
*/
package com.ginsberg.advent2016
import com.ginsberg.advent2016.utils.toHex
/**
* Advent of Code - Day 2: December 2, 2016
*
* From http://adventofcode.com/2016/day/2
*
*/
class Day02(val instructions: List<String>, val startingPoint: Int = 5) {
/**
* Keypad like this:
* 1 2 3
* 4 5 6
* 7 8 9
*/
fun solvePart1(): String {
return solve { from: Int, via: Char ->
from + when (via) {
'L' -> if (setOf(1, 4, 7).contains(from)) 0 else -1
'R' -> if (setOf(3, 6, 9).contains(from)) 0 else 1
'U' -> if (setOf(1, 2, 3).contains(from)) 0 else -3
'D' -> if (setOf(7, 8, 9).contains(from)) 0 else 3
else -> 0
}
}
}
/**
* Keypad like this:
* 1
* 2 3 4
* 5 6 7 8 9
* A B C
* D
*/
fun solvePart2(): String {
return solve { from: Int, via: Char ->
from + when (via) {
'L' -> if (setOf(1, 2, 5, 10, 13).contains(from)) 0
else -1
'R' -> if (setOf(1, 4, 9, 12, 13).contains(from)) 0
else 1
'U' -> if (setOf(1, 2, 4, 5, 9).contains(from)) 0
else if (setOf(3, 13).contains(from)) -2
else -4
'D' -> if (setOf(5, 9, 10, 12, 13).contains(from)) 0
else if (setOf(1, 11).contains(from)) 2
else 4
else -> 0
}
}
}
/**
* Execute the inputs one by one, given a keypad mapping function
*/
private fun solve(keymapFunction: (a: Int, b: Char) -> Int): String {
tailrec fun inner(digits: List<Int>, lines: List<String>): String {
if(lines.isEmpty()) {
return digits.map(Int::toHex).joinToString(separator = "")
} else {
val from = digits.lastOrNull() ?: startingPoint
return inner(digits + stringToDigit(from, lines[0], keymapFunction), lines.drop(1))
}
}
return inner(emptyList(), instructions)
}
private fun stringToDigit(start: Int, input: String, op: (a: Int, b: Char) -> Int): Int =
input.fold(start){ carry, next -> op(carry, next) }
}
| 0 | Kotlin | 0 | 3 | a486b60e1c0f76242b95dd37b51dfa1d50e6b321 | 2,397 | advent-2016-kotlin | MIT License |
src/main/kotlin/solutions/day02/Day2.kt | Dr-Horv | 570,666,285 | false | {"Kotlin": 115643} | package solutions.day02
import solutions.Solver
enum class Moves {
ROCK,
PAPER,
SCISSORS
}
enum class Outcome {
DRAW,
LOST,
WON
}
class Day2 : Solver {
private fun roundScore(input: String, partTwo: Boolean): Int {
val moves = input.split(" ")
val opponentMove = when (moves.first()) {
"A" -> Moves.ROCK
"B" -> Moves.PAPER
"C" -> Moves.SCISSORS
else -> {
throw Error("Not expected")
}
}
val yourMove = if (!partTwo) {
when (moves.last()) {
"X" -> Moves.ROCK
"Y" -> Moves.PAPER
"Z" -> Moves.SCISSORS
else -> {
throw Error("Not expected")
}
}
} else {
when (moves.last()) {
"X" -> getLosingMove(opponentMove)
"Y" -> opponentMove
"Z" -> getWinningMove(opponentMove)
else -> {
throw Error("Not expected")
}
}
}
val outcome = getOutcome(yourMove, opponentMove)
return getMoveScore(yourMove) + getOutcomeScore(outcome)
}
private fun getWinningMove(opponentMove: Moves): Moves = when (opponentMove) {
Moves.ROCK -> Moves.PAPER
Moves.PAPER -> Moves.SCISSORS
Moves.SCISSORS -> Moves.ROCK
}
private fun getLosingMove(opponentMove: Moves): Moves = when (opponentMove) {
Moves.ROCK -> Moves.SCISSORS
Moves.PAPER -> Moves.ROCK
Moves.SCISSORS -> Moves.PAPER
}
private fun getOutcomeScore(outcome: Outcome): Int {
return when (outcome) {
Outcome.DRAW -> 3
Outcome.LOST -> 0
Outcome.WON -> 6
}
}
private fun getMoveScore(move: Moves): Int = when (move) {
Moves.ROCK -> 1
Moves.PAPER -> 2
Moves.SCISSORS -> 3
}
private fun getOutcome(yourMove: Moves, opponentMove: Moves): Outcome = when (yourMove) {
Moves.ROCK -> when (opponentMove) {
Moves.ROCK -> Outcome.DRAW
Moves.PAPER -> Outcome.LOST
Moves.SCISSORS -> Outcome.WON
}
Moves.PAPER -> when (opponentMove) {
Moves.ROCK -> Outcome.WON
Moves.PAPER -> Outcome.DRAW
Moves.SCISSORS -> Outcome.LOST
}
Moves.SCISSORS -> when (opponentMove) {
Moves.ROCK -> Outcome.LOST
Moves.PAPER -> Outcome.WON
Moves.SCISSORS -> Outcome.DRAW
}
}
override fun solve(input: List<String>, partTwo: Boolean): String {
return input.sumOf { roundScore(it, partTwo) }.toString()
}
} | 0 | Kotlin | 0 | 2 | 6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e | 2,762 | Advent-of-Code-2022 | MIT License |
src/main/kotlin/com/nibado/projects/advent/y2021/Day04.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2021
import com.nibado.projects.advent.*
object Day04 : Day {
private val values = resourceLines(2021, 4)
private val numbers = values.first().split(',').map { it.toInt() }
private val boards = values.asSequence().drop(1).filterNot { it.trim().isBlank() }.chunked(5) {
Board(it.map { it.trim().split("\\s+".toRegex()).map { it.toInt() } })
}.toMutableList()
private val wins = numbers.flatMap { n ->
boards.forEach { it.mark(n) }
val won = boards.filter { it.win() }
boards.removeIf { it.win() }
won.map { it to n }
}
data class Board(val grid: List<List<Int>>, val marked: MutableSet<Point> = mutableSetOf()) {
fun mark(number: Int) {
marked += points().filter { (x, y) -> grid[y][x] == number }
}
fun rowWin(): Boolean = grid.indices.any { y -> grid[y].indices.all { x -> marked.contains(Point(x, y)) } }
fun colWin(): Boolean = grid.first().indices.any { x -> grid.indices.all { y -> marked.contains(Point(x, y)) } }
fun win() = rowWin() or colWin()
fun points() = grid.indices.flatMap { y -> grid.first().indices.map { x -> Point(x, y) } }
fun unmarkedSum() = points().filterNot { marked.contains(it) }.map { grid[it.y][it.x] }.sum()
}
override fun part1() = wins.first().let { (board, num) -> board.unmarkedSum() * num }
override fun part2() = wins.last().let { (board, num) -> board.unmarkedSum() * num }
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,504 | adventofcode | MIT License |
advent-of-code-2021/src/main/kotlin/Day13.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 13: Transparent Origami
//https://adventofcode.com/2021/day/13
import java.io.File
fun main() {
val dots = mutableListOf<Pair<Int, Int>>()
val folds = mutableListOf<Fold>()
val lines = File("src/main/resources/Day13.txt").readLines()
lines.forEach {
if (it.startsWith("fold")) {
folds.add(Fold(it.substringAfter(" along ").first(), it.substringAfter("=").toInt()))
} else if (it.isNotBlank()) {
val (x, y) = it.split(",")
dots.add(x.toInt() to y.toInt())
}
}
val manual = Array(dots.maxOf { it.first } + 1) { Array(dots.maxOf { it.second } + 1) { 0 } }
dots.forEach {
manual[it.first][it.second]++
}
val manualFoldedOnce = foldManual(manual, folds.take(1))
var dotsFromFold1 = 0
for (i in 0 until manualFoldedOnce[0].size) {
for (element in manualFoldedOnce) {
if (element[i] >= 1) dotsFromFold1++
}
}
println(dotsFromFold1)
val foldedManual = foldManual(manual, folds)
for (i in foldedManual[0].size - 1 downTo 0) {
print("\n")
for (j in foldedManual.size - 1 downTo 0) {
if (foldedManual[j][i] >= 1) print("#") else print(" ")
}
}
}
fun foldManual(manual: Array<Array<Int>>, folds: List<Fold>): Array<Array<Int>> {
var foldedManual = manual
for (fold in folds) {
foldedManual = if (fold.isAlongX) {
foldHorizontally(foldedManual, fold.value)
} else {
foldVertically(foldedManual, fold.value)
}
}
return foldedManual
}
fun foldHorizontally(original: Array<Array<Int>>, foldIndex: Int): Array<Array<Int>> {
val y = original[0].size
val array = Array(foldIndex) { Array(y) { 0 } }
for (i in foldIndex + 1 until original.size) {
for (j in 0 until y) {
array[i - foldIndex - 1][j] = original[i][j] + original[(2 * foldIndex) - i][j]
}
}
return array
}
fun foldVertically(original: Array<Array<Int>>, foldIndex: Int): Array<Array<Int>> {
val y = original[0].size
val array = Array(original.size) { Array(foldIndex) { 0 } }
for (i in original.indices) {
for (j in foldIndex + 1 until y) {
array[i][j - foldIndex - 1] = original[i][j] + original[i][(2 * foldIndex) - j]
}
}
return array
}
data class Fold(val axis: Char, val value: Int) {
val isAlongX = axis == 'x'
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,443 | advent-of-code | Apache License 2.0 |
src/aoc2023/Day17.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2023
import readInput
import java.util.PriorityQueue
fun main() {
fun somePathHeatLoss(map: Array<Array<Int>>): Int {
return (1 until map.size).sumOf { map[it - 1][it] + map[it][it] }
}
data class Point(val x: Int, val y: Int)
data class Move(val direction: Char, val point: Point, val steps: Int)
data class CurrentState(val move: Move, val cost: Int)
fun promising(state: CurrentState, currentMin: Int, gridSize: Int, currentMinAtPoint: Int): Boolean {
val distanceToEnd = gridSize - state.move.point.x - 1 + gridSize - state.move.point.y - 1
if (state.cost + distanceToEnd >= currentMin) {
return false
}
if (state.cost > currentMinAtPoint + 4) {
return false
}
return true
}
fun up(point: Point, map: Array<Array<Int>>): Point? {
val newX = point.x - 1
if (newX < 0) {
return null
}
return Point(newX, point.y)
}
fun down(point: Point, map: Array<Array<Int>>): Point? {
val newX = point.x + 1
if (newX >= map.size) {
return null
}
return Point(newX, point.y)
}
fun right(point: Point, map: Array<Array<Int>>): Point? {
val newY = point.y + 1
if (newY >= map.size) {
return null
}
return Point(point.x, newY)
}
fun left(point: Point, map: Array<Array<Int>>): Point? {
val newY = point.y - 1
if (newY < 0) {
return null
}
return Point(point.x, newY)
}
fun next(state: CurrentState, map: Array<Array<Int>>): List<CurrentState> {
val result = mutableListOf<CurrentState>()
if (state.move.direction == 'R') {
val down = down(state.move.point, map)
if (down != null) {
result.add(CurrentState(Move('D', down, 0), state.cost + map[down.x][down.y]))
}
if (state.move.steps < 2) {
val right = right(state.move.point, map)
if (right != null) {
result.add(CurrentState(Move('R', right, state.move.steps + 1), state.cost + map[right.x][right.y]))
}
}
val up = up(state.move.point, map)
if (up != null) {
result.add(CurrentState(Move('U', up, 0), state.cost + map[up.x][up.y]))
}
} else if (state.move.direction == 'D') {
val right = right(state.move.point, map)
if (right != null) {
result.add(CurrentState(Move('R', right, 0), state.cost + map[right.x][right.y]))
}
if (state.move.steps < 2) {
val down = down(state.move.point, map)
if (down != null) {
result.add(CurrentState(Move('D', down, state.move.steps + 1), state.cost + map[down.x][down.y]))
}
}
val left = left(state.move.point, map)
if (left != null) {
result.add(CurrentState(Move('L', left, 0), state.cost + map[left.x][left.y]))
}
} else if (state.move.direction == 'U') {
val right = right(state.move.point, map)
if (right != null) {
result.add(CurrentState(Move('R', right, 0), state.cost + map[right.x][right.y]))
}
val left = left(state.move.point, map)
if (left != null) {
result.add(CurrentState(Move('L', left, 0), state.cost + map[left.x][left.y]))
}
if (state.move.steps < 2) {
val up = up(state.move.point, map)
if (up != null) {
result.add(CurrentState(Move('U', up, state.move.steps + 1), state.cost + map[up.x][up.y]))
}
}
} else if (state.move.direction == 'L') {
val down = down(state.move.point, map)
if (down != null) {
result.add(CurrentState(Move('D', down, 0), state.cost + map[down.x][down.y]))
}
if (state.move.steps < 2) {
val left = left(state.move.point, map)
if (left != null) {
result.add(CurrentState(Move('L', left, state.move.steps + 1), state.cost + map[left.x][left.y]))
}
}
val up = up(state.move.point, map)
if (up != null) {
result.add(CurrentState(Move('U', up, state.move.steps + 1), state.cost + map[up.x][up.y]))
}
}
return result
}
fun part1(lines: List<String>): Int {
val map = Array(lines.size) { Array(lines[0].length) { 0 } }
for (i in lines.indices) {
map[i] = lines[i].toCharArray().map { it.digitToInt() }.toTypedArray()
}
var currentMin = somePathHeatLoss(map)
val curMinAtPoint = mutableMapOf<Point, Int>()
val visited = mutableListOf<CurrentState>()
val toVisit = PriorityQueue((compareBy<CurrentState> { 2 * (map.size + map.size - it.move.point.x - it.move.point.y - 2) + it.cost }))
toVisit.add(CurrentState(Move('R', Point(0, 0), 0), 0))
toVisit.add(CurrentState(Move('D', Point(0, 0), 0), 0))
while (toVisit.isNotEmpty()) {
val current = toVisit.remove()
visited.add(current)
val next = next(current, map)
for (elem in next) {
if (elem.move.point == Point(map.size - 1, map.size - 1)) {
if (elem.cost < currentMin) {
currentMin = elem.cost
println(currentMin)
}
} else if (!visited.contains(elem)) {
if (promising(elem, currentMin, map.size, curMinAtPoint.getOrDefault(elem.move.point, currentMin))) {
toVisit.add(elem)
if (elem.cost < curMinAtPoint.getOrDefault(elem.move.point, currentMin)) {
curMinAtPoint.put(elem.move.point, elem.cost)
}
}
}
}
toVisit.removeIf { !promising(it, currentMin, map.size, curMinAtPoint.getOrDefault(it.move.point, currentMin)) }
}
return currentMin
}
println(part1(readInput("aoc2023/Day17_test")))
println(part1(readInput("aoc2023/Day17")))
} | 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 6,451 | advent-of-code-kotlin | Apache License 2.0 |
src/Day11.kt | mr-cell | 575,589,839 | false | {"Kotlin": 17585} | import kotlin.math.floor
fun main() {
fun part1(input: List<String>): Long {
val monkeys = input.toMonkeys()
repeat(20) {
monkeys.forEach { monkey ->
val transfers = monkey.inspectItems()
transfers.forEach { transfer -> monkeys[transfer.first].addItem(transfer.second) }
}
}
return monkeys
.map(Monkey::getInspections)
.sortedDescending()
.take(2)
.reduce { acc, i -> acc * i }
}
fun part2(input: List<String>): Long {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
private fun List<String>.toMonkeys(): List<Monkey> = this.filterNot { it == "" }.chunked(6).map { it.toMonkey() }
private fun List<String>.toMonkey(): Monkey {
val startItems = this[1].substringAfter(": ").split(", ").map { it.toLong() }.toMutableList()
val operationValue = this[2].substringAfterLast(" ")
val testParameter = this[3].substringAfterLast(" ").toLong()
val trueMonkey = this[4].substringAfterLast(" ").toInt()
val falseMonkey = this[5].substringAfterLast(" ").toInt()
return Monkey(
items = startItems,
operation = when {
operationValue == "old" -> ({ it * it })
'*' in this[2] -> ({ it * operationValue.toLong() })
else -> ({ it + operationValue.toLong() })
},
test = { i -> (i % testParameter).toInt() == 0 },
trueMonkey = trueMonkey,
falseMonkey = falseMonkey
)
}
class Monkey(
private val items: MutableList<Long>,
private val operation: (Long) -> Long,
private val test: (Long) -> Boolean,
private val trueMonkey: Int,
private val falseMonkey: Int
) {
private var inspections: Long = 0
fun addItem(item: Long) {
items.add(item)
}
fun inspectItems(): List<Transfer> {
inspections += items.size
val transfers = items
.map(operation)
.map { floor(it.toDouble().div(3)).toLong() }
.map {
if(test.invoke(it)) {
Transfer(trueMonkey, it)
} else {
Transfer(falseMonkey, it)
}
}
items.clear()
return transfers
}
fun inspectItemsPart2(): List<Transfer> {
inspections += items.size
val transfers = items
.map(operation)
.map {
if(test.invoke(it)) {
Transfer(trueMonkey, it)
} else {
Transfer(falseMonkey, it)
}
}
items.clear()
return transfers
}
fun getInspections(): Long = inspections
}
private typealias Transfer = Pair<Int, Long> | 0 | Kotlin | 0 | 0 | 2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9 | 3,030 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | GunnarBernsteinHH | 737,845,880 | false | {"Kotlin": 10952} | /*
* --- Day 3: Gear Ratios ---
* Source: https://adventofcode.com/2023/day/3
*/
/** main function containing sub-functions like a class */
fun main() {
data class NumberData(
val value: Int,
val start: Int,
val endExclusive: Int,
var isAdjacent: Boolean = false
)
class LineData(line: String) {
// normally this would be immutable lists
val numbers = mutableListOf<NumberData>()
val symbolMap = mutableMapOf<Int, Char>()
// parse line
init {
var isNumber = false
var start = 0
line.forEachIndexed { pos, c ->
if (c != '.') {
if (c.isDigit()) {
if (!isNumber) {
isNumber = true
start = pos
}
} else {
// is a symbol
if (isNumber) {
isNumber = false
numbers.add(NumberData(line.substring(start, pos).toInt(), start, pos))
}
symbolMap[pos] = c
}
} else {
if (isNumber) {
isNumber = false
numbers.add(NumberData(line.substring(start, pos).toInt(), start, pos))
}
}
}
if (isNumber) {
// isNumber = false
numbers.add(NumberData(line.substring(start).toInt(), start, line.length))
}
}
}
val data = mutableListOf<LineData>()
fun part1(input: List<String>): Int {
fun checkNumberIsAdjacentSymbol(numbers: List<NumberData>, posSymbol: Int) {
numbers.forEach { number ->
if (number.start <= posSymbol + 1 && number.endExclusive >= posSymbol)
number.isAdjacent = true
}
}
// parse input into objects
input.forEach { s ->
val lineData = LineData(s)
data.add(lineData)
}
// find relevant numbers
data.forEachIndexed { lineNo, line ->
line.symbolMap.keys.forEach { pos ->
if (lineNo > 0) {
checkNumberIsAdjacentSymbol(data[lineNo - 1].numbers, pos)
}
checkNumberIsAdjacentSymbol(data[lineNo].numbers, pos)
if (lineNo < data.size - 1) {
checkNumberIsAdjacentSymbol(data[lineNo + 1].numbers, pos)
}
}
}
// add adjacent numbers
var total = 0
data.forEach { line ->
total += line.numbers.filter { it.isAdjacent }.sumOf { it.value }
}
return total
}
// relies on data
data class GearNumber (val numberValue1: Int, var numberValue2: Int, val lineNo: Int, val posSymbol: Int, var gearCount: Int )
fun part2(): Int {
val gears = mutableListOf<GearNumber>()
fun checkNumberIsPotentialGear(numbers: List<NumberData>, posSymbol: Int, lineNo: Int) {
numbers.forEach { number ->
if (number.start <= posSymbol + 1 && number.endExclusive >= posSymbol) {
// is potential gear
val g = gears.filter { it.lineNo == lineNo && it.posSymbol == posSymbol }
if (g.isEmpty()) {
gears.add(GearNumber( number.value, 0, lineNo, posSymbol, 1))
} else {
g[0].gearCount++
if (g[0].gearCount == 2) {
g[0].numberValue2 = number.value
}
}
}
}
}
// find relevant gears: two numbers adjacent to same '*'
data.forEachIndexed { lineNo, line ->
line.symbolMap.forEach { (pos, symbol) ->
if (symbol == '*') {
if (lineNo > 0) {
// no need to check all numbers, only those which are adjacent are candidates
checkNumberIsPotentialGear(data[lineNo - 1].numbers.filter { it.isAdjacent }, pos, lineNo)
}
checkNumberIsPotentialGear(data[lineNo].numbers.filter { it.isAdjacent }, pos, lineNo)
if (lineNo < data.size - 1) {
checkNumberIsPotentialGear(data[lineNo + 1].numbers.filter { it.isAdjacent }, pos, lineNo)
}
}
}
}
// add gears
var total = 0
gears.filter { it.gearCount == 2 }.forEach { gear ->
total += gear.numberValue1 * gear.numberValue2
}
return total
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("input.day02.test1.txt")
// check(part2(testInput) == 840)
val input = readInput("input.day03.txt")
println("Results for 2023, day 3:")
println("Result of part 1: " + part1(input))
println("Result of part 2: " + part2())
}
| 0 | Kotlin | 0 | 0 | bc66eef73bca2e64dfa5d83670266c8aaeae5b24 | 5,198 | aoc-2023-in-kotlin | MIT License |
src/main/kotlin/dev/sirch/aoc/y2022/days/Day02.kt | kristofferchr | 573,549,785 | false | {"Kotlin": 28399, "Mustache": 1231} | package dev.sirch.aoc.y2022.days
import dev.sirch.aoc.Day
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
class Day02(testing: Boolean = false): Day(2022, 2, testing) {
override fun part1(): Int {
return inputLines.sumOf {
val foe = Shape.from(it.first())
val me = Shape.fromMyCode(it.last())
val matchScore = me.playAgainst(foe).scoreValue
return@sumOf me.scoreValue + matchScore
}
}
override fun part2(): Int {
return inputLines.sumOf {
val foe = Shape.from(it.first())
val strategy = PlayOutcome.from(it.last())
val me = Shape.fromMyWinningStrategy(strategy, foe)
val matchScore = me.playAgainst(foe).scoreValue
return@sumOf me.scoreValue + matchScore
}
}
}
enum class PlayOutcome(val codeLetter: Char, val scoreValue: Int) {
Loose('X', 0),
Draw('Y', 3),
Win('Z', 6);
companion object {
fun from(codeLetter: Char): PlayOutcome {
return values().first { it.codeLetter == codeLetter }
}
}
}
enum class Shape(val scoreValue: Int, val codeLetter: Char) {
Rock(scoreValue = 1, codeLetter = 'A') {
override val beatsShape: Shape
get() = Scissor
},
Paper(scoreValue = 2, codeLetter = 'B') {
override val beatsShape: Shape
get() = Rock
},
Scissor(scoreValue = 3, codeLetter = 'C') {
override val beatsShape: Shape
get() = Paper
};
abstract val beatsShape: Shape
fun playAgainst(other: Shape): PlayOutcome {
return when {
this.beatsShape == other -> PlayOutcome.Win
this == other -> PlayOutcome.Draw
other.beatsShape == this -> PlayOutcome.Loose
else -> throw IllegalStateException("Outcome not supported")
}
}
companion object {
fun from(codeLetter: Char): Shape {
return Shape.values().first { it.codeLetter == codeLetter }
}
fun fromMyCode(codeLetter: Char): Shape {
return when (codeLetter) {
'X' -> Rock
'Y' -> Paper
'Z' -> Scissor
else -> throw IllegalArgumentException("Invalid code letter $codeLetter")
}
}
fun fromMyWinningStrategy(strategy: PlayOutcome, foeShape: Shape): Shape {
return when (strategy) {
PlayOutcome.Win -> Shape.values().first { it.beatsShape == foeShape }
PlayOutcome.Loose -> foeShape.beatsShape
PlayOutcome.Draw -> foeShape
}
}
}
}
| 0 | Kotlin | 0 | 0 | 867e19b0876a901228803215bed8e146d67dba3f | 2,663 | advent-of-code-kotlin | Apache License 2.0 |
src/com/ncorti/aoc2022/Day05.kt | cortinico | 571,724,497 | false | {"Kotlin": 5773} | package com.ncorti.aoc2022
import java.util.*
private fun String.processInput(): Pair<List<Stack<Char>>, List<List<Int>>> {
val (stackDefs, moveDefs) = split("\n\n")
val stacks = mutableListOf<Stack<Char>>()
val stackLines = stackDefs.split("\n")
stackLines.last().split(" ").filter(String::isNotBlank).forEach { _ ->
stacks.add(Stack<Char>())
}
for (i in stackLines.size - 2 downTo 0) {
val line = stackLines[i]
val chars = line.toCharArray()
for (j in chars.indices step 4) {
if (chars[j] == '[') {
stacks[j / 4].push(chars[j+1])
}
}
}
val moves = moveDefs.split("\n")
.map {
val tokens = it.split(" ")
listOf(tokens[1].toInt(), tokens[3].toInt(), tokens[5].toInt())
}
return stacks.toList() to moves
}
fun main() {
fun part1() = getInputAsText("05", String::processInput)
.let { (stacks, moves) ->
moves.forEach { (count, from, to) ->
repeat(count) {
stacks[to - 1].push(stacks[from - 1].pop())
}
}
stacks
}
.let {
it.joinToString("") { stack -> stack.peek().toString() }
}
fun part2() = getInputAsText("05", String::processInput)
.let { (stacks, moves) ->
moves.forEach { (count, from, to) ->
val list = mutableListOf<Char>()
repeat(count) {
list.add(stacks[from - 1].pop())
}
repeat(count) {
stacks[to - 1].push(list.removeLast())
}
}
stacks
}
.let {
it.joinToString("") { stack -> stack.peek().toString() }
}
println(part1())
println(part2())
}
| 4 | Kotlin | 0 | 1 | cd9ad108a1ed1ea08f9313c4cad5e52a200a5951 | 1,609 | adventofcode-2022 | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[674]最长连续递增序列.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。
//
// 连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那
//么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。
//
//
//
// 示例 1:
//
//
//输入:nums = [1,3,5,4,7]
//输出:3
//解释:最长连续递增序列是 [1,3,5], 长度为3。
//尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。
//
//
// 示例 2:
//
//
//输入:nums = [2,2,2,2,2]
//输出:1
//解释:最长连续递增序列是 [2], 长度为1。
//
//
//
//
// 提示:
//
//
// 0 <= nums.length <= 104
// -109 <= nums[i] <= 109
//
// Related Topics 数组
// 👍 164 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun findLengthOfLCIS(nums: IntArray): Int {
//连续递增 动态规划 nums[index] > nums[index-1]
//时间复杂度 O(n)
if(nums.isEmpty()) return 0
var index =0 // 开始递增开始 index
var max = 1
for ( i in 1 until nums.size){
if (nums[i] > nums[i-1]){
//符合递增
//计算记录最大长度
max = Math.max(i - index + 1,max)
}else{
index = i
}
}
return max
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,590 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/wtf/log/xmas2021/day/day02/Day02.kt | damianw | 434,043,459 | false | {"Kotlin": 62890} | package wtf.log.xmas2021.day.day02
import wtf.log.xmas2021.Day
import java.io.BufferedReader
object Day02 : Day<List<Instruction>, Int, Int> {
override fun parseInput(reader: BufferedReader): List<Instruction> = reader
.lineSequence()
.map(Instruction::parse)
.toList()
override fun part1(input: List<Instruction>): Int {
val finalPosition = input.fold(Position(), Position::followingSimple)
return finalPosition.horizontal * finalPosition.depth
}
override fun part2(input: List<Instruction>): Int {
val finalPosition = input.fold(Position(), Position::followingWithAim)
return finalPosition.horizontal * finalPosition.depth
}
}
data class Position(
val horizontal: Int = 0,
val depth: Int = 0,
val aim: Int = 0,
) {
fun followingSimple(instruction: Instruction): Position = when (instruction.axis) {
Axis.HORIZONTAL -> copy(horizontal = horizontal + instruction.amount)
Axis.DEPTH -> copy(depth = depth + instruction.amount)
}
fun followingWithAim(instruction: Instruction): Position = when (instruction.axis) {
Axis.HORIZONTAL -> copy(
horizontal = horizontal + instruction.amount,
depth = depth + (aim * instruction.amount),
)
Axis.DEPTH -> copy(aim = aim + instruction.amount)
}
}
data class Instruction(
val axis: Axis,
val amount: Int,
) {
companion object {
fun parse(input: String): Instruction {
val parts = input.split(' ')
require(parts.size == 2)
val axis: Axis
val multiplier: Int
when (val direction = parts.first()) {
"forward" -> {
axis = Axis.HORIZONTAL
multiplier = 1
}
"down" -> {
axis = Axis.DEPTH
multiplier = 1
}
"up" -> {
axis = Axis.DEPTH
multiplier = -1
}
else -> throw IllegalArgumentException("Unknown direction: $direction")
}
return Instruction(axis, multiplier * parts[1].toInt())
}
}
}
enum class Axis {
HORIZONTAL,
DEPTH,
}
| 0 | Kotlin | 0 | 0 | 1c4c12546ea3de0e7298c2771dc93e578f11a9c6 | 2,292 | AdventOfKotlin2021 | BSD Source Code Attribution |
scripts/profiling/CompareCSVs.kts | TIBHannover | 197,416,205 | false | {"Kotlin": 3096016, "Cypher": 217169, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240} | #!/usr/bin/env kscript
import java.io.File
val fileA = args.getOrElse(0) { "before.csv" }
val fileB = args.getOrElse(1) { "after.csv" }
val mapA = readCSV(fileA)
val mapB = readCSV(fileB)
var totalTimeA: Long = 0
var totalTimeB: Long = 0
var totalMethodCount = 0
println("Comparing $fileA (A) to $fileB (B)")
(mapA.keys intersect mapB.keys).forEach { repo ->
println("$repo:")
val methodsA = computeMethodResults(mapA[repo]!!)
val methodsB = computeMethodResults(mapB[repo]!!)
var timeA: Long = 0
var timeB: Long = 0
var methodCount = 0
(methodsA.keys intersect methodsB.keys).forEach { method ->
val resultA = methodsA[method]!!
val resultB = methodsB[method]!!
print(" ")
print("avg: ${resultA.average} ${resultB.average} ${resultB.average - resultA.average} ")
print("median: ${resultA.median} ${resultB.median} ${resultB.median - resultA.median} ")
println(method)
timeA += resultA.average
timeB += resultB.average
methodCount++
}
println("Repository average: ${timeA.toDouble() / methodCount} ${timeB.toDouble() / methodCount} ${(timeB - timeA).toDouble() / methodCount}")
println()
totalTimeA += timeA
totalTimeB += timeB
totalMethodCount += methodCount
}
println("Total average: ${totalTimeA.toDouble() / totalMethodCount} ${totalTimeB.toDouble() / totalMethodCount} ${(totalTimeB - totalTimeA).toDouble() / totalMethodCount}")
println("Ratio A/B: ${totalTimeA.toDouble() / totalTimeB.toDouble()}")
println("Ratio B/A: ${totalTimeB.toDouble() / totalTimeA.toDouble()}")
fun computeMethodResults(measurements: List<Measurement>): Map<String, ProfilingResult> {
val methodToResult: MutableMap<String, MutableList<Long>> = mutableMapOf()
measurements.forEach {
methodToResult.getOrPut(it.method) { mutableListOf() } += it.time
}
return methodToResult.mapValues { (_, times) ->
ProfilingResult(times.sum() / times.size, times.median())
}
}
fun readCSV(csv: String): MutableMap<String, MutableList<Measurement>> {
val result: MutableMap<String, MutableList<Measurement>> = mutableMapOf()
File(csv).useLines { lines ->
lines.forEach { line ->
val split = line.split(",")
val measurement = Measurement(
repository = split[0],
method = split[1],
time = split[2].toLong()
)
result.getOrPut(measurement.repository) { mutableListOf() } += measurement
}
}
return result
}
data class Measurement(
val repository: String,
val method: String,
val time: Long
)
data class ProfilingResult(
val average: Long,
val median: Long
)
fun List<Long>.median() =
sorted().let {
if (size % 2 == 0)
(this[size / 2] + this[(size - 1) / 2]) / 2
else
this[size / 2]
}
| 0 | Kotlin | 1 | 4 | bcc5b31678df9610bb2128dd14fd5fe34461eea8 | 2,916 | orkg-backend | MIT License |
src/day02/Day02.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day02
import println
import readInput
data class Position(val aim: Int = 0, val depth: Int = 0, val position: Int = 0)
fun main() {
fun part1(input: List<String>): Int = input.map { line -> line.split(" ") }
.fold(Position()) { acc, next ->
when (next[0]) {
"forward" -> acc.copy(position = acc.position + next[1].toInt())
"down" -> acc.copy(depth = acc.depth + next[1].toInt())
"up" -> acc.copy(depth = acc.depth - next[1].toInt())
else -> throw IllegalArgumentException("Don't understand ${next[0]}")
}
}.let { it.depth * it.position }
fun part2(input: List<String>): Int = input.map { line -> line.split(" ") }
.fold(Position()) { acc, next ->
when (next[0]) {
"forward" -> acc.copy(
depth = acc.depth + acc.aim * next[1].toInt(),
position = acc.position + next[1].toInt()
)
"down" -> acc.copy(aim = acc.aim + next[1].toInt())
"up" -> acc.copy(aim = acc.aim - next[1].toInt())
else -> throw IllegalArgumentException("Don't understand ${next[0]}")
}
}.let { it.depth * it.position }
val testInput = readInput("day02/Day02_test")
check(part1(testInput) == 150)
check(part2(testInput) == 900)
val input = readInput("day02/Day02")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 1,490 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/endredeak/aoc2022/Day15.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
import kotlin.math.abs
fun main() {
solve("Beacon Exclusion Zone") {
fun Pair<Int, Int>.manhattanRange(m: Int): Pair<IntRange, IntRange> =
(this.first - m..this.first + m) to (this.second - m..this.second + m)
infix fun Pair<Int, Int>.manhattan(other: Pair<Int, Int>) =
abs(this.first - other.first) + abs(this.second - other.second)
val input = lines
.map { Regex(".*x=(-?\\d+), y=(-?\\d+).*x=(-?\\d+), y=(-?\\d+)").find(it)!!.destructured }
.map { m -> m.toList().map { it.toInt() } }
.map { (sx, sy, bx, by) -> (sx to sy) to (bx to by) }
.map { Triple(it.first, it.second, it.first manhattan it.second) }
part1(4883971) {
val y = 10
input
.map { it to it.first.manhattanRange(it.third) }
.filter { (_, r) -> y in r.second }
.flatMap { line ->
val (s, _, m) = line.first
val d = abs(m - abs(s.second - y))
(s.first - d..s.first + d).map { it to y }
}
.toSet()
.minus(input.map { it.second }.toSet())
.size
}
part2(12691026767556) {
val max = 4000000
(0..max)
.mapNotNull { x ->
var y = 0
while (y <= max) {
val sensor = input.find { it.first manhattan (x to y) <= it.third } ?: return@mapNotNull x to y
y = sensor.first.second + sensor.third - abs(x - sensor.first.first) + 1
}
null
}
.first()
.let { it.first.toLong() * 4000000L + it.second.toLong() }
}
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 1,842 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
src/main/kotlin/com/ginsberg/advent2022/Day05.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 5 - Supply Stacks
* Problem Description: http://adventofcode.com/2022/day/5
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day5/
*/
package com.ginsberg.advent2022
class Day05(input: List<String>) {
private val stacks: List<MutableList<Char>> = createStacks(input)
private val instructions: List<Instruction> = parseInstructions(input)
fun solvePart1(): String {
performInstructions(true)
return stacks.tops()
}
fun solvePart2(): String {
performInstructions(false)
return stacks.tops()
}
private fun performInstructions(reverse: Boolean) {
instructions.forEach { (amount, source, destination) ->
val toBeMoved = stacks[source].take(amount)
repeat(amount) { stacks[source].removeFirst() }
stacks[destination].addAll(0, if (reverse) toBeMoved.reversed() else toBeMoved)
}
}
private fun Iterable<Iterable<Char>>.tops(): String =
map { it.first() }.joinToString("")
private fun createStacks(input: List<String>): List<MutableList<Char>> {
val stackRows = input.takeWhile { it.contains('[') }
return (1..stackRows.last().length step 4).map { index ->
stackRows
.mapNotNull { it.getOrNull(index) }
.filter { it.isUpperCase() }
.toMutableList()
}
}
private fun parseInstructions(input: List<String>): List<Instruction> =
input
.dropWhile { !it.startsWith("move") }
.map { row ->
row.split(" ").let { parts ->
Instruction(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
}
}
private data class Instruction(val amount: Int, val source: Int, val target: Int)
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 1,909 | advent-2022-kotlin | Apache License 2.0 |
src/main/kotlin/graph/variation/NumShortestPaths.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.*
import util.OneArray
import java.util.*
import kotlin.collections.HashMap
// given # of shortest paths (that should have equal length) in a graph G = (V, E)
// starting with vertex v in V
fun <V> WeightedGraph<V, Int>.numShortestPaths(s: Vertex<V>,
t: Vertex<V>,
checkIdentity: Boolean = true): Int {
val (dist, _) = dijkstra(s, checkIdentity)
// O(E log V)
val newEdges = HashSet<WeightedEdge<V, Int>>()
weightedEdges.forEach { edge ->
val (start, end, _, w) = edge
if (dist[end]!! == dist[start]!! + w!!) {
newEdges.add(edge)
}
}
val newGraph = WeightedGraph(vertices, newEdges)
val list = newGraph.topoSort()
// O(V + E)
val dict = HashMap<Vertex<V>, Int>()
list.forEachIndexed { i, vertex ->
dict[vertex] = i
}
val num = OneArray(list.size) { 0 }
num[dict[t]!!] = 1
for (i in dict[t]!! - 1 downTo dict[s]!!) {
num[i] = getEdgesFrom(list[i], checkIdentity)
.map { num[dict[it.vertex2]!!] }
.sum()
}
// num.prettyPrintln()
return num[dict[s]!!]
}
fun main(args: Array<String>) {
val V = (0..2).map { Vertex(it) }
val E = setOf(
WeightedEdge(V[0], V[1], true, 1),
WeightedEdge(V[1], V[2], true, 2),
WeightedEdge(V[0], V[2], true, 3))
val G = WeightedGraph(V, E)
println(G.numShortestPaths(V[0], V[2]))
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,399 | AlgoKt | MIT License |
src/day09/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day09
import println
import readInput
fun main() {
fun diffList(numbers: List<Long>): List<Long> {
return (0..<(numbers.size-1)).map {
numbers[it + 1] - numbers[it]
}.toList()
}
fun extrapolateLine(numbers: List<Long>): Long {
var diffs = diffList(numbers)
if (diffs.sum() == 0L) return numbers.last()
return numbers.last() + extrapolateLine(diffs)
}
fun toList(input: String): List<Long> {
return input.split(" ").map { number -> number.toLong() }
}
check(extrapolateLine(toList("0 3 6 9 12 15")) == 18L)
check(readInput("day09/test1").map(::toList).map(::extrapolateLine).sum() == 114L)
"Part 1:".println()
readInput("day09/input").map(::toList)
.map(::extrapolateLine)
.sum().println()
check(extrapolateLine(toList("10 13 16 21 30 45").reversed()) == 5L)
"Part 2:".println()
readInput("day09/input").map(::toList)
.map { it.reversed() }
.map(::extrapolateLine)
.sum().println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 1,050 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimizeMax.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
/**
* 2616. Minimize the Maximum Difference of Pairs
* @see <a href="https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs/">Source</a>
*/
fun interface MinimizeMax {
operator fun invoke(nums: IntArray, p: Int): Int
}
/**
* Greedy + Binary Search
*/
class MinimizeMaxGreedyBS : MinimizeMax {
override operator fun invoke(nums: IntArray, p: Int): Int {
nums.sort()
val n = nums.size
var left = 0
var right = nums[n - 1] - nums[0]
while (left < right) {
val mid = left + (right - left) / 2
// If there are enough pairs, look for a smaller threshold.
// Otherwise, look for a larger threshold.
if (countValidPairs(nums, mid) >= p) {
right = mid
} else {
left = mid + 1
}
}
return left
}
// Find the number of valid pairs by greedy approach
private fun countValidPairs(nums: IntArray, threshold: Int): Int {
var index = 0
var count = 0
while (index < nums.size - 1) {
// If a valid pair is found, skip both numbers.
if (nums[index + 1] - nums[index] <= threshold) {
count++
index++
}
index++
}
return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,978 | kotlab | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2021/Day8.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
import java.util.BitSet
class Day8 : AdventDay(2021, 8) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day8()
report {
day.part1()
}
report {
day.part2()
}
}
val maxSegments = 7
val numbers = listOf(
BitSet(maxSegments).apply { listOf(0, 1, 2, 4, 5, 6).forEach { set(it) } }, // 0
BitSet(maxSegments).apply { listOf(2, 5).forEach { set(it) } }, // 1
BitSet(maxSegments).apply { listOf(0, 2, 3, 4, 6).forEach { set(it) } }, // 2
BitSet(maxSegments).apply { listOf(0, 2, 3, 5, 6).forEach { set(it) } }, // 3
BitSet(maxSegments).apply { listOf(1, 2, 3, 5).forEach { set(it) } }, // 4
BitSet(maxSegments).apply { listOf(0, 1, 3, 5, 6).forEach { set(it) } }, // 5
BitSet(maxSegments).apply { listOf(0, 1, 3, 4, 5, 6).forEach { set(it) } }, // 6
BitSet(maxSegments).apply { listOf(0, 2, 5).forEach { set(it) } }, // 7
BitSet(maxSegments).apply { listOf(0, 1, 2, 3, 4, 5, 6).forEach { set(it) } }, // 8
BitSet(maxSegments).apply { listOf(0, 1, 2, 3, 5, 6).forEach { set(it) } } // 9
)
val uniqueCardinality =
numbers.groupBy { it.cardinality() }.filter { it.value.size == 1 }.values.flatten().map { it.cardinality() }
.filter { it < maxSegments }
val uniqueCardinalityDigits = numbers.mapIndexed { index, bitSet -> index to bitSet }
.filter { it.second.cardinality() in uniqueCardinality }.toMap().mapKeys { it.value.cardinality() }
val uniqueSegmentTotals =
(0 until maxSegments).groupBy { segment -> numbers.count { it[segment] } }.filter { it.value.size == 1 }
.mapValues { it.value.single() }.map { it.value to it.key }.toMap()
}
data class Signal(val input: List<BitSet>, val output: List<BitSet>)
fun findDigits(signals: List<Signal>): Int {
val uniqueNumbers =
numbers.groupBy { it.cardinality() }.filter { it.value.size == 1 }.values.flatten().map { it.cardinality() }
return signals.sumOf { it.output.count { it.cardinality() in uniqueNumbers } }
}
val inputAsSignals = parseInput(inputAsLines)
fun parseInput(input: List<String>): List<Signal> {
return input.map { toSignal(it) }
}
fun String.toBitSet(): BitSet {
val s = this
return BitSet(maxSegments).apply { (0 until maxSegments).map { set(it, s.contains('a' + it)) } }
}
private fun BitSet.getBitsSet(): Set<Int> {
return (0 until size()).filter { this[it] }.toSet()
}
fun toSignal(input: String): Signal {
val (input, display) = input.split("|").map { it.trim() }
val patterns = input.split(" ").map { it.trim() }.map { it.toBitSet() }
val output = display.split(" ").map { it.trim() }.map { it.toBitSet() }
return Signal(patterns, output)
}
fun signalToNumber(
signal: Signal
): Int {
val possibilities = (0 until maxSegments).associateWith { (0 until maxSegments).toSet() }.toMutableMap()
val uniqueEntries = signal.input.filter { it.cardinality() in uniqueCardinality }
.map { it to uniqueCardinalityDigits[it.cardinality()]!! }
uniqueEntries.forEach { (entry, real) ->
real.getBitsSet().forEach { seg ->
possibilities[seg] = possibilities[seg]!!.intersect(entry.getBitsSet())
}
}
uniqueSegmentTotals.forEach { (seg, total) ->
val entrySeg = (0 until maxSegments).first { en -> signal.input.count { it[en] } == total }
possibilities[seg] = setOf(entrySeg)
}
if (possibilities.values.any { it.size == 1 }) {
do {
val old = possibilities.map { it.value.size }
val ones = possibilities.filter { it.value.size == 1 }.values.map { it.single() }
for (seg in possibilities.keys) {
val current = possibilities[seg]!!
if (current.size == 1 && current.single() in ones) {
continue
}
possibilities[seg] = current - ones
}
if (possibilities.map { it.value.size } == old) {
break
}
if (possibilities.values.all { it.size == 1 }) {
break
}
} while (possibilities.map { it.value.size } != old && possibilities.values.any { it.size > 1 })
}
val used = possibilities.mapValues { it.value.single() }
val digits = signal.output.map { digi ->
BitSet().apply {
(0 until maxSegments).forEach {
this[it] = digi[used[it]!!]
}
}
}
val mapped = digits.map { numbers.indexOf(it) }
return mapped.joinToString("").toInt()
}
fun parseSignalsToNumbers(input: List<Signal>): Int {
return input.sumOf { signal ->
signalToNumber(signal)
}
}
fun part1(): Int {
return findDigits(inputAsSignals)
}
fun part2(): Int {
return parseSignalsToNumbers(inputAsSignals)
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 5,481 | adventofcode | MIT License |
src/main/kotlin/com/ginsberg/advent2020/Day22.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 22 - Crab Combat
* Problem Description: http://adventofcode.com/2020/day/22
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day22/
*/
package com.ginsberg.advent2020
import java.util.Objects
typealias Deck = MutableList<Int>
class Day22(input: List<String>) {
private val deck1: Deck = input.drop(1).takeWhile { it.isNotBlank() }.map { it.toInt() }.toMutableList()
private val deck2: Deck = input.dropWhile { it.isNotBlank() }.drop(2).map { it.toInt() }.toMutableList()
fun solvePart1(): Int =
playUntilWinner().score()
fun solvePart2(): Int =
playUntilWinner(true).score()
private fun playUntilWinner(allowRecursive: Boolean = false): Deck =
if (playGame(deck1, deck2, allowRecursive)) deck1 else deck2
private fun playGame(deckA: Deck, deckB: Deck, allowRecursive: Boolean): Boolean {
val history = mutableSetOf(Objects.hash(deckA, deckB))
deckA.pairedWith(deckB).forEach { (a, b) ->
val winner = when {
allowRecursive && deckA.size >= a && deckB.size >= b ->
playGame(
deckA.take(a).toMutableList(),
deckB.take(b).toMutableList(),
true
)
else -> a > b
}
if (winner) deckA.addAll(listOf(a, b)) else deckB.addAll(listOf(b, a))
if(allowRecursive) {
Objects.hash(deckA, deckB).also {
if (it in history) return true else history += it
}
}
}
return deckA.isNotEmpty()
}
private fun Deck.score(): Int =
this.foldIndexed(0) { index, acc, current -> acc + (current * (size - index)) }
private fun Deck.pairedWith(other: Deck): Sequence<Pair<Int, Int>> = sequence {
while (this@pairedWith.isNotEmpty() && other.isNotEmpty()) {
yield(Pair(this@pairedWith.removeFirst(), other.removeFirst()))
}
}
}
| 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 2,098 | advent-2020-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NamingCompany.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
/**
* 2306. Naming a Company
* @see <a href="https://leetcode.com/problems/naming-a-company/">Source</a>
*/
fun interface NamingCompany {
fun distinctNames(ideas: Array<String>): Long
}
class NamingCompanyCountPairs : NamingCompany {
override fun distinctNames(ideas: Array<String>): Long {
var res: Long = 0
val cnt = Array(ALPHABET_LETTERS_COUNT) { LongArray(ALPHABET_LETTERS_COUNT) }
val s: Array<MutableSet<String>> = Array(ALPHABET_LETTERS_COUNT) { mutableSetOf() }
for (idea in ideas) {
s[idea[0] - 'a'].add(idea.substring(1))
}
for (i in 0 until ALPHABET_LETTERS_COUNT) {
for (suff in s[i]) {
for (j in 0 until ALPHABET_LETTERS_COUNT) {
cnt[i][j] += (if (s[j].contains(suff)) 0 else 1).toLong()
}
}
}
for (i in 0 until ALPHABET_LETTERS_COUNT) {
for (j in 0 until ALPHABET_LETTERS_COUNT) {
res += cnt[i][j] * cnt[j][i]
}
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,764 | kotlab | Apache License 2.0 |
04/04.kt | Steve2608 | 433,779,296 | false | {"Python": 34592, "Julia": 13999, "Kotlin": 11412, "Shell": 349, "Cython": 211} | import java.io.File
private class Bingo(board: List<String>) {
val numbers: Array<IntArray>
val marked: Array<BooleanArray>
val calledNumbers: MutableList<Int> = mutableListOf(-1)
init {
fun getLine(board: List<String>, line: Int) =
board[line].split("\\s+".toRegex()).filter { it.isNotBlank() }.map { it.toInt() }.toIntArray()
numbers = Array(board.size) { i -> getLine(board, i) }
marked = Array(board.size) { i -> getLine(board, i).map { false }.toBooleanArray() }
}
val hasWinner: Boolean
get() {
if (marked.any { array -> array.all { it } }) return true
for (i in 0..marked.lastIndex) {
if (marked.all { it[i] }) return true
}
return false
}
val winningScore: Int
get() {
var sum = 0
for (i in 0..numbers.lastIndex) {
for (j in 0..numbers[i].lastIndex) {
if (!marked[i][j]) sum += numbers[i][j]
}
}
return sum * calledNumbers.last()
}
fun callNumber(number: Int) {
numbers.forEachIndexed { i, a ->
val index = a.indexOf(number)
if (index >= 0) marked[i][index] = true
}
calledNumbers.add(number)
}
override fun toString(): String =
numbers.joinToString(separator = "\n") { it.joinToString(separator = " ") { num -> "%02d".format(num) } } + "\n" +
marked.joinToString(separator = "\n") { it.joinToString(separator = " ") { mark -> if (mark) "XX" else "__" } }
}
private fun part1(filename: String): Int {
val (numbers, boards) = File(filename).readData()
numbers.forEach {
for (board in boards) {
board.callNumber(it)
if (board.hasWinner) return board.winningScore
}
}
return -1
}
private fun part2(filename: String): Int {
val (numbers, boards) = File(filename).readData()
var prev = boards.toMutableList()
var curr = mutableListOf<Bingo>()
numbers.forEach {
prev.forEach { board ->
board.callNumber(it)
if (board.hasWinner) {
if (prev.size == 1) return board.winningScore
} else {
curr.add(board)
}
}
prev = curr
curr = mutableListOf()
}
return -1
}
private fun File.readData(): Pair<IntArray, MutableList<Bingo>> {
val lines = this.readLines().filter { it.isNotBlank() }
val numbers = lines[0].split(",").map { it.toInt() }.toIntArray()
val games: MutableList<Bingo> = mutableListOf()
for (i in 1..lines.lastIndex step 5) {
val board = lines.subList(i, i + 5)
games.add(Bingo(board))
}
return Pair(numbers, games)
}
fun main() {
assert(4512 == part1("example.txt")) { "Expected 188 * 24 = 4512" }
assert(1924 == part2("example.txt")) { "Expected 148 * 13 = 1924" }
println(part1("input.txt"))
println(part2("input.txt"))
} | 0 | Python | 0 | 1 | 2dcad5ecdce5e166eb053593d40b40d3e8e3f9b6 | 2,591 | AoC-2021 | MIT License |
src/main/kotlin/ru/timakden/aoc/year2022/Day14.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2022
import ru.timakden.aoc.util.Point
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
import kotlin.math.max
import kotlin.math.min
/**
* [Day 14: Regolith Reservoir](https://adventofcode.com/2022/day/14).
*/
object Day14 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2022/Day14")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val cave = buildCave(input)
val sandSource = Point(500, 0)
val caveLimits = listOf(
cave.minOf { it.x },
cave.maxOf { it.x },
cave.maxOf { it.y }
)
var counter = 0
outer@ while (true) {
var unitOfSand = sandSource
while (true) {
val (x, y) = unitOfSand
if (Point(x, y + 1) !in cave) unitOfSand = unitOfSand.copy(y = y + 1) else {
if (Point(x - 1, y + 1) in cave) {
if (Point(x + 1, y + 1) in cave) {
counter++
cave += unitOfSand
break
} else unitOfSand = Point(x + 1, y + 1)
} else unitOfSand = Point(x - 1, y + 1)
if (unitOfSand.x in caveLimits || unitOfSand.y in caveLimits) break@outer
}
}
}
return counter
}
fun part2(input: List<String>): Int {
val cave = buildCave(input)
val sandSource = Point(500, 0)
val caveLimit = cave.maxOf { it.y + 1 }
var counter = 0
outer@ while (true) {
var unitOfSand = sandSource
while (true) {
val (x, y) = unitOfSand
if (Point(x, y + 1) !in cave) unitOfSand = unitOfSand.copy(y = y + 1) else
if (Point(x - 1, y + 1) in cave) {
if (Point(x + 1, y + 1) in cave) {
counter++
cave += unitOfSand
if (unitOfSand == sandSource)
break@outer
break
} else unitOfSand = Point(x + 1, y + 1)
} else unitOfSand = Point(x - 1, y + 1)
if (unitOfSand.y == caveLimit) {
counter++
cave += unitOfSand
if (unitOfSand == sandSource) break@outer
break
}
}
}
return counter
}
private fun buildCave(input: List<String>): MutableSet<Point> {
val cave = mutableSetOf<Point>()
input.forEach { line ->
val points = line.split(" -> ").map { point ->
point.split(',').let { Point(it.first().toInt(), it.last().toInt()) }
}
(1..points.lastIndex).forEach { index ->
val point1 = points[index - 1]
val point2 = points[index]
(min(point1.x, point2.x)..max(point1.x, point2.x)).forEach {
cave += Point(it, point1.y)
}
(min(point1.y, point2.y)..max(point1.y, point2.y)).forEach {
cave += Point(point1.x, it)
}
}
}
return cave
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 3,502 | advent-of-code | MIT License |
java/app/src/main/kotlin/com/github/ggalmazor/aoc2021/day22/Cuboid.kt | ggalmazor | 434,148,320 | false | {"JavaScript": 80092, "Java": 33594, "Kotlin": 14508, "C++": 3077, "CMake": 119} | package com.github.ggalmazor.aoc2021.day22
data class Cuboid(val xx: IntRange, val yy: IntRange, val zz: IntRange) {
fun within(other: Cuboid): Boolean = other.xx.contains(xx.first) && other.xx.contains(xx.last)
&& other.yy.contains(yy.first) && other.yy.contains(yy.last)
&& other.zz.contains(zz.first) && other.zz.contains(zz.last)
private fun overlaps(other: Cuboid): Boolean {
return (other.xx.contains(xx.first) || xx.contains(other.xx.first))
&& (other.yy.contains(yy.first) || yy.contains(other.yy.first))
&& (other.zz.contains(zz.first) || zz.contains(other.zz.first))
}
fun subtract(other: Cuboid): List<Cuboid> {
if (!overlaps(other))
return listOf(this)
val subtraction = mutableListOf<Cuboid>()
if (xx.first < other.xx.first)
subtraction.add(Cuboid(xx.first until other.xx.first, yy, zz))
if (other.xx.last < xx.last)
subtraction.add(Cuboid(other.xx.last + 1..xx.last, yy, zz))
val xxRest = IntRange(
if (xx.first < other.xx.first) other.xx.first else xx.first,
if (other.xx.last < xx.last) other.xx.last else xx.last
)
if (yy.first < other.yy.first)
subtraction.add(Cuboid(xxRest, yy.first until other.yy.first, zz))
if (other.yy.last < yy.last)
subtraction.add(Cuboid(xxRest, other.yy.last + 1..yy.last, zz))
val yyRest = IntRange(
if (yy.first < other.yy.first) other.yy.first else yy.first,
if (other.yy.last < yy.last) other.yy.last else yy.last
)
if (zz.first < other.zz.first)
subtraction.add(Cuboid(xxRest, yyRest, zz.first until other.zz.first))
if (other.zz.last < zz.last)
subtraction.add(Cuboid(xxRest, yyRest, other.zz.last + 1..zz.last))
return subtraction
}
fun size(): Long = xx.count().toLong() * yy.count().toLong() * zz.count().toLong()
}
| 0 | JavaScript | 0 | 0 | 7a7ec831ca89de3f19d78f006fe95590cc533836 | 2,005 | aoc2021 | Apache License 2.0 |
src/main/kotlin/com/github/freekdb/aoc2019/Day08.kt | FreekDB | 228,241,398 | false | null | package com.github.freekdb.aoc2019
import java.io.File
// https://adventofcode.com/2019/day/8
fun main() {
val input = File("input/day-08--input.txt").readLines()[0]
println("Input length: ${input.length}.")
println("15000 == 9925 + 2524 + 2551 = ${9925 + 2524 + 2551}")
val width = 25
val height = 6
val layerSize = width * height
solvePart1(input, layerSize)
solvePart2(input, width, height, layerSize)
}
enum class DigitColor(val value: Char) {
BLACK('0'),
WHITE('1'),
TRANSPARENT('2')
}
@Suppress("SameParameterValue")
private fun solvePart1(input: String, layerSize: Int) {
val digitFrequencies: Map<Char, Int>? = input
.chunked(layerSize)
.map { layerDigits -> layerDigits.toList().groupingBy { it }.eachCount() }
.minBy { it[DigitColor.BLACK.value] ?: 0 }
println("Digit frequencies in layer with fewest '${DigitColor.BLACK.value}' digits: $digitFrequencies.")
if (digitFrequencies != null) {
val product = (digitFrequencies[DigitColor.WHITE.value] ?: 0) *
(digitFrequencies[DigitColor.TRANSPARENT.value] ?: 0)
println("Calculation -- '${DigitColor.WHITE.value}' frequency times" +
" '${DigitColor.TRANSPARENT.value}' frequency =>")
println("${digitFrequencies[DigitColor.WHITE.value]} * ${digitFrequencies[DigitColor.TRANSPARENT.value]} =" +
" $product.")
}
println()
}
fun solvePart2(input: String, width: Int, height: Int, layerSize: Int) {
for (rowIndex in 0 until height) {
for (columnIndex in 0 until width) {
var digitIndex = rowIndex * width + columnIndex
var digit = DigitColor.TRANSPARENT.value
while (digit == DigitColor.TRANSPARENT.value && digitIndex < input.length) {
digit = input[digitIndex]
digitIndex += layerSize
}
// For enhanced readability, I replace all black positions with spaces.
print(if (digit == DigitColor.BLACK.value) ' ' else digit)
}
println()
}
}
| 0 | Kotlin | 0 | 1 | fd67b87608bcbb5299d6549b3eb5fb665d66e6b5 | 2,103 | advent-of-code-2019 | Apache License 2.0 |
src/main/day3/Day03.kt | Derek52 | 572,850,008 | false | {"Kotlin": 22102} | package main.day3
import main.readInput
val priorityMap = HashMap<Char, Int>()
fun main() {
val input = readInput("day3/day3")
var count = 1
val alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for (letter in alphabet) {
priorityMap[letter] = count
count++
}
val firstHalf = false
//testAlg(firstHalf)
if (firstHalf) {
println((part1(input)))
} else {
println((part2(input)))
}
}
fun part1(input: List<String>) : Int {
var prioritySum = 0
for (line in input) {
val hashSet = HashSet<Char>()
val a = line.substring(0, line.length/2)
val b = line.substring(line.length/2)
for (letter in a) {
hashSet.add(letter)
}
for (letter in b) {
if (hashSet.contains(letter)) {
prioritySum += priorityMap[letter]!!
continue
}
}
}
return prioritySum
}
fun part2(input: List<String>) : Int {
var prioritySum = 0
for (i in input.indices step 3) {
val hashMap = HashMap<Char, Int>()
for (letter in input[i]) {
if (!hashMap.contains(letter)) {//if hashmap does not contain letter already
hashMap[letter] = 1
}
}
for (letter in input[i+1]) {
if (hashMap.contains(letter)) {
hashMap[letter] = 2
}
}
for (letter in input[i+2]) {
if (hashMap.contains(letter)) {
if (hashMap[letter] == 2) {
//println("Shared letter is ${letter}")
prioritySum += priorityMap[letter]!!
break
}
}
}
}
return prioritySum
}
fun testAlg(firstHalf: Boolean) {
val input = readInput("day3/test_day3")
if (firstHalf) {
println(part1(input))
} else {
println(part2(input))
}
} | 0 | Kotlin | 0 | 0 | c11d16f34589117f290e2b9e85f307665952ea76 | 1,976 | 2022AdventOfCodeKotlin | Apache License 2.0 |
src/main/kotlin/eu/qiou/aaf4k/util/algorithm/Algorithm.kt | 6234456 | 191,817,083 | false | null | package eu.qiou.aaf4k.util.algorithm
import eu.qiou.aaf4k.util.mkString
import java.math.BigInteger
import kotlin.math.roundToInt
import kotlin.random.Random
object Algorithm {
val PRIMES = mutableListOf(2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L)
private val CHECK_IF_GT = 100_000L
fun sequentialIsPrime(n:Long):Boolean {
if (PRIMES.binarySearch(n) >= 0)
return true
if (preliminaryCheck(n) || (n >= CHECK_IF_GT && checkLargePrime(n))){
val ende = Math.sqrt(n.toDouble()).roundToInt() + 1
PRIMES.forEachIndexed { index, l ->
if (l > ende) {
PRIMES.add(n)
return true
}
if (index > 2){
if(n.rem(l) == 0L)
return false
}
}
}
return false
}
private fun preliminaryCheck(n:Long):Boolean{
val digit = truncatNumber(n, 1)
if (digit.rem(2) == 0L || digit.rem(5) == 0L || threeDividable(n))
return false
return true
}
fun primesBefore(n: Long):List<Long>{
if (PRIMES.last() >= n) {
var tmp = n
while (true){
val a = PRIMES.binarySearch(tmp)
if(a < 0) tmp-- else return PRIMES.take(a+1)
}
}
(PRIMES.last() until(n+1)).forEach { sequentialIsPrime(it) }
return PRIMES
}
fun threeDividable(n:Long): Boolean {
val len = totalDigit(n) + 1
if (len < 3) return n.rem(3L) == 0L
return threeDividable((1 until len).fold(0){ acc, i -> acc + digitAt(n, i) }.toLong())
}
fun digitAt(number: Long, position: Int):Int {
if( position <= 0 || position > totalDigit(number) )
throw Exception("ParameterException: position $position not allowed")
return (if(position == 1)
truncatNumber(number, 1)
else
(truncatNumber(number, position) - truncatNumber(number, position -1)) / (1 until position-1).fold(10L){acc, _ -> acc * 10L }
).toInt()
}
// take the digit from right to left, starting from 1
fun truncatNumber(number: Long, take: Int, fromLeft: Boolean = false):Long{
val tmp = splitNumberAt(number, take, fromLeft)
return if (fromLeft) tmp.first else tmp.second
}
fun splitNumberAt(number: Long, at: Int, fromLeft: Boolean = false): Pair<Long, Long>{
if (fromLeft && totalDigit(number) == at)
return number to 0L
if (!fromLeft && at == 0)
return number to 0L
val divisor = (1 until if (fromLeft) totalDigit(number) - at else at).fold(10L){acc, _ -> acc * 10L }
return (number / divisor) to number.rem(divisor)
}
fun totalDigit(number: Long): Int{
var res = 1
var divisor = 10L
while (true){
if (number.rem(divisor) == number)
return res
divisor *= 10L
res++
}
}
fun gcd(a: BigInteger, b: BigInteger): BigInteger {
if ( a < BigInteger.ZERO || b < BigInteger.ZERO)
throw Exception("Only nature number supported.")
if (a == BigInteger.ZERO || b == BigInteger.ZERO) return BigInteger.ZERO
if (a == b) return a
return if (a > b){
val rem2 = a.rem(b)
if (rem2 == BigInteger.ZERO)
b
else
gcd(b, rem2)
} else{
gcd(b, a)
}
}
fun gcd(a: Long, b: Long): Long {
if ( a < 0L || b < 0L)
throw Exception("Only nature number supported.")
if (a == 0L || b == 0L) return 0L
if (a == b) return a
return if (a > b){
val rem2 = a.rem(b)
if (rem2 == 0L)
b
else
gcd(b, rem2)
} else{
gcd(b, a)
}
}
fun gcd(a:Int, b:Int):Int {
return gcd(a.toLong(), b.toLong()).toInt()
}
fun lcm(a: Int, b: Int):Long{
return lcm(a.toLong(), b.toLong())
}
fun lcm(a:Long, b:Long):Long {
return a * b / gcd(a, b)
}
fun serial(start: Long, generator: (Long)-> Long):List<Long>{
val res = mutableListOf<Long>()
var a = start
while (!res.contains(a)){
res.add(a)
a = generator(a)
}
return res
}
// a * x + b * y = gcd solve x, y | integer
fun gcdSolution(a: Long, b: Long, gcd: Long = gcd(a, b)): Pair<Long, Long>{
if (a > b){
if (gcd == 0L) return 0L to 0L
if (b == 0L && a == 1L && gcd == 1L) return 1L to 0L
if (a.rem(b) == gcd) return 1L to -1L * (a / b)
val p = gcdSolution(b, a.rem(b), gcd)
return p.second to (p.second * (a / b) * (-1L) + p.first)
}
return gcdSolution(b, a, gcd).let {
it.second to it.first
}
}
// invoke primeBefore to prepare the prime numbers first
fun factorialPrime(n:Long): Map<Long, Int>{
if (n <= 1)
throw java.lang.Exception("ParameterException: n should be greater than 1")
if(PRIMES.last() < n)
primesBefore(n)
if (PRIMES.binarySearch(n) >= 0){
return mapOf(n to 1)
}
var tmp = n
val res = mutableMapOf<Long, Int>()
PRIMES.forEach {
if (tmp == 1L)
return res
var cnt = 0
while (true){
if(tmp.rem(it) != 0L){
if (cnt > 0){
res.put(it, cnt)
}
break
}
tmp /= it
cnt++
}
}
return res
}
fun factorialToString(map: Map<Long, Int>):String {
return map.map { "${it.key}${if (it.value == 1) "" else "^${it.value}" }" }.mkString("*","","")
}
fun congruence(a: Long, c: Long, m: Long, start: Long = 0L, end : Long? = null): List<Long> {
val g = gcd(a, m)
if (c.rem(g) != 0L) return listOf()
val u0 = gcdSolution(a, m, g).first
val v = m / g
var x0 = (u0 * (c/ g))
while (x0 < 0){
x0 += v
}
return ((start).until((end?:1) * g)).map { it * v + x0 }
}
// if multi > 2, end = m * n * k
fun multicongruence(b: Long, m: Long, c: Long, n:Long, end:Long? = null) : Set<Long> {
return congruence(1, b, m, end = if (end == null) n else (end/m)).intersect(congruence(1, c, n, end = if (end == null) m else (end/n)))
}
fun euler_phi(n:Long, factorial: Map<Long, Int>? = null):Long {
return (factorial?:factorialPrime(n)).keys.fold(n){acc, l -> acc / l * (l - 1L) }
}
// the sum of all the divisors of n including 1 and n
fun sigma(n:Long):Long {
return factorialPrime(n).toList().fold(1L) {
acc, pair ->
acc * sumOfGeometricSequence(pair.second.toLong(), pair.first)
}
}
fun sumOfGeometricSequence(pow: Long, increment: Long, start: Long = 1L):Long{
if (increment == 1L)
return pow * start
return start * (increment.powOf(pow + 1) - 1L) / (increment - 1L)
}
@SuppressWarnings
fun socialables(start: Long, order: Int): Set<Long>? {
var s = start
var flag = true
(1..order).fold(mutableListOf<Long>(s)){
acc, _ ->
acc.apply {
if (flag){
if(s <= 1L){
flag = false
}
else{
s = sigma(s) - s
this.add(s)
}
}
}
}.let {
if(flag && it.drop(1).indexOfFirst { x -> x == start } >= 0)
return it.toSet()
return null
}
}
fun modPow(a:Long, k:Long, m:Long): Long {
var k0 = k
var a0 = a
var res = 1L
while (k0 >= 1){
val isOdd = (k0.rem(2) == 1L)
if (isOdd)
res = (res.times(a0)).rem(m)
a0 = (a0.times(a0)).rem(m)
k0 = if (isOdd) (k0 - 1) / 2 else (k0 / 2)
}
return res
}
// if false muss be composite
fun checkLargePrime(n:Long, sampleBase: Iterable<Long>? = null):Boolean{
return (sampleBase?:((1..10).map{ Random.nextLong(2L, n-1) })).all {
modPow(it, n-1, n) == 1L
}
}
fun solveRootsMod(k: Long, b: Long, m: Long, factorial: Map<Long, Int>? = null): Long {
val phi = euler_phi(m, factorial)
return modPow(b, gcdSolution(k, phi).first.let {
var res = it
while (res <= 0) res += phi
res
}, m)
}
fun pollars_rho(n:BigInteger, x: BigInteger = 2.toBigInteger(), y:BigInteger = 2.toBigInteger(), d: BigInteger = BigInteger.ONE, f: (BigInteger) -> BigInteger = {it.powOf(2) + BigInteger.ONE}): BigInteger {
var x0 = x
var y0 = y
var d0 = d
while (d0 == BigInteger.ONE){
x0 = f(x0)
y0 = f(f(y0))
d0 = gcd(if((x0 - y0) > BigInteger.ZERO) x0 -y0 else y0 - x0 , n)
}
if (d0 == n)
throw Exception("Error")
return d0
}
fun pollars_rho(n:Long, x: Long = 2, y:Long = 2, d: Long = 1, f: (Long) -> Long = {it.powOf(2) + 1}): Long {
var x0 = x
var y0 = y
var d0 = d
while (d0 == 1L){
x0 = f(x0)
y0 = f(f(y0))
d0 = gcd(if((x0 - y0) > 0) x0 -y0 else y0 - x0 , n)
}
if (d0 == n)
throw Exception("Error")
return d0
}
}
fun Long.powOf(n:Long):Long {
if (n == 1L)
return this
if (n.rem(2L) == 0L){
val a = this.powOf(n.div(2L))
return a.times(a)
}else{
val a = this.powOf((n-1).div(2L))
return this.times(a).times(a)
}
}
fun BigInteger.powOf(n:Long):BigInteger {
if (n == 1L)
return this
if (n.rem(2L) == 0L){
val a = this.powOf(n.div(2L))
return a.times(a)
}else{
val a = this.powOf((n-1).div(2L))
return this.times(a).times(a)
}
}
fun Long.powOf(n:Int):Long{
return this.powOf(n.toLong())
} | 2 | Kotlin | 0 | 0 | dcd0ef0bad007e37a08ce5a05af52990c9d904e0 | 10,506 | aaf4k-base | MIT License |
src/main/day11/Part1.kt | ollehagner | 572,141,655 | false | {"Kotlin": 80353} | package day11
import infiniteInts
import readInput
import java.lang.IllegalArgumentException
import java.util.*
import kotlin.math.floor
fun main() {
val monkeys = parseInput(readInput("day11/testinput.txt"))
infiniteInts(1)
.take(20)
.forEach { round ->
monkeys.forEach { monkey ->
monkey.inspectAndThrow(monkeys) { value -> value / 3 }
}
}
val monkeyBusinessValue = monkeys
.map { it.inspections }
.sortedByDescending { it }
.take(2)
.reduce(Long::times)
println("Day 11 part 1. Total monkey business: $monkeyBusinessValue")
}
fun worryFunction(instructions: String): (Long) -> Long {
val operand = instructions.split(" ").last().trim()
return when {
instructions.contains("old * old") -> { value -> value * value }
instructions.contains("+") -> { value -> operand.toLong() + value }
instructions.contains("*") -> { value -> value * operand.toLong() }
else -> throw IllegalArgumentException("Unknown operator in $instructions")
}
}
fun monkeyRouter(divisor: Long, routeIfTrue: Int, routeIfFalse: Int): (Long) -> Int {
return { value -> if (value % divisor == 0L) routeIfTrue else routeIfFalse }
}
fun parseInput(input: List<String>): List<Monkey> {
return input
.map { it.trim() }
.windowed(6,7)
.map { monkeyData ->
Monkey(monkeyData)
}
}
class Monkey(input: List<String>) {
val items: Queue<Long>
val worryIncrease: (Long) -> Long
val monkeyRouter: (Long) -> Int
val modDivisor = input[3].substringAfterLast(" ").toLong()
var inspections: Long = 0
init {
items = LinkedList(input[1].substringAfter(":")
.split(",")
.map { it.trim().toLong() })
worryIncrease = worryFunction(input[2])
monkeyRouter = monkeyRouter(
modDivisor,
input[4].substringAfterLast(" ").toInt(),
input[5].substringAfterLast(" ").toInt()
)
}
fun inspectAndThrow(monkeys: List<Monkey>, worryLevelDecreaseFunction: (Long) -> Long) {
this.items.map { item ->
val worryLevel = worryIncrease.invoke(item)
inspections++
val loweredWorryItem = floor((worryLevelDecreaseFunction.invoke(worryLevel)).toDouble()).toLong()
monkeys[monkeyRouter.invoke(loweredWorryItem)].throwItem(loweredWorryItem)
}
this.items.clear()
}
fun throwItem(item: Long) {
items.add(item)
}
override fun toString(): String {
return "Monkey (items=$items). Inspections: $inspections"
}
} | 0 | Kotlin | 0 | 0 | 6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1 | 2,679 | aoc2022 | Apache License 2.0 |
src/Day08.kt | AxelUser | 572,845,434 | false | {"Kotlin": 29744} | data class Input(
val rows: Array<Array<MutableList<Int>>>,
val cols: Array<Array<MutableList<Int>>>,
val map: Array<IntArray>
)
fun main() {
fun List<String>.parse(): Input {
val rows = Array(size) { Array(10) { mutableListOf<Int>() } }
val cols = Array(this[0].length) { Array(10) { mutableListOf<Int>() } }
val map = Array(size) { IntArray(this[0].length) }
for (row in indices) {
for (col in this[row].indices) {
val num = this[row][col] - '0'
rows[row][num].add(col)
cols[col][num].add(row)
map[row][col] = num
}
}
return Input(rows, cols, map)
}
fun part1(input: Input): Int {
val (rows, cols, map) = input
var count = (map.size - 1) * 2 + (map[0].size - 1) * 2
for (row in 1 until map.lastIndex) {
for (col in 1 until map[row].lastIndex) {
val n = map[row][col]
var leftCover = false
var rightCover = false
for (coverIdx in rows[row].drop(n).flatten()) {
if (coverIdx > col) rightCover = true
if (coverIdx < col) leftCover = true
if (leftCover && rightCover) break
}
if (!leftCover || !rightCover) {
count++
continue
}
var topCover = false
var bottomCover = false
for (coverIdx in cols[col].drop(n).flatten()) {
if (coverIdx > row) bottomCover = true
if (coverIdx < row) topCover = true
if (topCover && bottomCover) break
}
if (!topCover || !bottomCover) {
count++
continue
}
}
}
return count
}
fun part2(input: Input): Int {
val (_, _, map) = input
var maxScore = 0
for (row in map.indices) {
for (col in map[row].indices) {
var seeLeft = 0
for (i in col - 1 downTo 0) {
seeLeft++
if (map[row][i] >= map[row][col]) break
}
var seeRight = 0
for (i in col + 1..map[row].lastIndex) {
seeRight++
if (map[row][i] >= map[row][col]) break
}
var seeTop = 0
for (i in row - 1 downTo 0) {
seeTop++
if (map[i][col] >= map[row][col]) break
}
var seeBottom = 0
for (i in row + 1..map.lastIndex) {
seeBottom++
if (map[i][col] >= map[row][col]) break
}
maxScore = maxOf(maxScore, seeLeft * seeRight * seeTop * seeBottom)
}
}
return maxScore
}
var input = readInput("Day08_test").parse()
check(part1(input) == 21)
check(part2(input) == 8)
input = readInput("Day08").parse()
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 042e559f80b33694afba08b8de320a7072e18c4e | 3,234 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/learn/sudoku/Sudoku.kt | asher-stern | 193,098,718 | false | null | package com.learn.sudoku
import java.io.File
typealias Board = Array<Array<Int?>> // Row first. For example, b[1][3] means second row forth column.
fun main(args: Array<String>)
{
val board = Sudoku.read(args[0])
println(Sudoku.print(board))
println((1..11).joinToString("") { "=" } )
if(!Sudoku.solve(board)) println("Unsolvable.")
}
object Sudoku
{
fun read(filename: String): Board =
File(filename).useLines { lines ->
lines.take(9).map { line -> line.map { if (it.isDigit()) it.toString().toInt() else null }.toTypedArray() }
.toList().toTypedArray()
}
fun print(board: Board): String =
board.withIndex().joinToString("\n") { (i, r) ->
val columnString = r.withIndex().joinToString("") { (ci, c) ->
(if ((ci>0)&&(0==(ci%3))) "|" else "") + (c?.toString()?:" ")
}
(if ((i>0)&&(0==(i%3))) (1..11).joinToString("", postfix = "\n") { "-" } else "") + columnString
}
fun solve(board: Board): Boolean = solve(board, 0, 0)
private fun solve(board: Board, row: Int, column: Int): Boolean
{
if (board[row][column] == null)
{
for (value in 1..9)
{
if (!violates(value, row, column, board))
{
board[row][column] = value
if ( (row == 8) && (column == 8) )
{
println(print(board))
return true
}
else
{
val (nextRow, nextColumn) = next(row, column)
if (solve(board, nextRow, nextColumn))
{
return true
}
}
board[row][column] = null
}
}
return false
}
else
{
if ( (row == 8) && (column == 8) )
{
println(print(board))
return true
}
else
{
val (nextRow, nextColumn) = next(row, column)
return solve(board, nextRow, nextColumn)
}
}
}
private fun next(row: Int, column: Int): Pair<Int, Int>
{
if (column < 8) return Pair(row, column + 1)
else return Pair(row + 1, 0)
}
private fun violates(value: Int, row: Int, column: Int, board: Board): Boolean
{
return violatesRow(value, row, column, board) ||
violatesColumn(value, row, column, board) ||
violatesSquare(value, row, column, board)
}
private fun violatesRow(value: Int, row: Int, column: Int, board: Board): Boolean =
(0 until 9).any { (it != column) && (board[row][it] == value) }
private fun violatesColumn(value: Int, row: Int, column: Int, board: Board): Boolean =
(0 until 9).any { (it != row) && (board[it][column] == value) }
private fun violatesSquare(value: Int, row: Int, column: Int, board: Board): Boolean
{
val rowBegin = (row/3)*3
val columnBegin = (column/3)*3
for (r in rowBegin until (rowBegin+3))
{
for (c in columnBegin until (columnBegin+3))
{
if ( (r != row) && (c != column) )
{
if (board[r][c] == value)
{
return true
}
}
}
}
return false
}
} | 0 | Kotlin | 0 | 0 | 73ee63a2dcb749a72e3f6e01a21b62974b2dd24e | 3,647 | sudoku | MIT License |
src/day17/Code.kt | fcolasuonno | 225,219,560 | false | null | package day17
import IntCode
import IntCodeComputer
import isDebug
import java.io.File
private fun Pair<Int, Int>.neighbours() = listOf(
copy(first = first - 1),
copy(first = first + 1),
copy(second = second - 1),
copy(second = second + 1)
)
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2(parsed)}")
}
fun parse(input: List<String>) = input.map {
it.split(",").map { it.toLong() }
}.requireNoNulls().single()
fun part1(input: List<Long>) = mutableListOf<Long>().apply {
IntCodeComputer(input, null, IntCode.Output { a -> add(a) }).run()
}.map { it.toChar() }.joinToString("").split("\n")
.withIndex().flatMap { (j, s) ->
s.withIndex().mapNotNull { (i, c) -> (i to j).takeIf { c != '.' } }
}.toSet()
.run {
filter { it.neighbours().all { it in this } }.sumBy { it.first * it.second }
}
data class Robot(val position: Pair<Int, Int>, val direction: Direction, val step: Int, val turn: Direction) {
private operator fun Pair<Int, Int>.plus(dir: Direction) = copy(first = first + dir.dx, second = second + dir.dy)
fun straight(map: Set<Pair<Int, Int>>) =
(position + direction).takeIf { it in map }?.let { copy(position = it, step = step + 1) }
fun left(map: Set<Pair<Int, Int>>) = when (direction) {
Direction.U -> Direction.L
Direction.D -> Direction.R
Direction.L -> Direction.D
Direction.R -> Direction.U
}.let { Pair(it, position + it) }.takeIf { it.second in map }?.let {
copy(
position = it.second,
direction = it.first,
step = 1,
turn = Direction.L
)
}
fun right(map: Set<Pair<Int, Int>>) = when (direction) {
Direction.U -> Direction.R
Direction.D -> Direction.L
Direction.L -> Direction.U
Direction.R -> Direction.D
}.let { Pair(it, position + it) }.takeIf { it.second in map }?.let {
copy(
position = it.second,
direction = it.first,
step = 1,
turn = Direction.R
)
}
override fun toString() = "$turn,$step"
}
enum class Direction(val dx: Int, val dy: Int) {
U(0, -1),
D(0, 1),
L(-1, 0),
R(1, 0);
}
fun part2(codeInput: List<Long>): Any? {
val output = mutableListOf<Long>()
val input = mutableListOf<Long>()
val computer = IntCodeComputer(codeInput, IntCode.Input {
input.removeAt(0)
}, IntCode.Output { a ->
output.add(a)
}).apply {
mem[0] = 2L
}
computer.runWhile { peekOp is IntCode.Input }
val (map, initialRobot) = output.map { it.toChar() }.joinToString("").split("\n")
.withIndex().flatMap { (j, s) -> s.mapIndexed { i, c -> (i to j) to c } }.let {
it.filter { it.second != '.' }.map { it.first }.toSet() to it.single { it.second == '^' }.first
}
val fullDirections = generateSequence(Robot(initialRobot, Direction.L, 0, Direction.L)) { robot ->
robot.straight(map) ?: robot.left(map) ?: robot.right(map)
}.let { it.zipWithNext().filter { it.second.direction != it.first.direction }.map { it.first } + it.last() }
.joinToString(",", postfix = ",")
val compressedDirection =
(21 downTo 2).flatMap { a -> (21 downTo 2).flatMap { b -> (21 downTo 2).map { c -> Triple(a, b, c) } } }
.first { (a, b, c) ->
val aMovement = fullDirections.take(a)
val aReplaced = fullDirections.replace(aMovement, "")
val bMovement = aReplaced.take(b)
val bReplaced = aReplaced.replace(bMovement, "")
bReplaced.replace(bReplaced.take(c), "").isEmpty()
}.let { (a, b, c) ->
val aMovement = fullDirections.take(a)
val aReplaced = fullDirections.replace(aMovement, "")
val bMovement = aReplaced.take(b)
val bReplaced = aReplaced.replace(bMovement, "")
val cMovement = bReplaced.take(c)
listOf(
fullDirections.replace(aMovement, "A,").replace(bMovement, "B,").replace(cMovement, "C,"),
aMovement,
bMovement,
cMovement
).joinToString("\n", postfix = "\nn\n") { it.dropLast(1) }
}
input.addAll(compressedDirection.map { it.toLong() })
computer.run()
return output.last()
}
| 0 | Kotlin | 0 | 0 | d1a5bfbbc85716d0a331792b59cdd75389cf379f | 4,673 | AOC2019 | MIT License |
src/main/kotlin/tr/emreone/adventofcode/days/Day09.kt | EmRe-One | 433,772,813 | false | {"Kotlin": 118159} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import tr.emreone.kotlin_utils.math.Coords
class Day09 : Day(9, 2021, "Smoke Basin") {
class Grid(var input: List<String>) {
private val grid = mutableMapOf<Coords, Int>()
private val width = input.first().length
private val length = input.size
init {
input.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
grid[Pair(x, y)] = c.digitToInt()
}
}
}
fun getLowPoints(): List<Pair<Coords, Int>> {
return this.grid.toList().filter { pair ->
var minValueInNeighborhood = 10
val coords = pair.first
if (coords.second > 0) { // not top edge
minValueInNeighborhood = minOf(minValueInNeighborhood, grid[coords.first to (coords.second - 1)]!!)
}
if (coords.first < width - 1) { // not right edge
minValueInNeighborhood = minOf(minValueInNeighborhood, grid[(coords.first + 1) to coords.second]!!)
}
if (coords.second < length - 1) { // not bottom edge
minValueInNeighborhood = minOf(minValueInNeighborhood, grid[coords.first to (coords.second + 1)]!!)
}
if (coords.first > 0) { // not left edge
minValueInNeighborhood = minOf(minValueInNeighborhood, grid[(coords.first - 1) to coords.second]!!)
}
pair.second < minValueInNeighborhood
}
}
private fun addNeighborsToSet(current: Pair<Coords, Int>, coords: MutableSet<Coords>) {
val x = current.first.first
val y = current.first.second
val height = current.second
if (height > 8) {
return
} else {
coords.add(current.first)
}
// not top edge
if (y > 0 && grid[x to (y - 1)]!! > height) {
val topNeighbor = (x to (y - 1)) to grid[x to (y - 1)]!!
addNeighborsToSet(topNeighbor, coords)
}
// not right edge
if (x < width - 1 && grid[(x + 1) to y]!! > height) {
val rightNeighbor = (x + 1 to y) to grid[(x + 1) to y]!!
addNeighborsToSet(rightNeighbor, coords)
}
// not bottom edge
if (y < length - 1 && grid[x to (y + 1)]!! > height) {
val bottomNeighbor = (x to (y + 1)) to grid[x to (y + 1)]!!
addNeighborsToSet(bottomNeighbor, coords)
}
// not left edge
if (x > 0 && grid[(x - 1) to y]!! > height) {
val leftNeighbor = ((x - 1) to y) to grid[(x - 1) to y]!!
addNeighborsToSet(leftNeighbor, coords)
}
}
fun getBasins(): List<Set<Coords>> {
val basins = mutableListOf<Set<Coords>>()
getLowPoints().forEach {
val coords = mutableSetOf<Coords>()
addNeighborsToSet(it, coords)
basins.add(coords)
}
return basins
}
}
override fun part1(): Int {
val grid = Grid(inputAsList)
return grid.getLowPoints().sumOf {
it.second + 1
}
}
override fun part2(): Int {
val grid = Grid(inputAsList)
val basins = grid.getBasins()
val sortedBasins = basins.sortedByDescending {
it.size
}
return sortedBasins[0].size * sortedBasins[1].size * sortedBasins[2].size
}
}
| 0 | Kotlin | 0 | 0 | 516718bd31fbf00693752c1eabdfcf3fe2ce903c | 3,715 | advent-of-code-2021 | Apache License 2.0 |
src/day11/Day11.kt | ZsemberiDaniel | 159,921,870 | false | null | package day11
import RunnablePuzzleSolver
import java.lang.Integer.min
class Day11 : RunnablePuzzleSolver {
val gridSerialNumber = 7347
val cells = Array(301) { Array(301) { 0 } }
val cellSums = Array(301) { Array(301) { 0 } }
override fun readInput1(lines: Array<String>) { }
override fun readInput2(lines: Array<String>) { }
override fun solvePart1(): String {
for (y in 1 until cells.size) {
for (x in 1 until cells[y].size) {
// Find the fuel cell's rack ID, which is its X coordinate plus 10
val rackId = x + 10
// Begin with a power level of the rack ID times the Y coordinate
var powerLevel = rackId * y
// Increase the power level by the value of the grid serial number (your puzzle input)
powerLevel += gridSerialNumber
// Set the power level to itself multiplied by the rack ID
powerLevel *= rackId
// Keep only the hundreds digit of the power level
powerLevel %= 1000
powerLevel -= powerLevel % 100
powerLevel /= 100
// Subtract 5 from the power level
powerLevel -= 5
cells[y][x] = powerLevel
// calculate the sums till this cell
cellSums[y][x] = cells[y][x] + cellSums[y - 1][x] + cellSums[y][x - 1] - cellSums[y - 1][x - 1]
}
}
var whereMax = Pair(0, 0)
var max = Int.MIN_VALUE
for (y in 1 until cells.size - 2) {
for (x in 1 until cells.size - 2) {
val sum = cellSums[y + 2][x + 2] - cellSums[y - 1][x + 2] - cellSums[y + 2][x - 1] + cellSums[y - 1][x - 1]
if (max < sum) {
max = sum
whereMax = Pair(x, y)
}
}
}
return whereMax.toString()
}
override fun solvePart2(): String {
var max = Int.MIN_VALUE
var solution = Triple(0, 0, 0)
for (y in 1 until cells.size) {
for (x in 1 until cells[y].size) {
val maxSize = min(cells.size - y, cells[y].size - x)
for (size in 0 until maxSize) {
val sum = cellSums[y + size][x + size] - cellSums[y - 1][x + size] - cellSums[y + size][x - 1] + cellSums[y - 1][x - 1]
if (max < sum) {
max = sum
solution = Triple(x, y, size + 1)
}
}
}
}
return solution.toString()
}
}
| 0 | Kotlin | 0 | 0 | bf34b93aff7f2561f25fa6bd60b7c2c2356b16ed | 2,660 | adventOfCode2018 | MIT License |
src/main/kotlin/07/07.kt | Wrent | 225,133,563 | false | null | import java.lang.IllegalStateException
import java.math.BigInteger
import java.util.*
fun main() {
var permutations = getPermutations(listOf(0L, 1L, 2L, 3L, 4L).map { it.toBigInteger() }.toTypedArray())
var max = BigInteger.ZERO
permutations.forEach {
val res = evaluateAmplifier(it[0], evaluateAmplifier(it[1], evaluateAmplifier(it[2], evaluateAmplifier(it[3], evaluateAmplifier(it[4], BigInteger.ZERO)))))
if (res > max) max = res
}
println(max)
println("second part")
permutations = getPermutations(listOf(5L, 6L, 7L, 8L, 9L).map { it.toBigInteger() }.toTypedArray())
max = BigInteger.ZERO
permutations.forEach {
val res = evaluatePermutation(it, INPUT7)
if (res > max) max = res
}
println(max)
}
fun evaluatePermutation(it: Array<BigInteger>, input: String): BigInteger {
val amplifierE = Amplifier(getData(input), BigInteger.ZERO, null)
val amplifierD = Amplifier(getData(input), BigInteger.ZERO, amplifierE)
val amplifierC = Amplifier(getData(input), BigInteger.ZERO, amplifierD)
val amplifierB = Amplifier(getData(input), BigInteger.ZERO, amplifierC)
val amplifierA = Amplifier(getData(input), BigInteger.ZERO, amplifierB)
amplifierE.next = amplifierA
amplifierA.queue.add(it[0])
amplifierA.queue.add(BigInteger.ZERO)
amplifierB.queue.add(it[1])
amplifierC.queue.add(it[2])
amplifierD.queue.add(it[3])
amplifierE.queue.add(it[4])
var current = amplifierA
while (true) {
try {
val instr = parseInstr(current.index, current.data, { current.queue.poll() }, { output ->
current.next?.queue?.add(output)
current.lastOutput = output
})
current.index = instr.apply(current.data, current.index)
} catch (ex: IllegalStateException) {
current = current.next!!
} catch (ex: HaltException) {
println("amplifier stopped")
current.isStopped = true
val tmp = current
while (current.isStopped) {
current = current.next!!
if (current == tmp) {
break
}
}
if (current.isStopped) {
break
}
}
}
val res = amplifierE.lastOutput
return res
}
class Amplifier(val data: MutableMap<BigInteger, BigInteger>, var index: BigInteger, var next: Amplifier?) {
val queue: Queue<BigInteger> = LinkedList()
var lastOutput = BigInteger.ZERO
var isStopped = false
}
fun getPermutations(input: Array<BigInteger>): List<Array<BigInteger>> {
val indexes = LongArray(input.size)
for (i in 0 until input.size) {
indexes[i] = 0
}
var current = input.clone()
val result = mutableListOf<Array<BigInteger>>()
result.add(current)
var i = 0
while (i < input.size) {
if (indexes[i] < i) {
swap(current, if (i % 2 == 0) 0 else indexes[i].toInt(), i)
result.add(current.clone())
indexes[i]++
i = 0
} else {
indexes[i] = 0
i++
}
}
return result
}
fun swap(input: Array<BigInteger>, a: Int, b: Int) {
val tmp: BigInteger = input[a]
input[a] = input[b]
input[b] = tmp
}
fun evaluateAmplifier(a: BigInteger, b: BigInteger): BigInteger {
val data = getData(INPUT7)
var index = 0L.toBigInteger()
var inputCallCnt = 0
try {
while (true) {
val instr = parseInstr(index, data, { if (inputCallCnt++ == 0) a else b }, {})
index = instr.apply(data, index)
}
} catch (ex: RuntimeException) {
return output
}
}
fun getData(input: String): MutableMap<BigInteger, BigInteger> {
val data = mutableMapOf<BigInteger, BigInteger>()
input.split(",").map { it.toBigInteger() }.toMutableList().forEachIndexed { index, i -> data[index.toBigInteger()] = i }
return data
}
const val INPUT7 =
"3,8,1001,8,10,8,105,1,0,0,21,46,67,76,97,118,199,280,361,442,99999,3,9,1002,9,3,9,101,4,9,9,102,3,9,9,1001,9,3,9,1002,9,2,9,4,9,99,3,9,102,2,9,9,101,5,9,9,1002,9,2,9,101,2,9,9,4,9,99,3,9,101,4,9,9,4,9,99,3,9,1001,9,4,9,102,2,9,9,1001,9,4,9,1002,9,5,9,4,9,99,3,9,102,3,9,9,1001,9,2,9,1002,9,3,9,1001,9,3,9,4,9,99,3,9,101,1,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1001,9,1,9,4,9,3,9,1001,9,1,9,4,9,3,9,101,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,1001,9,2,9,4,9,3,9,101,1,9,9,4,9,99,3,9,102,2,9,9,4,9,3,9,101,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1001,9,1,9,4,9,3,9,102,2,9,9,4,9,3,9,101,1,9,9,4,9,3,9,101,2,9,9,4,9,99,3,9,1002,9,2,9,4,9,3,9,1001,9,1,9,4,9,3,9,101,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,1,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,1,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,1001,9,1,9,4,9,99,3,9,1001,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,2,9,9,4,9,3,9,1001,9,1,9,4,9,3,9,101,1,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1001,9,1,9,4,9,3,9,1002,9,2,9,4,9,3,9,1001,9,1,9,4,9,99,3,9,1002,9,2,9,4,9,3,9,101,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,101,1,9,9,4,9,3,9,102,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1002,9,2,9,4,9,99" | 0 | Kotlin | 0 | 0 | 0a783ed8b137c31cd0ce2e56e451c6777465af5d | 5,279 | advent-of-code-2019 | MIT License |
src/Day04.kt | sd2000usr | 573,123,353 | false | {"Kotlin": 21846} |
fun main()
{
fun part1(input: List<String>)
{
var overlappingCount = 0
input.forEach ()
{ line ->
println("line: $line")
val split = line.split(',')
val (elfWithRange0Raw, elfWithRange1Raw) = split
val elfRangeSplit0 = elfWithRange0Raw.split('-')
val elfRangeSplit1 = elfWithRange1Raw.split('-')
val elf0Range = IntRange(elfRangeSplit0[0].toInt(), elfRangeSplit0[1].toInt())
val elf1Range = IntRange(elfRangeSplit1[0].toInt(), elfRangeSplit1[1].toInt())
println("[elf 0] range: $elf0Range")
println("[elf 1] range: $elf1Range")
val isOverlapping =
elf0Range.first >= elf1Range.first && elf0Range.last <= elf1Range.last ||
elf1Range.first >= elf0Range.first && elf1Range.last <= elf0Range.last
println("[overlapping] $isOverlapping")
println()
if (isOverlapping)
overlappingCount++
}
println("overlappingCount count: $overlappingCount")
}
fun part2(input: List<String>)
{
var overlappingCount = 0
input.forEach ()
{ line ->
println("line: $line")
val split = line.split(',')
val (elfWithRange0Raw, elfWithRange1Raw) = split
val elfRangeSplit0 = elfWithRange0Raw.split('-')
val elfRangeSplit1 = elfWithRange1Raw.split('-')
val elf0Range = IntRange(elfRangeSplit0[0].toInt(), elfRangeSplit0[1].toInt())
val elf1Range = IntRange(elfRangeSplit1[0].toInt(), elfRangeSplit1[1].toInt())
println("[elf 0] range: $elf0Range")
println("[elf 1] range: $elf1Range")
/*val isOverlapping =
elf0Range.first >= elf1Range.first && elf0Range.last <= elf1Range.last ||
elf1Range.first >= elf0Range.first && elf1Range.last <= elf0Range.last
println("[overlapping] $isOverlapping")
println()
if (isOverlapping)
overlappingCount++*/
val overlappingRangeStart =
if (elf0Range.first >= elf1Range.first)
elf0Range.first
else
elf1Range.first
val overlappingRangeEnd =
if (elf0Range.last <= elf1Range.last)
elf0Range.last
else
elf1Range.last
println("overlappingRange: $overlappingRangeStart..$overlappingRangeEnd")
if (overlappingRangeStart <= overlappingRangeEnd)
{
val overlappingSize = overlappingRangeEnd - overlappingRangeStart + 1
//overlappingCount += overlappingSize
overlappingCount ++
println("[overlapping] size: $overlappingSize")
}
else
println("[not overlapping]")
println()
}
println("overlappingCount count: $overlappingCount")
}
val input = readInput("Day04")
//val input = readInput("testDay04")
//part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | fe5307af5dd8620ae8dee0ad5244466b5332e535 | 3,223 | cfgtvsizedxr8jubhy | Apache License 2.0 |
kotlin/2021/round-1c/roaring-years/src/main/kotlin/Solution.kt | ShreckYe | 345,946,821 | false | null | /*
import kotlin.math.floor
import kotlin.math.log10
fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val y = readLine()!!
val ansY = ans(y)
println("Case #${ti + 1}: $ansY")
}
fun ans(y: String): Long {
val yLong = y.toLong()
return (1..y.length / 2).flatMap {
val start = y.take(it).toLong()
val yLength = y.length
val min10PowGtStart = min10PowGt(yLong)
(listOfNotNull(
roaring(start, yLength)?.takeIf { it.toLong() > yLong },
roaring(start + 1, yLength)
) +
listOfNotNull(
roaring(min10PowGt(yLong), yLength + 1)
)).map { it.toLong() }
}.minOrNull()!!
}
*/
/*fun min10PowGt(n: Long) =
10L powInt (floor(log10(n.toDouble())).toInt() + 1)*//*
fun roaring(start: Long, length: Int): String? =
possibleRoaring(start, length)?.run { if (second >= 2) first else null }
fun possibleRoaring(start: Long, length: Int): Pair<String, Int>? =
if (length == 0) "" to 0
else {
val startS = start.toString()
val startLength = startS.length
if (startLength > length)
null
else possibleRoaring(start + 1, length - startLength)?.run {
startS + first to second + 1
}
}
fun Long.squared(): Long =
this * this
infix fun Long.powInt(that: Int): Long =
when {
that == 0 -> 1L
that > 0 -> powInt(that / 2).squared()
.let { if (that % 2 == 0) it else it * this }
else -> throw IllegalArgumentException("exponent less than 0")
}
*/
| 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 1,645 | google-code-jam | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ThreeSum.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
/**
* 3 Sum.
* @see <a href="https://leetcode.com/problems/3sum/">Source</a>
*/
fun interface ThreeSum {
operator fun invoke(nums: IntArray): List<List<Int>>
}
/**
* Approach 1: Two Pointers.
* Time Complexity: O(n^2).
* Space Complexity: O(n^2).
*/
class ThreeSumTwoPointers : ThreeSum {
override operator fun invoke(nums: IntArray): List<List<Int>> {
nums.sort()
val res: MutableList<List<Int>> = ArrayList<List<Int>>()
var i = 0
while (i < nums.size && nums[i] <= 0) {
if (i == 0 || nums[i - 1] != nums[i]) {
twoSumII(nums, i, res)
}
++i
}
return res
}
private fun twoSumII(nums: IntArray, i: Int, res: MutableList<List<Int>>) {
var lo = i + 1
var hi = nums.size - 1
while (lo < hi) {
val sum = nums[i] + nums[lo] + nums[hi]
when {
sum < 0 -> {
++lo
}
sum > 0 -> {
--hi
}
else -> {
res.add(listOf(nums[i], nums[lo++], nums[hi--]))
while (lo < hi && nums[lo] == nums[lo - 1]) ++lo
}
}
}
}
}
/**
* Approach 2: Hashset.
* Time Complexity: O(n^2).
* Space Complexity: O(n^2).
*/
class ThreeSumHashset : ThreeSum {
override operator fun invoke(nums: IntArray): List<List<Int>> {
nums.sort()
val res: MutableList<List<Int>> = ArrayList<List<Int>>()
var i = 0
while (i < nums.size && nums[i] <= 0) {
if (i == 0 || nums[i - 1] != nums[i]) {
twoSum(nums, i, res)
}
++i
}
return res
}
private fun twoSum(nums: IntArray, i: Int, res: MutableList<List<Int>>) {
val seen = HashSet<Int>()
var j = i + 1
while (j < nums.size) {
val complement = -nums[i] - nums[j]
if (seen.contains(complement)) {
res.add(listOf(nums[i], nums[j], complement))
while (j + 1 < nums.size && nums[j] == nums[j + 1]) ++j
}
seen.add(nums[j])
++j
}
}
}
/**
* Approach 3: "No-Sort".
* Time Complexity: O(n^2).
* Space Complexity: O(n).
*/
class ThreeSumNoSort : ThreeSum {
override operator fun invoke(nums: IntArray): List<List<Int>> {
val res: MutableSet<List<Int>> = HashSet()
val dups: MutableSet<Int> = HashSet()
val seen: MutableMap<Int, Int> = HashMap()
for (i in nums.indices) if (dups.add(nums[i])) {
for (j in i + 1 until nums.size) {
val complement = -nums[i] - nums[j]
if (seen.containsKey(complement) && seen[complement] == i) {
val triplet: MutableList<Int> = mutableListOf(nums[i], nums[j], complement)
triplet.sort()
res.add(triplet)
}
seen[nums[j]] = i
}
}
return ArrayList(res)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,735 | kotlab | Apache License 2.0 |
src/Day03.kt | D000L | 575,350,411 | false | {"Kotlin": 23716} | fun main() {
fun part1(input: List<String>): Int {
return input.map {
val halfSize = it.length / 2
val wordA = it.subSequence(0,halfSize)
val wordB = it.subSequence(halfSize,it.length)
wordA.toSet().intersect(wordB.toSet()).first()
}.sumOf {
it.code - if (it.isLowerCase())96 else 38
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).map {
val (a, b, c) = it
a.toSet().intersect(b.toSet()).intersect(c.toSet()).first()
}.sumOf {
it.code - if (it.isLowerCase()) 96 else 38
}
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b733a4f16ebc7b71af5b08b947ae46afb62df05e | 745 | adventOfCode | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec03.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2020
import org.elwaxoro.advent.PuzzleDayTester
class Dec03 : PuzzleDayTester(3, 2020) {
override fun part1(): Any = countTrees(parseInput(), 3, 1)
override fun part2(): Any = DOTHEDEW(parseInput())
private fun DOTHEDEW(rows: List<List<Int>>) =
listOf(
1 to 1,
3 to 1,
5 to 1,
7 to 1,
1 to 2
).map { countTrees(rows, it.first, it.second) }
.reduce { total, row -> total * row }
private fun countTrees(rows: List<List<Int>>, colStep: Int, rowStep: Int): Long =
rows.filterIndexed { index, _ -> index % rowStep == 0 }
.fold(0 to 0L) { thingy, row ->
thingy.first + colStep to thingy.second + row[thingy.first % row.size]
}.second
private fun parseInput(): List<List<Int>> = load().map { row ->
row.trim().toCharArray().map {
if (it == '#')
1
else
0
}
}
private fun countTreesLoop(rows: List<List<Int>>, colStep: Int, rowStep: Int): Long {
// god i forgot how many variables you have to use with a for loop wtf
var col = 0
var counter = 0L
for (i in rows.indices step rowStep) {
val row = rows[i]
counter += row[col % row.size]
col += colStep
}
return counter
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 1,422 | advent-of-code | MIT License |
src/Day04.kt | A55enz10 | 573,364,112 | false | {"Kotlin": 15119} | fun main() {
fun part1(input: List<String>): Int {
return input.map {it.split(",","-")}
.map{elem -> elem.map{it.toInt()}}
.filter {elvesRange -> (elvesRange[0] >= elvesRange[2] && elvesRange[1] <= elvesRange[3])
|| (elvesRange[0] <= elvesRange[2] && elvesRange[1] >= elvesRange[3])}
.size
}
fun part2(input: List<String>): Int {
return input.map {it.split(",","-")}
.map{elem -> elem.map{it.toInt()}}
.filter {elvesRange -> ((elvesRange[0] <= elvesRange[2] && elvesRange[1] >= elvesRange[2])
|| (elvesRange[0] >= elvesRange[2] && elvesRange[0] <= elvesRange[3])
|| (elvesRange[0] >= elvesRange[2] && elvesRange[1] <= elvesRange[3])
|| (elvesRange[0] <= elvesRange[2] && elvesRange[1] >= elvesRange[3]))
}
.size
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 8627efc194d281a0e9c328eb6e0b5f401b759c6c | 1,001 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2021/Day2.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day2: AdventDay(2021, 2) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day2()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun parseInstructionsPart1(line: String): Submarine {
val (direction, amount) = line.split(" ")
return when(direction) {
"forward" -> Submarine(x = amount.toInt(), depth = 0)
"up" -> Submarine(x = 0, depth = -amount.toInt())
"down" -> Submarine(x = 0, depth = amount.toInt())
else -> Submarine(0, 0)
}
}
fun parseInstructionPart2(line: String): Instruction {
val (direction, amount) = line.split(" ")
return when(direction) {
"forward" -> Instruction(Direction.FORWARD, amount.toInt())
"up" -> Instruction(Direction.UP, amount.toInt())
"down" -> Instruction(Direction.DOWN, amount.toInt())
else -> Instruction(Direction.FORWARD, 0)
}
}
fun parseInstructions(lines: List<String>): List<Submarine> {
return lines.map { parseInstructionsPart1(it) }
}
fun parseInstructionsPart2(lines: List<String>): List<Instruction> {
return lines.map { parseInstructionPart2(it) }
}
fun drive(startPos: Submarine, instructions: List<Submarine>): Submarine {
return instructions.fold(startPos) { sub, next ->
sub + next
}
}
fun drivePart2(startPos: Submarine, instructions: List<Instruction>): Submarine {
return instructions.fold(startPos) { sub, next ->
when(next.direction) {
Direction.UP -> sub.copy(aim = sub.aim - next.amount)
Direction.DOWN -> sub.copy(aim = sub.aim + next.amount)
Direction.FORWARD -> sub.copy(x = sub.x + next.amount, depth = sub.depth + (next.amount * sub.aim))
}
}
}
val instructions: List<Submarine> = parseInstructions(inputAsLines)
fun part1(): Int {
return drive(Submarine(0, 0), instructions).product
}
fun part2(): Int {
return drivePart2(Submarine(0, 0), parseInstructionsPart2(inputAsLines)).product
}
enum class Direction {
UP,
DOWN,
FORWARD
}
data class Instruction(val direction: Direction, val amount: Int)
data class Submarine(val x: Int, val depth: Int, val aim: Int = 0) {
val product = x*depth
}
operator fun Submarine.plus(other: Submarine) = Submarine(x = x + other.x, depth = depth + other.depth)
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,749 | adventofcode | MIT License |
src/Day15.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | import kotlin.math.abs
fun main() {
fun log(message: Any?) {
println(message)
}
data class Vec2(val x: Int, val y: Int)
data class Node(val c: Char, val beacon: Vec2? = null, val manhattan: Int? = null)
class Grid(val grid: MutableMap<Vec2, Node>, val rangeX: Pair<Int, Int>, val rangeY: Pair<Int, Int>)
// generate the positions 1 step outside the manhattan distance
fun generateOutsideDiamond(x: Int, y: Int, distance: Int, scanMax: Int): List<Vec2> {
// paint in a diamond around the S
return buildList {
(0..distance).forEach { i ->
add(Vec2(x + i, y - (1 + distance - i)))
add(Vec2(x - i, y + (1 + distance - i)))
add(Vec2(x - distance - 1 + i, y - i))
add(Vec2(x + distance + 1 - i, y + i))
}
}.filter { it.x in (0..scanMax) && it.y in (0..scanMax)} // wasteful adding and removing <shrug>
}
// Sensor at x=2, y=18: closest beacon is at x=-2, y=15
fun parse(input: List<String>): Grid {
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
var minY = Int.MAX_VALUE
var maxY = Int.MIN_VALUE
val signedIntRegex="""-?\d+""".toRegex()
val grid = buildMap<Vec2, Node> {
input.forEachIndexed() { i, line ->
val (sX, sY, bX, bY)=signedIntRegex.findAll(line).map { it.value.toInt() }.toList()
minX = minOf(minX, sX, bX)
maxX = maxOf(maxX, sX, bX)
minY = minOf(minY, sY, bY)
maxY = maxOf(maxY, sY, bY)
this[Vec2(bX, bY)] = Node('B')
val manhattanDistance = abs(sX - bX) + abs(sY - bY)
this[Vec2(sX, sY)] = Node('S', beacon = Vec2(bX, bY), manhattan = manhattanDistance)
}
}
return Grid(grid.toMutableMap(), Pair(minX, maxX), Pair(minY, maxY))
}
fun printGrid(grid: Grid, expand: Int = 0, filter: (Node) -> Boolean = { true }) {
for (y in (grid.rangeY.first - expand)..(grid.rangeY.second + expand)) {
print("${"%3d".format(y) } ")
for(x in (grid.rangeX.first - expand)..(grid.rangeX.second + expand)) {
val node = grid.grid.getOrDefault(Vec2(x, y), Node('.'))
if (filter(node)) print(node.c) else print('.')
}
println()
}
}
fun markScanned(grid: Grid, x: Int, y: Int) {
val node: Node? = grid.grid[Vec2(x, y)]
if (node == null) {
grid.grid[Vec2(x, y)] = Node('#')
}
}
fun markTargetRow(grid: Grid, targetY: Int) {
grid.grid.filter { it.value.c == 'S' }.forEach { sensor ->
val beacon = sensor.value.beacon!!
val (sX, sY, bX, bY) = listOf(sensor.key.x, sensor.key.y, beacon.x, beacon.y)
val manhattan = abs(sX - bX) + abs(sY - bY)
val verticalDistance = abs(sY - targetY)
val affects = manhattan - verticalDistance + 1
// log("S $sX,$sY B $bX,$bY -> scan $scan -> vert $vert affects $affects")
if (affects > 0) {
for (i in 0 until affects) {
markScanned(grid,sX + i, targetY)
markScanned(grid,sX - i, targetY)
}
}
}
}
fun part1(input: List<String>, targetY: Int): Int {
val grid = parse(input)
log("part1 >>> grid X -> ${grid.rangeX} Y -> ${grid.rangeY}")
markTargetRow(grid, targetY)
// printGrid(grid, expand = 2) // print every node
return grid.grid.filter { it.key.y == targetY }.filter { it.value.c in listOf('#') }.count()
}
fun part2(input: List<String>, scanMax: Int): Long {
val grid = parse(input)
val sensors = grid.grid.filter { it.value.c == 'S' }
val fenceNodes = buildSet<Vec2> {
sensors.forEach { sensor ->
addAll(generateOutsideDiamond(sensor.key.x, sensor.key.y, sensor.value.manhattan!!, scanMax))
}
}
log("part2 >>> sensors ${sensors.size} fenceNodes ${fenceNodes.size}")
// for each fence node, check the manhattan distance to each node
fenceNodes.forEach loopFence@{ here ->
sensors.forEach { sensor ->
val manhattanSensorToHere = abs(here.x - sensor.key.x) + abs(here.y - sensor.key.y)
if (sensor.value.manhattan!! >= manhattanSensorToHere) {
return@loopFence
}
}
// if we get here, we found an XY location that is not touched by any sensor
val result = (4_000_000L * here.x) + here.y
log("part2 >>> result $result (${here.x}, ${here.y})")
return result
}
return -1 // didn't find anything, shouldn't happen!
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test.txt")
val test1 = part1(testInput, targetY = 10)
check(test1 == 26)
val test2 = part2(testInput, scanMax = 20)
check(test2 == 56_000_011L)
// game inputs part1
val input = readInput("Day15.txt")
val result1 = part1(input, targetY = 2_000_000)
println(result1)
check(result1 == 4_879_972)
// game inputs part2
val result2 = part2(input, scanMax = 4_000_000)
println(result2)
check(result2 == 12_525_726_647_448L)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 5,452 | aoc2022 | Apache License 2.0 |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day19Test.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
import kotlin.math.ceil
import kotlin.math.max
private fun solution1(input: String) = parseBlueprints(input)
.sumOf { it.id * maxGeodes(it, 24) }
private fun solution2(input: String) = parseBlueprints(input).take(3)
.map { maxGeodes(it, 32) }
.reduce(Int::times)
private fun maxGeodes(blueprint: Blueprint, minutes: Int): Int {
val queue = ArrayDeque<State>().apply { add(State(blueprint, minutes)) }
var maxGeodes = 0
while (queue.isNotEmpty()) {
val first = queue.removeFirst()
val minutesRemaining = minutes - first.minutesElapsed
if (first.maxPotentialGeodes(minutesRemaining) > maxGeodes)
queue.addAll(first.subStates)
maxGeodes = max(maxGeodes, first.geodesAt(minutes))
}
return maxGeodes
}
private fun parseBlueprints(input: String) = input.lineSequence()
.map {
"\\d+".toRegex().findAll(it).map { c -> c.value.toInt() }.toList().let { tokens ->
Blueprint(
tokens[0],
Resources(ore = tokens[1]),
Resources(ore = tokens[2]),
Resources(ore = tokens[3], clay = tokens[4]),
Resources(ore = tokens[5], obsidian = tokens[6])
)
}
}.toList()
private data class State(
val blueprint: Blueprint,
val maxElapsed: Int,
val resources: Resources = Resources(),
val minutesElapsed: Int = 0,
val oreRobots: Int = 1,
val clayRobots: Int = 0,
val obsidianRobots: Int = 0,
val geodeRobots: Int = 0,
val geodesCracked: Int = 0
) {
private val maxOreCost = maxOf(
blueprint.oreRobot.ore, blueprint.clayRobot.ore, blueprint.obsidianRobot.ore, blueprint.geodeRobot.ore
)
private val maxClayCost = blueprint.obsidianRobot.clay
private val maxObsCost = blueprint.geodeRobot.obsidian
val subStates: Sequence<State>
get() = sequence {
if (oreRobots < maxOreCost) yield(buyOreRobot())
if (clayRobots < maxClayCost) yield(buyClayRobot())
if (clayRobots > 0 && obsidianRobots < maxObsCost) yield(buyObsidianRobot())
if (obsidianRobots > 0) yield(buyGeodeRobot())
}.filter { it.minutesElapsed <= maxElapsed }
private fun buyOreRobot() = (minutesUntil(blueprint.oreRobot) + 1).let { minutes ->
copy(
minutesElapsed = minutesElapsed + minutes,
resources = resourcesAfter(minutes) - blueprint.oreRobot,
oreRobots = oreRobots + 1,
geodesCracked = geodesAfter(minutes),
)
}
private fun buyClayRobot() = (minutesUntil(blueprint.clayRobot) + 1).let { minutes ->
copy(
minutesElapsed = minutesElapsed + minutes,
resources = resourcesAfter(minutes) - blueprint.clayRobot,
clayRobots = clayRobots + 1,
geodesCracked = geodesAfter(minutes),
)
}
private fun buyObsidianRobot() = (minutesUntil(blueprint.obsidianRobot) + 1).let { minutes ->
copy(
minutesElapsed = minutesElapsed + minutes,
resources = resourcesAfter(minutes) - blueprint.obsidianRobot,
obsidianRobots = obsidianRobots + 1,
geodesCracked = geodesAfter(minutes),
)
}
private fun buyGeodeRobot() = (minutesUntil(blueprint.geodeRobot) + 1).let { minutes ->
copy(
minutesElapsed = minutesElapsed + minutes,
resources = resourcesAfter(minutes) - blueprint.geodeRobot,
geodeRobots = geodeRobots + 1,
geodesCracked = geodesAfter(minutes),
)
}
private fun minutesUntil(goal: Resources) =
if (resources.isEnoughFor(goal)) 0
else maxOf(
ceil((goal.ore - resources.ore).toDouble() / oreRobots),
if (clayRobots > 0) ceil((goal.clay - resources.clay).toDouble() / clayRobots) else 0.0,
if (obsidianRobots > 0) ceil((goal.obsidian - resources.obsidian).toDouble() / obsidianRobots) else 0.0,
).toInt()
private fun resourcesAfter(minutes: Int) = resources.copy(
ore = resources.ore + oreRobots * minutes,
clay = resources.clay + clayRobots * minutes,
obsidian = resources.obsidian + obsidianRobots * minutes,
)
fun geodesAt(minutes: Int) = geodesAfter(minutes - minutesElapsed)
private fun geodesAfter(minutes: Int) = geodesCracked + geodeRobots * minutes
fun maxPotentialGeodes(minutes: Int) = geodesCracked + minutes * geodeRobots + (1 until minutes).sum()
}
private data class Blueprint(
val id: Int,
val oreRobot: Resources,
val clayRobot: Resources,
val obsidianRobot: Resources,
val geodeRobot: Resources
)
private data class Resources(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0) {
operator fun minus(other: Resources) =
copy(ore = ore - other.ore, clay = clay - other.clay, obsidian = obsidian - other.obsidian)
fun isEnoughFor(cost: Resources) = ore >= cost.ore && clay >= cost.clay && obsidian >= cost.obsidian
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 19
class Day19Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 33 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 1356 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 3472 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 27720 }
})
private val exampleInput =
"""
Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian.
""".trimIndent()
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 6,152 | adventofcode-kotlin | MIT License |
src/main/kotlin/recur/QuickSelect.kt | yx-z | 106,589,674 | false | null | package recur
import util.OneArray
import util.get
import util.swap
// given an unsorted array, A[1..n], find the k-th smallest element
fun main(args: Array<String>) {
val arr = OneArray(100) { it * 10 }
println(arr.quickSelect(30))
println(arr.momSelect(30))
}
// here we partition based on pivot index 1
// find a better pivoting strategy in `momSelect` below
fun OneArray<Int>.quickSelect(k: Int): Int {
val A = this
val n = size
if (n == 1) {
return A[1]
}
val r = partition(1)
// prettyPrintln(false)
return when {
k < r -> A[1 until r].quickSelect(k)
k > r -> A[r + 1..n].quickSelect(k - r)
else -> A[r]
}
}
// mom = median of median
fun OneArray<Int>.momSelect(k: Int): Int {
val A = this
val n = size
// we don't need to do fancy things if n is small
if (n <= 25) {
return quickSelect(k)
}
// here is the interesting part
// how can we find a good pivot?
// well an estimate of a median is a good pivot, so we can recurse and find
// a rough median!
val m = n / 5
val M = OneArray(m) { 0 }
for (i in 1..m) {
// find the median of five numbers
// either do brute force or quickselect <- overkill!
M[i] = A[5 * i - 4..5 * i].quickSelect(3)
}
val mom = M.momSelect(m / 2)
val r = partition(mom)
return when {
k < r -> A[1 until r].quickSelect(k)
k > r -> A[r + 1..n].quickSelect(k - r)
else -> A[r]
}
}
// given an element A[idx], partition A :
// A[1 until idx'] are elements less than or equal to A[idx] and
// A[idx' + 1..n] are elements greater than A[idx]
// return the correct index of A[idx], i.e. idx' after the partition
fun OneArray<Int>.partition(idx: Int): Int {
val A = this
val n = size
swap(idx, n)
var i = 0
var j = n
while (i < j) {
do {
i++
} while (i < j && A[i] <= A[n])
do {
j--
} while (i < j && A[j] > A[n])
if (i < j) {
swap(i, j)
}
}
// now idx >= j
swap(i, n)
return i
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,896 | AlgoKt | MIT License |
src/Day20.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} | fun Array<Int>.indexPos(signedPos: Int): Int {
return if (signedPos < 0) (this.size - 1 + (signedPos).rem(this.lastIndex)) else signedPos.rem(this.size)
}
fun main() { // ktlint-disable filename
fun part1(input: List<String>): Int {
val moves = input.map { it.toInt() }
val numbers = moves.toTypedArray()
moves.filter { it != 0 }.forEach { i ->
val oldPos = numbers.indexOf(i)
val newPos = numbers.indexPos(oldPos + i)
val destIndex = minOf(oldPos, newPos + 1)
val startIndex = minOf(oldPos + 1, newPos)
val endIndex = maxOf(oldPos, newPos + 1)
// println("copyright i:$i dest:$destIndex start:$startIndex end:$endIndex")
// shift array so there's space at the destination
numbers.copyInto(numbers, destIndex, startIndex, endIndex)
numbers[newPos] = i
println("numbers are: ${numbers.toList()}")
}
return 0
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
println("Grove coordinates sum: ${part1(testInput)}")
check(part1(testInput) == 64)
// println("Test #Exterior sides: ${part2(testInput)}")
// check(part2(testInput) == 58)
// val input = readInput("Day20_input")
// println("#Unconnected sides: ${part1(input)}")
// println("#Exterior sides: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 1,502 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/Day15.kt | spaikmos | 573,196,976 | false | {"Kotlin": 83036} | fun main() {
fun parseInput(input: List<String>): MutableSet<Pair<Pair<Int, Int>, Pair<Int, Int>>> {
val s = mutableSetOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>()
for (i in input) {
val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
val matchResult = regex.find(i)
val (sx, sy, bx, by) = matchResult!!.destructured
s.add(Pair(Pair(sx.toInt(), sy.toInt()), Pair(bx.toInt(), by.toInt())))
}
return s
}
// Calculate the number of positions in Row 2000000 that a beacon can NOT be located
fun part1(sb: MutableSet<Pair<Pair<Int, Int>, Pair<Int, Int>>>): Int {
val yRow = 2000000
val noBeacon = mutableSetOf<Int>()
for (i in sb) {
val (sensor, beacon) = i
// Calculate manhattan distance
val sensorRange = Math.abs(sensor.first - beacon.first) + Math.abs(sensor.second - beacon.second)
// Find distance to the yRow of interest
val yDist = Math.abs(yRow - sensor.second)
// If distance to yRow is less than the sensor's range, eliminate some points in the row
if (yDist < sensorRange) {
val xDist = sensorRange - yDist
for (x in (sensor.first - xDist)..(sensor.first + xDist)) {
noBeacon.add(x)
}
}
}
// NOTE: The data set contains one beacon at y=2000000. Instead of modifying the
// algorithm to handle this, I cheat and manually do it here.
return noBeacon.size - 1
}
// Find the one point in a 4,000,000 x 4,000,000 grid that the beacon must be located
fun part2(sb: MutableSet<Pair<Pair<Int, Int>, Pair<Int, Int>>>): Long {
val maxIdx = 4000000
val sensors = mutableSetOf<Pair<Pair<Int, Int>, Int>>()
// Pre-calculate all the sensor ranges first
for (i in sb) {
val (sensor, beacon) = i
val sensorRange = Math.abs(sensor.first - beacon.first) + Math.abs(sensor.second - beacon.second)
sensors.add(Pair(sensor, sensorRange))
}
// The 4M x 4M grid has 16M points. Check EACH point to see if any sensor can reach it.
// Since this is a lot of points to check, we need to speed it up.
for (x in 0..maxIdx) {
var y = 0
while (y <= maxIdx) {
var seen = false
for (i in sensors) {
val sensor = i.first
val range = i.second
val dist = Math.abs(x - sensor.first) + Math.abs(y - sensor.second)
if (dist <= range) {
// Sensor can see the beacon. Skip the range that the sensor can see the
// beacon by re-purposing the algorithm from part 1
val xDist = Math.abs(x - sensor.first)
val yDist = range - xDist
seen = true
if (dist < range) {
y = sensor.second + yDist
break
}
}
}
if (seen == false) {
println("Missing: x:$x, y:$y") // Missing: x:2949122, y:3041245
return maxIdx.toLong() * x + y
}
y++
}
}
return 0
}
val input = readInput("../input/Day15")
val sb = parseInput(input)
println(part1(sb)) // 5878678
println(part2(sb)) // 11796491041245
} | 0 | Kotlin | 0 | 0 | 6fee01bbab667f004c86024164c2acbb11566460 | 3,663 | aoc-2022 | Apache License 2.0 |
src/Day10.kt | Cryosleeper | 572,977,188 | false | {"Kotlin": 43613} | import kotlin.math.abs
private const val SCREEN_WIDTH = 40
fun main() {
fun part1(input: List<String>): Int {
var registerX = 1
var currentCycle = 1
val valuesToSave = mutableMapOf<Int, Int?>(
20 to null,
60 to null,
100 to null,
140 to null,
180 to null,
220 to null
)
input.forEach { line ->
valuesToSave.performCheck(currentCycle, registerX)
val command = line.split(" ")
when (command[0]) {
"noop" -> currentCycle++
"addx" -> {
currentCycle += 1
valuesToSave.performCheck(currentCycle, registerX)
currentCycle += 1
registerX += command[1].toInt()
}
}
}
return valuesToSave.values.sumOf { it!! }
}
fun part2(input: List<String>): String {
var output = ""
var registerX = 1
var currentCycle = 0
input.forEach { line ->
output += getPixel(currentCycle, registerX)
val command = line.split(" ")
when (command[0]) {
"noop" -> currentCycle++
"addx" -> {
currentCycle += 1
output += getPixel(currentCycle, registerX)
currentCycle += 1
registerX += command[1].toInt()
}
}
}
return output.drawOnScreen()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....""".trimIndent())
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
private fun MutableMap<Int, Int?>.performCheck(currentCycle: Int, registerX: Int) {
keys.forEach { key ->
if (currentCycle == key && this[key] == null) {
this[key] = registerX * currentCycle
return
}
}
}
private fun getPixel(pixel:Int, signal: Int) = if (abs(pixel%SCREEN_WIDTH - signal) < 2) "#" else "."
private fun String.drawOnScreen() = toList().chunked(SCREEN_WIDTH).joinToString("\n") { it.joinToString("") }
| 0 | Kotlin | 0 | 0 | a638356cda864b9e1799d72fa07d3482a5f2128e | 2,605 | aoc-2022 | Apache License 2.0 |
advent-of-code2016/src/main/kotlin/day10/Advent10.kt | REDNBLACK | 128,669,137 | false | null | package day10
import array2d
import day08.Operation.Type.*
import day10.Operation.Direction
import day10.Operation.Direction.BOT
import day10.Operation.Direction.OUTPUT
import day10.Operation.Target
import day10.Operation.Type.HIGH
import day10.Operation.Type.LOW
import mul
import parseInput
import splitToLines
import java.util.*
/**
--- Day 10: Balance Bots ---
You come upon a factory in which many robots are zooming around handing small microchips to each other.
Upon closer examination, you notice that each bot only proceeds when it has two microchips, and once it does, it gives each one to a different bot or puts it in a marked "output" bin. Sometimes, bots take microchips from "input" bins, too.
Inspecting one of the microchips, it seems like they each contain a single number; the bots must use some logic to decide what to do with each chip. You access the local control computer and download the bots' instructions (your puzzle input).
Some of the instructions specify that a specific-valued microchip should be given to a specific bot; the rest of the instructions indicate what a given bot should do with its lower-value or higher-value chip.
For example, consider the following instructions:
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
Initially, bot 1 starts with a value-3 chip, and bot 2 starts with a value-2 chip and a value-5 chip.
Because bot 2 has two microchips, it gives its lower one (2) to bot 1 and its higher one (5) to bot 0.
Then, bot 1 has two microchips; it puts the value-2 chip in output 1 and gives the value-3 chip to bot 0.
Finally, bot 0 has two microchips; it puts the 3 in output 2 and the 5 in output 0.
In the end, output bin 0 contains a value-5 microchip, output bin 1 contains a value-2 microchip, and output bin 2 contains a value-3 microchip. In this configuration, bot number 2 is responsible for comparing value-5 microchips with value-2 microchips.
Based on your instructions, what is the number of the bot that is responsible for comparing value-61 microchips with value-17 microchips?
--- Part Two ---
What do you get if you multiply together the values of one chip in each of outputs 0, 1, and 2?
*/
fun main(args: Array<String>) {
val test = """
|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
""".trimMargin()
val input = parseInput("day10-input.txt")
println(findBot(test, { b -> b.low() == 2 && b.high() == 5 }) == (2 to 30))
println(findBot(input, { b -> b.low() == 17 && b.high() == 61 }))
}
fun findBot(input: String, predicate: (Bot) -> Boolean): Pair<Int, Int> {
val bots = parseBots(input)
val outputs = HashMap<Int, Int>()
val operations = parseOperations(input)
var botNumber = 0
val done = mutableSetOf<Int>()
while (done.size < operations.size) {
for ((index, operation) in operations.withIndex()) {
val bot = bots.getOrElse(operation.botNumber, { Bot(operation.botNumber) })
if (!bot.hasChips()) continue
if (predicate(bot)) botNumber = bot.number
for ((number, direction, type) in operation.targets) {
val value = when (type) { LOW -> bot.low(); HIGH -> bot.high() }
when (direction) {
OUTPUT -> outputs.compute(number, { k, v -> value })
BOT -> bots.compute(number, { k, v -> (v ?: Bot(k)).addChip(value) })
}
}
bots.put(operation.botNumber, bot.clearChips())
done.add(index)
}
}
return botNumber to (0..2).map { outputs[it] }.filterNotNull().mul()
}
data class Bot(val number: Int, val chips: Set<Int> = setOf()) {
fun hasChips() = chips.size == 2
fun low() = chips.min() ?: throw RuntimeException()
fun high() = chips.max() ?: throw RuntimeException()
fun addChip(value: Int) = copy(chips = chips.plus(value))
fun clearChips() = copy(chips = setOf())
}
data class Operation(val botNumber: Int, val targets: Set<Target>) {
enum class Direction { OUTPUT, BOT }
enum class Type { LOW, HIGH }
data class Target(val entityNumber: Int, val direction: Direction, val type: Type)
}
private fun parseOperations(input: String) = input.splitToLines()
.filter { it.startsWith("bot") }
.sortedDescending()
.map {
val (botNumber, lowDirection, lowNumber, highDirection, highNumber) =
Regex("""bot (\d+) gives low to (bot|output) (\d+) and high to (bot|output) (\d+)""")
.findAll(it)
.map { it.groupValues.drop(1).toList() }
.toList()
.flatMap { it }
Operation(
botNumber = botNumber.toInt(),
targets = setOf(
Target(lowNumber.toInt(), Direction.valueOf(lowDirection.toUpperCase()), LOW),
Target(highNumber.toInt(), Direction.valueOf(highDirection.toUpperCase()), HIGH)
)
)
}
private fun parseBots(input: String) = input.splitToLines()
.filter { it.startsWith("value") }
.map {
val (value, botNumber) = Regex("""(\d+)""")
.findAll(it)
.map { it.groupValues[1] }
.map(String::toInt)
.toList()
botNumber to value
}
.groupBy { it.first }
.map { it.key to Bot(it.key, it.value.map { it.second }.toSet()) }
.toMap(HashMap())
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 5,985 | courses | MIT License |
src/aoc2017/kot/Day22.kt | Tandrial | 47,354,790 | false | null | package aoc2017.kot
import java.io.File
object Day22 {
fun solve(input: List<String>, cnt: Int, partTwo: Boolean = false): Int {
val grid = genGrid(input)
var count = 0
var pos = Pair(grid.size / 2, grid.size / 2)
var dir = Pair(-1, 0)
repeat(cnt) {
val (posX, posY) = pos
when (grid[posX][posY]) {
'#' -> {
//right turn
dir = Pair(dir.second, -dir.first)
if (partTwo) {
grid[posX][posY] = 'F'
} else {
grid[posX][posY] = '.'
}
}
'.' -> {
//left turn
dir = Pair(-dir.second, dir.first)
if (partTwo) {
grid[posX][posY] = 'W'
} else {
grid[posX][posY] = '#'
count++
}
}
'W' -> {
grid[posX][posY] = '#'
count++
}
'F' -> {
grid[posX][posY] = '.'
dir = Pair(-dir.first, -dir.second)
}
}
pos = Pair(posX + dir.first, posY + dir.second)
}
return count
}
private fun genGrid(input: List<String>): Array<CharArray> {
val grid = Array(1000) { CharArray(1000) { '.' } }
val offSet = grid.size / 2 - input.size / 2
for (xG in 0 until input.size) {
for (yG in 0 until input.size) {
grid[offSet + xG][offSet + yG] = input[xG][yG]
}
}
return grid
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day22_input.txt").readLines()
println("Part One = ${Day22.solve(input, 10000)}")
println("Part Two = ${Day22.solve(input, 10000000, true)}")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 1,617 | Advent_of_Code | MIT License |
src/day05/Day05.kt | easchner | 572,762,654 | false | {"Kotlin": 104604} | package day05
import readInputSpaceDelimited
import java.util.Stack
fun main() {
fun getStacks(input: List<String>): List<Stack<Char>> {
val stacks = mutableListOf<Stack<Char>>()
for (line in input) {
val containers = line.chunked(4).map {
it.substring(1, 2)[0]
}
for (i in containers.indices) {
val item = containers[i]
if (item in 'A'..'Z') {
while (stacks.size <= i) {
stacks.add(Stack())
}
stacks[i].push(item)
}
}
}
for (stack in stacks) {
stack.reverse()
}
return stacks
}
fun part1(input: List<List<String>>): String {
val stacks = getStacks(input[0])
for (line in input[1]) {
// Expected format: move 1 from 2 to 1
val nums = line.split(" ")
val amount = nums[1].toInt()
val from = nums[3].toInt() - 1
val target = nums[5].toInt() - 1
for (i in 0 until amount) {
stacks[target].push(stacks[from].pop())
}
}
return stacks.map { if (it.isNotEmpty()) it.pop() else "" }.joinToString("")
}
fun part2(input: List<List<String>>): String {
val stacks = getStacks(input[0])
for (line in input[1]) {
// move 1 from 2 to 1
val nums = line.split(" ")
val amount = nums[1].toInt()
val from = nums[3].toInt() - 1
val target = nums[5].toInt() - 1
val temp = Stack<Char>()
for (i in 0 until amount) {
temp.push(stacks[from].pop())
}
while(temp.isNotEmpty()) {
stacks[target].push(temp.pop())
}
}
return stacks.map { if (it.isNotEmpty()) it.pop() else "" }.joinToString("")
}
val testInput = readInputSpaceDelimited("day05/test")
val input = readInputSpaceDelimited("day05/input")
check(part1(testInput) == "CMZ")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 2,221 | Advent-Of-Code-2022 | Apache License 2.0 |
src/day04/Day04.kt | robin-schoch | 572,718,550 | false | {"Kotlin": 26220} | package day04
import AdventOfCodeSolution
fun main() {
Day04.run()
}
fun createRange(input: String) = with(input.split('-')) {
this[0].toInt()..this[1].toInt()
}
infix fun IntRange.overlaps(range: IntRange) = !(last < range.first || range.last < first)
infix fun IntRange.contains(range: IntRange) = first <= range.first && range.last <= last
object Day04 : AdventOfCodeSolution<Int, Int> {
override val testSolution1 = 2
override val testSolution2 = 4
override fun part1(input: List<String>): Int = input
.map { it.split(',') }
.map { createRange(it[0]) to createRange(it[1]) }
.count { (section1, section2) -> section1 contains section2 || section2 contains section1 }
override fun part2(input: List<String>): Int = input
.map { it.split(',') }
.map { createRange(it[0]) to createRange(it[1]) }
.count { (section1, section2) -> section1 overlaps section2 }
}
| 0 | Kotlin | 0 | 0 | fa993787cbeee21ab103d2ce7a02033561e3fac3 | 941 | aoc-2022 | Apache License 2.0 |
src/test/kotlin/be/brammeerten/y2023/Day10Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2023
import be.brammeerten.C
import be.brammeerten.readFile
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import kotlin.math.min
class Day10Test {
@Test
fun `part 1`() {
// val map = PipeMap(readFile("2023/day10/exampleInput.txt"))
// val map = PipeMap(readFile("2023/day10/exampleInput2.txt"))
val map = PipeMap(readFile("2023/day10/input.txt"))
val distances = listOfNotNull(
map.getDistanceMapNonStack(map.start + C.DOWN),
map.getDistanceMapNonStack(map.start + C.UP),
map.getDistanceMapNonStack(map.start + C.RIGHT),
map.getDistanceMapNonStack(map.start + C.LEFT),
)
// if (distances.size != 2) throw RuntimeException("Not expected")
var max = -1
for (key in distances[1].keys) {
val num = min(distances[1][key]!!, distances[3][key]!!)
if (num > max) max = num
}
// assertThat(max).isEqualTo(4);
// assertThat(max).isEqualTo(8);
assertThat(max).isEqualTo(7030);
}
class PipeMap(val rows: List<String>) {
val UP_DOWN = '|'
val LEFT_RIGHT = '-'
val UP_RIGHT = 'L'
val UP_LEFT = 'J'
val LEFT_DOWN = '7'
val RIGHT_DOWN = 'F'
val start: C;
val w: Int = rows[0].length;
val h: Int = rows.size
init {
var s: C? = null;
for (y in 0 until h) {
for (x in 0 until w) {
if (rows[y][x] == 'S') {
s = C(x, y);
break;
}
}
}
if (s != null) start = s else throw RuntimeException("No start")
}
fun getSurrounding(): List<C> {
val surrounding = mutableListOf<C>()
val down = get(start + C.DOWN)
if (down == UP_DOWN || down == UP_LEFT || down == UP_RIGHT)
surrounding.add(start + C.DOWN)
val left = get(start + C.LEFT)
if (left == RIGHT_DOWN || left == UP_RIGHT || left == LEFT_RIGHT)
surrounding.add(start + C.LEFT)
val right = get(start + C.RIGHT)
if (right == LEFT_RIGHT || right == LEFT_DOWN || right == UP_LEFT)
surrounding.add(start + C.RIGHT)
val up = get(start + C.UP)
if (up == UP_DOWN || up == RIGHT_DOWN || up == LEFT_DOWN)
surrounding.add(start + C.UP)
return surrounding
}
fun get(c: C): Char? {
if (c.y < rows.size && c.x < rows[0].length && c.y >= 0 && c.x >= 0)
return rows[c.y][c.x]
else return null
}
fun getDistanceMap(cur: C, next: C, curVal: Int = 0, map: MutableMap<C, Int> = mutableMapOf()): Map<C, Int>? {
val nextVal = get(next)
if (nextVal == 'S') return map
map[next] = curVal + 1
if (nextVal == UP_DOWN && cur != next + C.DOWN)
return getDistanceMap(next, next + C.DOWN, curVal + 1, map)
else if (nextVal == UP_DOWN)
return getDistanceMap(next, next + C.UP, curVal + 1, map)
if (nextVal == LEFT_RIGHT && cur != next + C.LEFT)
return getDistanceMap(next, next + C.LEFT, curVal + 1, map)
else if (nextVal == LEFT_RIGHT)
return getDistanceMap(next, next + C.RIGHT, curVal + 1, map)
if (nextVal == UP_RIGHT && cur != next + C.UP)
return getDistanceMap(next, next + C.UP, curVal + 1, map)
else if (nextVal == UP_RIGHT)
return getDistanceMap(next, next + C.RIGHT, curVal + 1, map)
if (nextVal == UP_LEFT && cur != next + C.UP)
return getDistanceMap(next, next + C.UP, curVal + 1, map)
else if (nextVal == UP_LEFT)
return getDistanceMap(next, next + C.LEFT, curVal + 1, map)
if (nextVal == LEFT_DOWN && cur != next + C.LEFT)
return getDistanceMap(next, next + C.LEFT, curVal + 1, map)
else if (nextVal == LEFT_DOWN)
return getDistanceMap(next, next + C.DOWN, curVal + 1, map)
if (nextVal == RIGHT_DOWN && cur != next + C.RIGHT)
return getDistanceMap(next, next + C.RIGHT, curVal + 1, map)
else if (nextVal == RIGHT_DOWN)
return getDistanceMap(next, next + C.DOWN, curVal + 1, map)
return null
}
fun getDistanceMapNonStack(nnnn: C): Map<C, Int>? {
var cur = start
var curVal = 0
var next = nnnn
var map: MutableMap<C, Int> = mutableMapOf()
while (true) {
val nextVal = get(next)
if (nextVal == 'S') return map
map[next] = curVal + 1
if (nextVal == UP_DOWN && cur != next + C.DOWN) {
cur = next; next += C.DOWN; curVal++; continue;
} else if (nextVal == UP_DOWN) {
cur = next; next += C.UP; curVal++; continue;
}
if (nextVal == LEFT_RIGHT && cur != next + C.LEFT) {
cur = next; next += C.LEFT; curVal++; continue;
} else if (nextVal == LEFT_RIGHT) {
cur = next; next += C.RIGHT; curVal++; continue;
}
if (nextVal == UP_RIGHT && cur != next + C.UP) {
cur = next; next += C.UP; curVal++; continue;
} else if (nextVal == UP_RIGHT) {
cur = next; next += C.RIGHT; curVal++; continue;
}
if (nextVal == UP_LEFT && cur != next + C.UP) {
cur = next; next += C.UP; curVal++; continue;
} else if (nextVal == UP_LEFT) {
cur = next; next += C.LEFT; curVal++; continue;
}
if (nextVal == LEFT_DOWN && cur != next + C.LEFT) {
cur = next; next += C.LEFT; curVal++; continue;
} else if (nextVal == LEFT_DOWN) {
cur = next; next += C.DOWN; curVal++; continue;
}
if (nextVal == RIGHT_DOWN && cur != next + C.RIGHT) {
cur = next; next += C.RIGHT; curVal++; continue;
} else if (nextVal == RIGHT_DOWN) {
cur = next; next += C.DOWN; curVal++; continue;
}
return null
}
}
}
} | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 6,629 | Advent-of-Code | MIT License |
code/numeric/ModLinEqSolver.kt | hakiobo | 397,069,173 | false | null | private class ModLinEqSolver(val matrix: Array<IntArray>, val p: Int) {
val inv = IntArray(p) { num ->
modPow(num.toLong(), (p - 2).toLong(), p.toLong()).toInt()
}
var status: Status? = null
private set
private fun swap(r1: Int, r2: Int) {
val tmp = matrix[r1]
matrix[r1] = matrix[r2]
matrix[r2] = tmp
}
private fun multiplyRow(row: Int, mult: Int) {
for (x in matrix[row].indices) {
matrix[row][x] *= mult
matrix[row][x] %= p
}
}
private fun divideRow(row: Int, div: Int) {
multiplyRow(row, inv[div])
}
private fun multiplyAddRow(row: Int, row2: Int, mult: Int) {
for (x in matrix[row].indices) {
matrix[row2][x] += matrix[row][x] * mult
matrix[row2][x] %= p
}
}
private fun examineCol(col: Int, idealRow: Int): Boolean {
var good = false
if (matrix[idealRow][col] == 0) {
for (row in idealRow + 1 until matrix.size) {
if (matrix[row][col] != 0) {
good = true
swap(row, idealRow)
break
}
}
} else {
good = true
}
if (good) {
divideRow(
idealRow,
matrix[idealRow][col]
)
for (row in matrix.indices) {
if (row == idealRow) continue
if (matrix[row][col] != 0) {
multiplyAddRow(
idealRow,
row,
p - matrix[row][col]
)
}
}
}
return good
}
fun solve() {
var idealRow = 0
var col = 0
while (idealRow < matrix.size && col < matrix[0].lastIndex) {
if (examineCol(col++, idealRow)) idealRow++
}
status = if (col != matrix[0].lastIndex) {
Status.MULTIPLE
} else if (idealRow != matrix.size && examineCol(col, idealRow)) {
Status.INCONSISTENT
} else if (idealRow == col) {
Status.SINGLE
} else {
Status.MULTIPLE
}
}
companion object {
private fun modPow(n: Long, k: Long, m: Long): Long {
if (k == 0L) {
return 1L
}
var half = modPow(n, k shr 1, m)
half *= half
if (k and 1L == 1L) {
half %= m
half *= n
}
return half % m
}
}
enum class Status {
INCONSISTENT, SINGLE, MULTIPLE
}
}
| 0 | Kotlin | 1 | 2 | f862cc5e7fb6a81715d6ea8ccf7fb08833a58173 | 2,693 | Kotlinaughts | MIT License |
src/main/kotlin/days/day11/Day11.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day11
import days.Day
import kotlin.math.abs
class Day11 : Day(false) {
override fun partOne(): Any {
return solve(1)
}
override fun partTwo(): Any {
return solve(999_999)
}
private fun solve(increas: Int):Long {
val input = readInput()
val galaxy = readInput().toMutableList()
val starCoordinates = mutableListOf<Pair<Long, Long>>()
for (i in galaxy.indices) {
for (j in galaxy[i].indices) {
if (galaxy[i][j] == '#') {
starCoordinates.add(Pair(i.toLong(), j.toLong()))
}
}
}
val strechedStarCoordinates = starCoordinates.toMutableList()
var countInsertions = 0
for (i in input.indices) {
if (input[i].none { it == '#' }) {
for (star in strechedStarCoordinates) {
if (star.first >= i + countInsertions * increas) {
strechedStarCoordinates[strechedStarCoordinates.indexOf(star)] =
Pair(star.first + increas, star.second)
}
}
countInsertions++
}
}
countInsertions = 0
for (i in input[0].indices) {
val column = input.map { it[i] }
if (column.none { it == '#' }) {
for (star in strechedStarCoordinates) {
if (star.second >= i + countInsertions * increas) {
strechedStarCoordinates[strechedStarCoordinates.indexOf(star)] =
Pair(star.first, star.second + increas)
}
}
countInsertions++
}
}
//make pairs of coordinates
val pairs = mutableListOf<Pair<Pair<Long, Long>, Pair<Long, Long>>>()
for (i in starCoordinates.indices) {
for (j in starCoordinates.indices) {
if (i != j && i < j) {
pairs.add(Pair(strechedStarCoordinates[i], strechedStarCoordinates[j]))
}
}
}
var totalDistance:Long = 0
for (pair in pairs) {
val distance = abs(pair.first.first - pair.second.first) + abs(pair.first.second - pair.second.second)
//println(pair to distance)
totalDistance += distance
}
return totalDistance
}
}
| 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 2,442 | advent-of-code_2023 | The Unlicense |
kotlin/2147-number-of-ways-to-divide-a-long-corridor.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | // Use combinatorics, time O(n) and space O(n)
class Solution {
fun numberOfWays(corridor: String): Int {
val mod = 1_000_000_007
val seats = mutableListOf<Int>()
for ((i, c) in corridor.withIndex()) {
if (c == 'S')
seats.add(i)
}
if (seats.size < 2 || seats.size % 2 == 1)
return 0
var res = 1L
var i = 1
while (i < seats.size - 1) {
res = (res * (seats[i + 1] - seats[i])) % mod
i += 2
}
return res.toInt()
}
}
// Use combinatorics, time O(n) and space O(1)
class Solution {
fun numberOfWays(corridor: String): Int {
val seats = corridor.count { it == 'S' }
if (seats < 2 || seats % 2 == 1) return 0
val mod = 1_000_000_007
var prev = corridor.indexOfFirst { it == 'S' }
var seatCount = 1
var res = 1L
for (i in prev + 1 until corridor.length) {
if (corridor[i] == 'S') {
if (seatCount == 2) {
res = (res * (i - prev)) % mod
seatCount = 1
} else {
seatCount++
}
prev = i
}
}
return res.toInt()
}
}
// Recursion + memoization, time O(n) and space O(n)
class Solution {
fun numberOfWays(corridor: String): Int {
val mod = 1_000_000_007
val dp = Array (corridor.length) { IntArray (3) { -1 } }
fun dfs(i: Int, seats: Int): Int {
if (i == corridor.length)
return if (seats == 2) 1 else 0
if (dp[i][seats] != -1) return dp[i][seats]
var res = 0
if (seats == 2) {
if (corridor[i] == 'S')
res = dfs(i + 1, 1)
else
res = (dfs(i + 1, 0) + dfs(i + 1, 2)) % mod
} else {
if (corridor[i] == 'S')
res = dfs(i + 1, seats + 1)
else
res = dfs(i + 1, seats)
}
dp[i][seats] = res
return res
}
return dfs(0, 0)
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 2,195 | leetcode | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/GraphSearch.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode
import java.util.*
fun <T : Any> searchGraph(
startingSet: Set<T>,
isDone: (T) -> Boolean,
nextSteps: (T) -> Set<Pair<T, Int>>,
computePath: Boolean = false,
heuristic: (T) -> Int = { 0 },
allowDuplicatesInQueue: Boolean = true
): Int {
val dists = mutableMapOf<T, Int>()
startingSet.forEach { dists[it] = 0 }
val queue = PriorityQueue(compareBy<T> { dists[it]!! + heuristic(it) })
queue += startingSet
val paths = mutableMapOf<T, T>()
while (queue.isNotEmpty()) {
val current: T = queue.remove()
val dist = dists[current]!!
if (isDone(current)) {
if (computePath) {
reconstructPath(current, paths).forEach { println(it) }
}
return dist
}
for ((next, stepSize) in nextSteps(current)) {
val nextDist = dist + stepSize
if (dists[next] == null || nextDist < dists[next]!!) {
dists[next] = nextDist
queue += next
if (computePath) paths[next] = current
} else if (nextDist < dists[next]!!) {
dists[next] = nextDist
if (!allowDuplicatesInQueue) queue -= next
queue += next
if (computePath) paths[next] = current
}
}
}
return -1
}
fun <T : Any> searchGraph(
start: T,
isDone: (T) -> Boolean,
nextSteps: (T) -> Set<Pair<T, Int>>,
computePath: Boolean = false,
heuristic: (T) -> Int = { 0 },
allowDuplicatesInQueue: Boolean = true
): Int = searchGraph(
startingSet = setOf(start),
isDone = isDone,
nextSteps = nextSteps,
computePath = computePath,
heuristic = heuristic,
allowDuplicatesInQueue = allowDuplicatesInQueue
)
fun <T> Set<T>.singleStep() = map { it to 1 }.toSet()
private fun <T> reconstructPath(end: T, cameFrom: Map<T, T>): List<T> = buildList<T> {
var current: T? = end
while (current != null) {
this += current
current = cameFrom[current]
}
}.asReversed()
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,110 | advent-of-code | MIT License |
src/Day05.kt | kedvinas | 572,850,757 | false | {"Kotlin": 15366} | fun main() {
fun part1(input: List<String>): String {
val stacks = mutableListOf<MutableList<String>>()
var i = 0
val line = input[i].chunked(4)
line.forEach {
stacks.add(mutableListOf(it))
}
while (true) {
if (input[++i].isEmpty()) {
break
}
val split = input[i].chunked(4)
split.forEachIndexed { j, it ->
stacks[j].add(it)
}
}
stacks.forEach { stack -> stack.removeAll { !it.contains("[") } }
stacks.forEach { it.reverse() }
while (++i < input.size) {
val split = input[i].split(" ")
var count = split[1].toInt()
val from = split[3].toInt() - 1
val to = split[5].toInt() - 1
while (count-- > 0) {
stacks[to].add(stacks[from].removeLast())
}
}
return stacks.map { it.last().replace("[\\[\\] ]".toRegex(), "") }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val stacks = mutableListOf<MutableList<String>>()
var i = 0
val line = input[i].chunked(4)
line.forEach {
stacks.add(mutableListOf(it))
}
while (true) {
if (input[++i].isEmpty()) {
break
}
val split = input[i].chunked(4)
split.forEachIndexed { j, it ->
stacks[j].add(it)
}
}
stacks.forEach { stack -> stack.removeAll { !it.contains("[") } }
stacks.forEach { it.reverse() }
while (++i < input.size) {
val split = input[i].split(" ")
var count = split[1].toInt()
val from = split[3].toInt() - 1
val to = split[5].toInt() - 1
val toMove = stacks[from].takeLast(count)
stacks[from] = stacks[from].dropLast(count).toMutableList()
stacks[to].addAll(toMove)
}
return stacks.map { it.last().replace("[\\[\\] ]".toRegex(), "") }.joinToString(separator = "")
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 04437e66eef8cf9388fd1aaea3c442dcb02ddb9e | 2,355 | adventofcode2022 | Apache License 2.0 |
src/main/aoc2015/Day24.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2015
import kotlin.math.min
class Day24(input: List<String>) {
private val parsedInput = input.map { it.toInt() }.sortedBy { -it } // Largest first
private fun List<Int>.weight(): Int = sum()
private fun List<Int>.qe(): Long = fold(1L) { acc, i -> i * acc }
private var smallestFound = input.size
/**
* Recursively make the first group by picking the largest numbers first until the group weight
* is at target weight. Abort if group weight is above target or if a smaller group than current
* group size have already been found.
*/
private fun makeGroup(group1: List<Int>, remaining: List<Int>, foundGroups: MutableList<List<Int>>, target: Int) {
when {
group1.weight() == target -> {
// Found a group of correct weight
foundGroups.add(group1)
smallestFound = min(smallestFound, group1.size)
return
}
group1.weight() > target -> return // Weight is too high, this is no good
remaining.isEmpty() -> return // Ran out of items to pick
group1.size >= smallestFound -> return // There are other smaller groups already, don't continue with this
}
val first = remaining.first()
val rest = remaining.drop(1)
// Either take a number
makeGroup(group1.toMutableList().apply { add(first) }, rest, foundGroups, target)
// or don't
makeGroup(group1, rest, foundGroups, target)
}
private fun balance(target: Int): Long {
val candidates = mutableListOf<List<Int>>()
makeGroup(listOf(), parsedInput, candidates, target)
return candidates.minOf { it.qe() }
}
fun solvePart1(): Long {
return balance(parsedInput.sum() / 3)
}
fun solvePart2(): Long {
return balance(parsedInput.sum() / 4)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,895 | aoc | MIT License |
kotlin/src/com/daily/algothrim/leetcode/medium/Search.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode.medium
/**
* 33. 搜索旋转排序数组
*
* 整数数组 nums 按升序排列,数组中的值 互不相同 。
* 在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。
* 给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 。
*/
class Search {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(Search().search(intArrayOf(4, 5, 6, 7, 0, 1, 2), 0))
println(Search().search(intArrayOf(4, 5, 6, 7, 0, 1, 2), 3))
println(Search().search(intArrayOf(1), 0))
println(Search().search(intArrayOf(3, 1), 1))
}
}
fun search(nums: IntArray, target: Int): Int {
var start = 0
var end = nums.size - 1
while (start <= end) {
val mid = start + (end - start).shr(1)
if (target == nums[mid]) return mid
if (nums[start] <= nums[mid]) {
if (target < nums[mid] && target >= nums[start]) {
end = mid - 1
} else {
start = mid + 1
}
} else {
if (target > nums[mid] && target <= nums[end]) {
start = mid + 1
} else {
end = mid - 1
}
}
}
return -1
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,719 | daily_algorithm | Apache License 2.0 |
src/main/kotlin/days/Day5.kt | jgrgt | 433,952,606 | false | {"Kotlin": 113705} | package days
import kotlin.math.abs
class Day5 : Day(5) {
override fun partOne(): Any {
return p1(inputList)
}
fun p1(ls: List<String>): Any {
val lines = parseLines(ls).filter { it.isVerticalSameX() || it.isHorizontalSameY() }
val maxPoint = findMaxPoint(lines)
val ground = Ground(maxPoint)
lines.forEach { line ->
ground.add(line)
}
val result = ground.map { _: Day5Point, value: Int ->
if (value > 1) {
1
} else {
0
}
}.sum()
println("Result $result")
// ground.print()
return result
}
fun findMaxPoint(lines: List<Line>) = lines.fold(Day5Point(0, 0)) { acc, line ->
val maxX = maxOf(line.a.x, line.b.x, acc.x)
val maxY = maxOf(line.a.y, line.b.y, acc.y)
Day5Point(maxX + 1, maxY + 1)
}
fun parseLines(ls: List<String>) =
ls.map { Line.from(it) }
override fun partTwo(): Any {
return p2(inputList)
}
fun p2(ls: List<String>): Any {
val lines = parseLines(ls)
val maxPoint = findMaxPoint(lines)
val ground = Ground(maxPoint)
lines.forEach { line ->
ground.add(line)
}
val result = ground.map { _: Day5Point, value: Int ->
if (value > 1) {
1
} else {
0
}
}.sum()
println("Result $result")
ground.print()
return result
}
}
data class Ground(val maxPoint: Day5Point) {
val ventLines = (0..maxPoint.y).map {
(0..maxPoint.x).map {
0
}.toMutableList()
}.toMutableList()
fun add(line: Line) {
line.forEachPoint { p: Day5Point ->
ventLines[p.y][p.x] += 1
}
}
fun <T> map(consumer: (Day5Point, Int) -> T): List<T> {
return ventLines.flatMapIndexed { x, subList ->
subList.mapIndexed { y, value ->
consumer.invoke(Day5Point(x, y), value)
}
}
}
fun print() {
ventLines.forEach { subList ->
val line = subList.map {
if (it == 0) {
"."
} else {
it.toString()
}
}.joinToString("")
println(line)
}
}
}
data class Day5Point(val x: Int, val y: Int) {
companion object {
fun from(s: String): Day5Point {
val (x, y) = s.trim().split(",").map { it.trim().toInt() }
return Day5Point(x, y)
}
}
}
data class Line(val a: Day5Point, val b: Day5Point) {
// vertical is same x
fun isVerticalSameX(): Boolean {
return a.x == b.x
}
// horizontal is same y
fun isHorizontalSameY(): Boolean {
return a.y == b.y
}
fun forEachPoint(consumer: (Day5Point) -> Unit) {
points().forEach {
consumer.invoke(it)
}
}
fun points(): List<Day5Point> {
val minX = minOf(a.x, b.x)
val maxX = maxOf(a.x, b.x)
val minY = minOf(a.y, b.y)
val maxY = maxOf(a.y, b.y)
return if (maxX == minX) {
(minY..maxY).map { y ->
(Day5Point(maxX, y))
}
} else if (maxY == minY) {
(minX..maxX).map { x ->
(Day5Point(x, maxY))
}
} else {
// Diagonal
val xStep = if (a.x < b.x) {
1
} else {
-1
}
val yStep = if (a.y < b.y) {
1
} else {
-1
}
val times = abs(a.x - b.x)
(0..times).map { i ->
Day5Point(a.x + xStep * i, a.y + yStep * i)
}
}
}
companion object {
fun from(s: String): Line {
val (pointAString, pointBString) = s.split(Regex.fromLiteral("->"))
return Line(Day5Point.from(pointAString), Day5Point.from(pointBString))
}
}
}
| 0 | Kotlin | 0 | 0 | 6231e2092314ece3f993d5acf862965ba67db44f | 4,107 | aoc2021 | Creative Commons Zero v1.0 Universal |
src/day4/Day4.kt | ZsemberiDaniel | 159,921,870 | false | null | package day4
import RunnablePuzzleSolver
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
class Day4 : RunnablePuzzleSolver {
val guards: HashMap<Int, Guard> = hashMapOf()
override fun readInput1(lines: Array<String>) {
// patterns for matching the input string
val datePattern = Pattern.compile("""\[(.+)] (.+)""")
val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm")
val guardStartPattern = Pattern.compile("""Guard #(\d+) begins shift""")
// gets the date from a line and sorts the list by the date
val linesWithDates = lines.map {
val matcher = datePattern.matcher(it).apply { find() }
// first group is date second is the rest of the string
Pair(dateFormatter.parse(matcher.group(1)), matcher.group(2))
}.sortedBy { it.first }
var currGuardId: Int = -1
for (line in linesWithDates) {
// we have a new guard
val guardStartMatcher = guardStartPattern.matcher(line.second).apply { find() }
if (guardStartMatcher.matches()) {
currGuardId = guardStartMatcher.group(1).toInt()
// we don't have a guard with this id so we need to make one
if (!guards.containsKey(currGuardId))
guards[currGuardId] = Guard(currGuardId)
} else { // current guard either falls asleep or wakes up
if (line.second == "wakes up") {
guards[currGuardId]!!.times[line.first.minutes]--
} else if (line.second == "falls asleep") {
guards[currGuardId]!!.times[line.first.minutes]++
}
}
}
// calculate some stuff for later usage
for (guard in guards.values)
guard.calculateAsleepDayCountPerMinute()
}
override fun readInput2(lines: Array<String>) { }
override fun solvePart1(): String {
// represents the guard who slept the most with id, sleepTime, mostSleptMinute
var mostMinuteAsleep = Triple(-1, 0, -1)
// for each guard we check for each minute on how many days he was asleep
for (guard in guards.values) {
// how many minutes the guard was asleep all in all
var sumOfSleepTimeGuard = 0
// in which minute the guard was asleep on most days: count, minute
var mostMinuteAsleepGuard = Pair(-1, 0)
for (minute in 0 until guard.times.size) {
// how many minutes were spent asleep
sumOfSleepTimeGuard += guard.asleepDayCountPerMinute[minute]
if (guard.asleepDayCountPerMinute[minute] > mostMinuteAsleepGuard.first) {
mostMinuteAsleepGuard = Pair(guard.asleepDayCountPerMinute[minute], minute)
}
}
if (sumOfSleepTimeGuard > mostMinuteAsleep.second) {
mostMinuteAsleep = Triple(guard.id, sumOfSleepTimeGuard, mostMinuteAsleepGuard.second)
}
}
return (mostMinuteAsleep.first * mostMinuteAsleep.third).toString()
}
override fun solvePart2(): String {
var maxGuard: Guard = guards.values.first()
var maxMinute = 0
for (minute in 0 until 60) {
// the guard that slept on most days in this minute
val currMaxGuard = guards.values.maxBy { it.asleepDayCountPerMinute[minute] }!!
// found a better solution
if (currMaxGuard.asleepDayCountPerMinute[minute] > maxGuard.asleepDayCountPerMinute[maxMinute]) {
maxGuard = currMaxGuard
maxMinute = minute
}
}
return (maxGuard.id * maxMinute).toString()
}
data class Guard(val id: Int) {
val times: Array<Int> = Array(60) { 0 }
val asleepDayCountPerMinute: Array<Int> = Array(60) { 0 }
/**
* Calculates for each minute on how many days the guard was asleep.
*/
fun calculateAsleepDayCountPerMinute() {
asleepDayCountPerMinute[0] = times[0]
for (i in 1 until times.size) {
asleepDayCountPerMinute[i] += asleepDayCountPerMinute[i - 1] + times[i]
}
}
}
} | 0 | Kotlin | 0 | 0 | bf34b93aff7f2561f25fa6bd60b7c2c2356b16ed | 4,302 | adventOfCode2018 | MIT License |
src/Day16.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | import kotlin.math.max
import kotlin.system.measureTimeMillis
fun main() {
val valves = readInput("Day16_input").mapIndexed { index, str ->
val parts = str.split(" ")
val name = parts[1]
val flowRate = parts[4].split("=")[1].dropLast(1).toInt()
val neighbors = parts.takeLast(parts.size - 9).map { it.trim { ch -> !ch.isLetter() } }
name to Valve(index, flowRate, neighbors)
}.toMap()
val maximumForState = mutableMapOf<VolcanoScanState, Int>()
fun calculateMaxStartingAtState(state: VolcanoScanState): Int {
// println(state)
if (maximumForState.contains(state)) {
return maximumForState[state]!!
}
if (state.timeLeft == 0) {
maximumForState[state] = 0
return maximumForState[state]!!
}
val currentValve = valves[state.currentValve]!!
var maxValue = 0
// If valve not opened and has some flow, try opening
if (currentValve.flowRate > 0 && (state.openedValuesBitMask and (1L shl currentValve.index)) == 0L) {
maxValue = max(
maxValue,
(currentValve.flowRate * (state.timeLeft - 1))
+ calculateMaxStartingAtState(
VolcanoScanState(
state.currentValve,
state.openedValuesBitMask or (1L shl currentValve.index),
state.timeLeft - 1
)
)
)
}
// Go and visit valves
for (n in currentValve.neighbors) {
maxValue = max(
maxValue,
calculateMaxStartingAtState(VolcanoScanState(n, state.openedValuesBitMask, state.timeLeft - 1))
)
}
maximumForState[state] = maxValue
return maximumForState[state]!!
}
val maximumForEndingState = mutableMapOf<VolcanoScanState, Int>()
fun calculateMaxEndingInState(targetState: VolcanoScanState): Int {
// println(state)
if (maximumForEndingState.contains(targetState)) {
return maximumForEndingState[targetState]!!
}
if (targetState.timeLeft == 0 || targetState.openedValuesBitMask == 0L) {
maximumForEndingState[targetState] = 0
return maximumForEndingState[targetState]!!
}
val currentValve = valves[targetState.currentValve]!!
var maxValue = 0
// If valve not opened and has some flow, try opening
if ((targetState.openedValuesBitMask and (1L shl currentValve.index)) != 0L) {
val maxStateIfCurrentOpened =
calculateMaxEndingInState(
VolcanoScanState(
targetState.currentValve,
targetState.openedValuesBitMask xor (1L shl currentValve.index),
targetState.timeLeft - 1
)
)
maxValue = max(maxValue, currentValve.flowRate * (targetState.timeLeft - 1) + maxStateIfCurrentOpened)
}
// Go and visit valves
for (n in currentValve.neighbors) {
maxValue = max(
maxValue,
calculateMaxEndingInState(
VolcanoScanState(
n,
targetState.openedValuesBitMask,
targetState.timeLeft - 1
)
)
)
}
maximumForEndingState[targetState] = maxValue
return maxValue
}
val part1 = calculateMaxStartingAtState(VolcanoScanState("AA", 0, 30))
println("part1: $part1")
// Part 2: The idea is that the set of valves opened by you and elephant will not intersect.
// TODO: This takes ~50 seconds to run, optimize away the zero flow nodes by computing shortest paths
// between every two nodes
val nonZeroValves = valves.filter { entry -> entry.value.flowRate > 0 }.map { entry -> entry.value.index }.toList()
val masks = mutableMapOf<Int, Long>()
for (i in 0 until (1 shl nonZeroValves.size)) {
masks[i] = nonZeroValves.mapIndexed { index, value -> if ((i and (1 shl index)) != 0) (1L shl value) else 0L }
.reduce { a, b -> a or b }
}
var maxValue = 0
val timeToRun = measureTimeMillis {
for (i in ((1 shl nonZeroValves.size) - 1) downTo 0) {
val j = i xor ((1 shl nonZeroValves.size) - 1)
val vali = calculateMaxEndingInState(VolcanoScanState("AA", masks[i]!!, 26))
val valj = calculateMaxEndingInState(VolcanoScanState("AA", masks[j]!!, 26))
maxValue = max(maxValue, vali + valj)
}
}
println("part2: $maxValue, time: $timeToRun")
}
private data class Valve(val index: Int, val flowRate: Int, val neighbors: List<String>)
private data class VolcanoScanState(val currentValve: String, val openedValuesBitMask: Long, val timeLeft: Int) {
override fun toString(): String {
return "valve=$currentValve, opened=${openedValuesBitMask.toString(2)} timeLeft=$timeLeft"
}
} | 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 5,125 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/adrielm/aoc2020/common/Algorithms.kt | Adriel-M | 318,860,784 | false | null | package com.adrielm.aoc2020.common
object Algorithms {
private fun <T> twoSum(
input: List<T>,
target: T,
startingIndex: Int,
subtractFun: (T, T) -> T
): Pair<T, T>? {
val visited = mutableSetOf<T>()
for (i in startingIndex until input.size) {
val currentNumber = input[i]
val numberToFind = subtractFun(target, currentNumber)
if (numberToFind in visited) {
return Pair(numberToFind, currentNumber)
}
visited.add(currentNumber)
}
return null
}
fun twoSum(input: List<Int>, target: Int, startingIndex: Int = 0): Pair<Int, Int>? {
return twoSum(
input = input,
target = target,
startingIndex = startingIndex,
subtractFun = { a, b -> a.minus(b) }
)
}
fun twoSum(input: List<Long>, target: Long, startingIndex: Int = 0): Pair<Long, Long>? {
return twoSum(
input = input,
target = target,
startingIndex = startingIndex,
subtractFun = { a, b -> a.minus(b) }
)
}
fun threeSum(input: List<Int>, target: Int): Triple<Int, Int, Int>? {
for ((i, currentNumber) in input.withIndex()) {
val targetTwoSum = target - currentNumber
val twoSumAnswer = twoSum(input, targetTwoSum, i + 1)
if (twoSumAnswer != null) {
return Triple(twoSumAnswer.first, twoSumAnswer.second, currentNumber)
}
}
return null
}
fun <T> binarySearch(lower: Int, upper: Int, instructions: List<T>, upperDecision: (T) -> Boolean): Int {
var currentLower = lower
var currentUpper = upper
for (instruction in instructions) {
val takeUpper = upperDecision(instruction)
val midPoint = (currentUpper + currentLower) / 2
if (takeUpper) {
currentLower = midPoint + 1
} else {
currentUpper = midPoint
}
}
return currentLower
}
private fun <PT, CT, O> dfs(
graph: Map<PT, Collection<CT>>,
start: PT,
getChildKeyLambda: (CT) -> PT,
actionAtEachLevel: (PT) -> Unit,
endOfLevelLambda: (PT, List<ChildAndReturn<CT, O>>) -> O
): O {
val visitedAndReturn = mutableMapOf<PT, O>()
fun traverse(current: PT): O {
if (current in visitedAndReturn) return visitedAndReturn[current]!!
actionAtEachLevel(current)
val children = graph[current] ?: listOf()
val childAndOutput = children.map { ChildAndReturn(it, traverse(getChildKeyLambda(it))) }
val returnValue = endOfLevelLambda(current, childAndOutput)
visitedAndReturn[current] = returnValue
return returnValue
}
return traverse(start)
}
fun <T> dfsActionEveryLevel(graph: Map<T, Set<T>>, start: T, actionAtEachLevel: (T) -> Unit) {
dfs(
graph = graph,
start = start,
actionAtEachLevel = actionAtEachLevel,
getChildKeyLambda = { it },
endOfLevelLambda = { _, _: List<*> -> }
)
}
fun <PT, CT, O> dfsReturn(
graph: Map<PT, Set<CT>>,
start: PT,
getChildKeyLambda: (CT) -> PT,
endOfLevelLambda: (PT, List<ChildAndReturn<CT, O>>) -> O
): O {
return dfs(
graph = graph,
start = start,
getChildKeyLambda = getChildKeyLambda,
actionAtEachLevel = { },
endOfLevelLambda = endOfLevelLambda,
)
}
class ChildAndReturn<CT, O>(
val child: CT,
val returnValue: O
)
}
| 0 | Kotlin | 0 | 0 | 8984378d0297f7bc75c5e41a80424d091ac08ad0 | 3,778 | advent-of-code-2020 | MIT License |
src/main/kotlin/advent/day10/SyntaxScoring.kt | hofiisek | 434,171,205 | false | {"Kotlin": 51627} | package advent.day10
import advent.loadInput
import java.io.File
/**
* @author <NAME>
*/
typealias Stack = ArrayDeque<Char>
fun Char.isOpeningBracket() = listOf('(', '[', '{', '<').contains(this)
infix fun Char.doesNotClose(openingChar: Char) = !(this closes openingChar)
infix fun Char.closes(openingBracket: Char) = openingBracket.findClosingBracket() == this
fun Char.findClosingBracket() = when (this) {
'(' -> ')'
'[' -> ']'
'{' -> '}'
'<' -> '>'
else -> throw IllegalArgumentException("Invalid opening char: $this")
}
val Char.syntaxErrorScore
get() = when (this) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> throw IllegalArgumentException("Invalid closing char: $this")
}
val Char.autocompletionScore: Long
get() = when (this) {
')' -> 1L
']' -> 2L
'}' -> 3L
'>' -> 4L
else -> throw IllegalArgumentException("Invalid closing char: $this")
}
fun part1(input: File) = input.readLines()
.map { chars ->
val stack = Stack()
chars.forEach { curr ->
when {
curr.isOpeningBracket() -> stack.add(curr)
curr closes stack.last() -> stack.removeLast()
curr doesNotClose stack.last() -> return@map curr // we only care about first illegal char
else -> throw IllegalArgumentException("Invalid char '$curr' in input line $chars")
}
}
null
}
.filterNotNull()
.sumOf(Char::syntaxErrorScore)
fun part2(input: File) = input.readLines()
.map { chars -> findCharsToComplete(chars.toList()) }
.filter(List<Char>::isNotEmpty)
.map { unclosedBrackets ->
unclosedBrackets
.reversed()
.map(Char::findClosingBracket)
.fold(0L) { totalScore, curr -> 5 * totalScore + curr.autocompletionScore }
}
.sorted()
.let { it[it.size / 2] }
fun findCharsToComplete(brackets: List<Char>, stack: List<Char> = emptyList()): List<Char> =
brackets
.firstOrNull()
?.let { bracket ->
when {
bracket.isOpeningBracket() -> findCharsToComplete(brackets.drop(1), stack + brackets.first())
bracket closes stack.last() -> findCharsToComplete(brackets.drop(1), stack.dropLast(1))
bracket doesNotClose stack.last() -> emptyList()
else -> throw IllegalArgumentException("Illegal bracket: $bracket")
}
} ?: stack
fun main() {
with(loadInput(day = 10)) {
// with(loadInput(day = 10, filename = "input_example.txt")) {
println(part1(this))
println(part2(this))
}
} | 0 | Kotlin | 0 | 2 | 3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb | 2,713 | Advent-of-code-2021 | MIT License |
src/main/kotlin/co/csadev/advent2021/Day21.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2021, Day 21
* Problem Description: http://adventofcode.com/2021/day/21
*/
package co.csadev.advent2021
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Resources.resourceAsList
class Day21(override val input: List<String> = resourceAsList("21day21.txt")) :
BaseDay<List<String>, Int, Long> {
private var rollCount = 0
private val deterministicDie: Sequence<Int>
get() = sequence {
while (true) {
yield((rollCount++ % 100) + 1)
}
}
override fun solvePart1(): Int {
var p1Pos = input.first().toInt()
var p1Score = 0
var p2Pos = input.last().toInt()
var p2Score = 0
val dice = deterministicDie
while (true) {
var roll = dice.take(3).sum()
p1Pos = (p1Pos + roll) % 10
p1Score += if (p1Pos == 0) 10 else p1Pos
if (p1Score >= 1000) {
return p2Score * rollCount
}
roll = dice.take(3).sum()
p2Pos = (p2Pos + roll) % 10
p2Score += if (p2Pos == 0) 10 else p2Pos
if (p2Score >= 1000) {
return p1Score * rollCount
}
}
}
override fun solvePart2(): Long = Score(input.first().toInt(), input.last().toInt(), 0, 0).let { (first, second) ->
maxOf(
first,
second
)
}
private object Score {
private val dice = sequence {
for (i in 1..3) for (j in 1..3) for (k in 1..3) yield(i + j + k)
}.groupingBy { it }.eachCount()
private val x = LongArray(44100)
private val y = LongArray(44100)
operator fun invoke(player1: Int, player2: Int, score1: Int, score2: Int): Pair<Long, Long> {
val i = player1 + 10 * player2 + 100 * score1 + 2100 * score2 - 11
if (x[i] == 0L && y[i] == 0L) {
var x1 = 0L
var y1 = 0L
for ((d, n) in dice) {
val play = (player1 + d - 1) % 10 + 1
if (score1 + play < 21) {
val (x2, y2) = this(player2, play, score2, score1 + play)
x1 += n * y2
y1 += n * x2
} else {
x1 += n
}
}
x[i] = x1
y[i] = y1
}
return x[i] to y[i]
}
}
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 2,535 | advent-of-kotlin | Apache License 2.0 |
src/year2022/day25/Day25.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day25
import readInputFileByYearAndDay
import readTestFileByYearAndDay
import kotlin.math.pow
val snafuToDec = mapOf('=' to -2, '-' to -1, '0' to 0, '1' to 1, '2' to 2)
fun main() {
fun decimalToSnafu(decimal: String): String {
val dec = decimal.toLong()
var digits = ""
var remaining = dec
while (remaining > 0) {
digits = "012=-"[(remaining % 5).toInt()] + digits
remaining -= ((remaining + 2) % 5) - 2
remaining /= 5
}
return digits
}
fun snafuToDecimal(snafu: String) =
snafu.reversed().mapIndexed { index, c -> snafuToDec[c]!! * 5.0.pow(index) }.map { it.toLong() }.sum()
fun part1(input: List<String>): String =
input.map { snafuToDecimal(it) }.sum().let { decimalToSnafu(it.toString()) }
fun part2(input: List<String>): String {
return "🙏"
}
val testInput = readTestFileByYearAndDay(2022, 25)
check(part1(testInput) == "2=-1=0")
check(part2(testInput) == "🙏")
val input = readInputFileByYearAndDay(2022, 25)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 1,153 | advent-of-code-kotlin | Apache License 2.0 |
AOC-2017/src/main/kotlin/Day16.kt | sagar-viradiya | 117,343,471 | false | {"Kotlin": 72737} | import utils.splitAtComma
object Day16 {
fun part1(danceMoves: String, input: String = "abcdefghijklmnop"): String {
val programs = StringBuffer(input)
var danceMoveType: DanceMoveType
for (danceMove in danceMoves.splitAtComma()) {
danceMoveType = getDanceMoveType(danceMove)
when(danceMoveType) {
is DanceMoveType.Spin -> {
val splitAt = programs.length - danceMoveType.spins
val firstPart = programs.substring(0 until splitAt)
programs.replace(0, splitAt, "")
programs.append(firstPart)
}
is DanceMoveType.Exchange -> {
val programA = programs[danceMoveType.positionA]
val programB = programs[danceMoveType.positionB]
programs.replace(danceMoveType.positionA, danceMoveType.positionA + 1, programB.toString())
programs.replace(danceMoveType.positionB, danceMoveType.positionB + 1, programA.toString())
}
is DanceMoveType.Partner -> {
val positionA = programs.indexOf(danceMoveType.programA)
val positionB = programs.indexOf(danceMoveType.programB)
programs.replace(positionA, positionA + 1, danceMoveType.programB.toString())
programs.replace(positionB, positionB + 1, danceMoveType.programA.toString())
}
}
}
return programs.toString()
}
/**
* Old solution using caching to reduce computation.
* Not optimise as it is iterating 1 billion times!
* */
/*fun part2(danceMoves: String, input: String = "abcdefghijklmnop", danceRepeat: Long = 1000000000): String {
var _input = input
val danceMapping = mutableMapOf<String, String>()
for (i in 0 until danceRepeat) {
if (danceMapping[_input] == null) {
danceMapping[_input] = part1(danceMoves, _input)
}
_input = danceMapping[_input]!!
}
return _input
}*/
/**
* Original solution was to iterate 1 billion times! and cache the result of dance sequence.
*
* This solution is optimised as it has much less iterations.
* Copied form https://github.com/dlew/aoc-2017/blob/answers/src/main/kotlin/Day16.kt
* */
fun part2(danceMoves: String, input: String = "abcdefghijklmnop", danceRepeat: Int = 1000000000): String {
var _input = input
for (i in 0 until danceRepeat % findCycleLength(danceMoves, input)) {
_input = part1(danceMoves, _input)
}
return _input
}
private fun findCycleLength(danceMoves: String, input: String): Int {
var _input = input
val seen = mutableSetOf<String>()
var length = 0
while (_input !in seen) {
seen.add(_input)
_input = part1(danceMoves, _input)
length++
}
return length
}
private fun getDanceMoveType(input: String): DanceMoveType {
return when(input[0]) {
's' -> DanceMoveType.Spin(input.substring(1).toInt())
'x' -> {
val exchangeIndices = input.substring(1).split("/")
DanceMoveType.Exchange(exchangeIndices[0].toInt(), exchangeIndices[1].toInt())
}
'p' -> {
DanceMoveType.Partner(input[1], input[3])
}
else -> throw IllegalArgumentException("Invalid dance move")
}
}
sealed class DanceMoveType {
class Spin(val spins: Int): DanceMoveType()
class Exchange(val positionA: Int, val positionB: Int): DanceMoveType()
class Partner(val programA: Char, val programB: Char): DanceMoveType()
}
} | 0 | Kotlin | 0 | 0 | 7f88418f4eb5bb59a69333595dffa19bee270064 | 3,872 | advent-of-code | MIT License |
src/main/kotlin/utils/Primes.kt | embuc | 735,933,359 | false | {"Kotlin": 110920, "Java": 60263} | package se.embuc.utils
import kotlin.math.sqrt
fun isPrime(n: Long): Boolean {
if (n < 2) return false
if (n == 2L) return true
if (n % 2L == 0L) return false
val sqrtN = Math.sqrt(n.toDouble()).toLong()
for (i in 3..sqrtN step 2) {
if (n % i == 0L) return false
}
return true
}
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n == 2) return true
if (n % 2 == 0) return false
val sqrtN = Math.sqrt(n.toDouble()).toLong()
for (i in 3..sqrtN step 2) {
if (n % i == 0L) return false
}
return true
}
fun findNextPrime(n: Long): Long {
var i = n + 1
while (!isPrime(i)) i++
return i
}
fun primeFactors(n: Int, primes: List<Int>): Set<Int> {
var number = n
val factors = mutableSetOf<Int>()
// Check divisibility by provided prime numbers
for (prime in primes) {
if (prime > number) break // No need to check primes greater than the remaining number
while (number % prime == 0) {
factors.add(prime)
number /= prime
}
}
// If number is a prime greater than the last prime in the list
if (number > 1) {
factors.add(number)
}
return factors
}
fun primeFactorsCount(n: Int): Int {
var number = n
var count = 0
var primeTest = -1
val rootOfN = sqrt(n.toDouble())
// Divide out all factors of 2
while (number % 2 == 0) {
if (primeTest != 2) {
count++
primeTest = 2
}
number /= 2;
}
var i = 3
while (i <= rootOfN) {
while (number % i === 0) {
if (primeTest != i) {
count++
primeTest = i
}
number /= i
}
i += 2
}
// add any remaining prime factors greater than 2
if (number > 2) {
count++
}
return count
}
// with primes for caching
fun primeFactorsCount(n: Int, primes: List<Int>): Int {
var number = n
var count = 0
var primeTest = -1
val rootOfN = sqrt(n.toDouble()).toInt()
for (prime in primes) {
if (prime > rootOfN) break // No need to check primes greater than the root of the number
while (number % prime == 0) {
if (primeTest != prime) {
count++
primeTest = prime
}
number /= prime
}
}
// If number is a prime greater than the last prime in the list
if (number > 1) {
count++
}
return count
}
//Sieve of Eratosthenes algorithm. This algorithm is highly efficient for finding all prime numbers up to a certain
//limit. It works by iteratively marking the multiples of each prime number as non-prime.
//This implementation initializes a Boolean array, prime, to keep track of whether each number up to n is prime.
//Initially, all entries in the array are set to true. Then, for each number starting from 2, if the number is marked as
//prime, it's added to the sum, and all of its multiples are marked as non-prime (false).
fun sumOfPrimesBelow(n: Int): Long {
var sum = 0L
val primes = getPrimesSieveBelow(n)
primes.forEachIndexed { index, b ->
if (b) sum += index
}
return sum
}
//optimized version for whole array of primes:
//All even numbers except 2 are marked as non-prime initially.
//The outer loop runs through odd numbers starting from 3 and only up to the square root of n.
//The inner loop starts from i * i and steps through numbers at intervals of 2 * i (since we're only considering odd
//multiples of i, which are odd).
fun getPrimesSieveBelow(n: Int): BooleanArray {
val sievePrimes = BooleanArray(n) { true }
if (n > 0) sievePrimes[0] = false
if (n > 1) sievePrimes[1] = false
for (i in 4 until n step 2) {//jump over 2 and mark all even numbers as non-prime
sievePrimes[i] = false
}
val sqrtN = kotlin.math.sqrt(n.toDouble()).toInt()
for (i in 3..sqrtN step 2) {
if (sievePrimes[i]) {
for (j in i * i until n step 2 * i) {
sievePrimes[j] = false
}
}
}
return sievePrimes
}
fun getUpToNPrimes(limit: Int): List<Int> {
// Pn < n ln (n ln n) for n ≥ 6
val size = if (limit < 6) 13 else (limit * Math.log(limit.toDouble() * Math.log(limit.toDouble()))).toInt()
val sieve = getPrimesSieveBelow(size);
val primes = mutableListOf<Int>()
for (i in 2 until sieve.size) {
if (sieve[i]) {
primes.add(i)
}
if (primes.size == limit) break
}
return primes
}
fun getPrimesBelow(limit: Int): Pair<MutableList<Int>, BooleanArray> {
val sieve = getPrimesSieveBelow(limit);
val primes = mutableListOf<Int>()
for (i in 2 until sieve.size) {
if (sieve[i]) {
primes.add(i)
}
}
return Pair(primes, sieve)
} | 0 | Kotlin | 0 | 1 | 79c87068303f862037d27c1b33ea037ab43e500c | 4,317 | projecteuler | MIT License |
src/day01/Day01.kt | jpveilleux | 573,221,738 | false | {"Kotlin": 42252} | package day01
import readInput
fun main() {
val testInputFileName = "Day01_test";
val inputFileName = "Day01";
val testInput = readInput(testInputFileName)
val input = readInput(inputFileName)
fun part1(input: List<String>, nameOfFile: String) {
getHighestCalCount(input, "$nameOfFile.txt");
}
part1(input, inputFileName);
part1(testInput, testInputFileName);
fun part2(input: List<String>) {
val calTotals = getListOfCaloriesTotals(input);
val total = calTotals.sortedDescending().slice(0..2).sum();
println("Top three elves' total calories: $total")
}
part2(input);
}
private fun getHighestCalCount(input: List<String>, nameOfFile: String) {
var currentCalCount = 0;
var currentHighestCalCount = 0;
for (line in input) {
if (line.isNotEmpty()) {
currentCalCount += line.toInt();
} else {
if (currentHighestCalCount < currentCalCount) {
currentHighestCalCount = currentCalCount;
}
currentCalCount = 0;
}
}
println("The highest calories count in \"$nameOfFile\" is $currentHighestCalCount");
}
private fun getListOfCaloriesTotals(input: List<String>): List<Int> {
val allTotals = arrayListOf<Int>();
var currentCalCount = 0;
for (line in input) {
if (line.isNotEmpty()) {
currentCalCount += line.toInt();
} else {
allTotals.add(currentCalCount);
currentCalCount = 0;
}
}
return allTotals;
}
| 0 | Kotlin | 0 | 0 | 5ece22f84f2373272b26d77f92c92cf9c9e5f4df | 1,569 | jpadventofcode2022 | Apache License 2.0 |
src/Day03.kt | nGoldi | 573,158,084 | false | {"Kotlin": 6839} | fun main() {
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun calculatePriority(char: Char): Int {
return if (char.code >= 92) {
char.code - 96
} else {
char.code - 38
}
}
private fun calculatePriority(backpacks: List<String>): Int {
return calculatePriority(backpacks.map { it.toCharArray().toSet() }.reduce { acc, backpack -> backpack.intersect(acc) }.first())
}
private fun part1(backpacks: List<String>): Int {
return backpacks.sumOf { calculatePriority(it.chunked(it.length / 2)) }
}
private fun part2(backpacks: List<String>): Int {
return backpacks.windowed(3, step = 3).sumOf { calculatePriority(it) }
}
| 0 | Kotlin | 0 | 0 | bc587f433aa38c4d745c09d82b7d231462f777c8 | 712 | advent-of-code | Apache License 2.0 |
src/main/kotlin/io/math/SumOf4Numbers.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.math
import io.utils.runTests
class SumOf4Numbers {
fun execute(input: IntArray, target: Int): List<List<Int>> {
val triples = (input.indices).flatMap { i -> (i + 1 until input.size).map { Triple(i, it, input[i] + input[it]) } }
val map = mutableMapOf<Int, MutableList<Pair<Int, Int>>>()
triples.forEach { (i, j, sum) ->
map.getOrPut(sum) { mutableListOf() }.add(i to j)
}
return triples.flatMap { (i, j, sum) ->
map[target - sum]?.filter { (k, l) -> i != k && i != l && j != l && j != k }?.map { (k, l) ->
listOf(input[i], input[j], input[k], input[l]).sorted()
}?.distinct()
?: emptyList()
}.distinct()
}
}
fun main() {
runTests(listOf(
Triple(intArrayOf(1, 0, -1, 0, -2, 2), 0, listOf(
listOf(-1, 0, 0, 1),
listOf(-2, -1, 1, 2),
listOf(-2, 0, 0, 2))),
Triple(intArrayOf(-3, -2, -1, 0, 0, 1, 2, 3), 0, listOf(
listOf(-3, -2, 2, 3),
listOf(-3, -1, 1, 3),
listOf(-3, 0, 0, 3),
listOf(-3, 0, 1, 2),
listOf(-2, -1, 0, 3),
listOf(-2, -1, 1, 2),
listOf(-2, 0, 0, 2),
listOf(-1, 0, 0, 1)
)),
Triple(intArrayOf(-5, 5, 4, -3, 0, 0, 4, -2), 4, listOf(
listOf(-5, 0, 4, 5),
listOf(-3, -2, 4, 5)
))
)
// ,outputString = { it.joinToString(separator = "\n") { item -> item.toString() } }
) { (input, target, value) -> value.map { it.sorted() } to SumOf4Numbers().execute(input, target).map { it.sorted() } }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,547 | coding | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1675/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1675
import java.util.*
/**
* LeetCode page: [1675. Minimize Deviation in Array](https://leetcode.com/problems/minimize-deviation-in-array/);
*/
class Solution {
/* Complexity:
* Time O(NLogN) and Space O(N);
*/
fun minimumDeviation(nums: IntArray): Int {
/* We build the maxPq from nums, using the original even numbers but doubling the odd numbers.
* Doing so will not affect the result, since we can divide the number back if necessary.
* However, we now reduce two possible operations to one, i.e. division only.
*/
val numMaxPq = buildMaxPqWithAllOddNumbersDoubled(nums)
return findMinimumDeviation(numMaxPq)
}
private fun buildMaxPqWithAllOddNumbersDoubled(numbers: IntArray): PriorityQueue<Int> {
val result = PriorityQueue<Int>(reverseOrder())
for (number in numbers) {
if (number.isOdd()) {
result.offer(number shl 1)
} else {
result.offer(number)
}
}
return result
}
private fun Int.isOdd() = this and 1 == 1
private fun findMinimumDeviation(numMaxPq: PriorityQueue<Int>): Int {
require(numMaxPq.size >= 2)
var currMin = numMaxPq.min()!!
var minDeviation = numMaxPq.peek() - currMin
// If the max number is odd, we can be sure we found the min deviation.
while (!numMaxPq.peek().isOdd()) {
val currMax = numMaxPq.poll()
val halfCurrMax = currMax shr 1
numMaxPq.offer(halfCurrMax)
if (halfCurrMax < currMin) currMin = halfCurrMax
val newDeviation = numMaxPq.peek() - currMin
minDeviation = minOf(minDeviation, newDeviation)
}
return minDeviation
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,827 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/g2401_2500/s2493_divide_nodes_into_the_maximum_number_of_groups/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2401_2500.s2493_divide_nodes_into_the_maximum_number_of_groups
// #Hard #Breadth_First_Search #Graph #Union_Find
// #2023_07_05_Time_862_ms_(100.00%)_Space_58.1_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
fun magnificentSets(n: Int, edges: Array<IntArray>): Int {
val adj: MutableList<MutableList<Int>> = ArrayList()
val visited = IntArray(n + 1)
visited.fill(-1)
for (i in 0..n) {
adj.add(ArrayList())
}
for (edge in edges) {
adj[edge[0]].add(edge[1])
adj[edge[1]].add(edge[0])
}
val comp = IntArray(n + 1)
var count = -1
var ans = 0
for (i in 1..n) {
if (visited[i] == -1) {
count++
comp[count] = bfs(i, adj, visited, count, n)
if (comp[count] == -1) {
return -1
}
} else {
comp[visited[i]] = Math.max(comp[visited[i]], bfs(i, adj, visited, visited[i], n))
}
}
for (group in comp) {
ans += group
}
return ans
}
private fun bfs(start: Int, adj: List<MutableList<Int>>, visited: IntArray, count: Int, n: Int): Int {
val q: Queue<Int> = LinkedList()
visited[start] = count
var ans = 1
val group = IntArray(n + 1)
q.add(start)
group[start] = 1
while (q.isNotEmpty()) {
val node = q.remove()
for (adjN in adj[node]) {
if (group[adjN] == 0) {
visited[adjN] = count
group[adjN] = group[node] + 1
q.add(adjN)
ans = Math.max(ans, group[adjN])
} else if (Math.abs(group[adjN] - group[node]) != 1) {
return -1
}
}
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,948 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/de/dikodam/calendar/Day05.kt | dikodam | 573,126,346 | false | {"Kotlin": 26584} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.executeTasks
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day05().executeTasks()
}
class Day05 : AbstractDay() {
private val inputLines = readInputLines()
private val stackDefinition = inputLines.takeWhile { it.isNotEmpty() }
private val moveCommands = inputLines.drop(stackDefinition.size + 1)
.map { parseMoveCommand(it) }
override fun task1(): String {
val stacks = buildStacks(stackDefinition)
val restackedStacks = moveCommands.fold(stacks) { acc, mc ->
mc.executeCraneMover9000(acc)
acc
}
return restackedStacks
.map { (_, deque) -> deque.removeFirst() }
.joinToString(separator = "", prefix = "", postfix = "")
}
private fun buildStacks(wholeStackDef: List<String>): Map<Int, ArrayDeque<Char>> {
val shortStackDef: List<String> = wholeStackDef.dropLast(1)
val stacks = (1..9).associateWith { ArrayDeque<Char>() }
val stackPositionsInLine = (1..34 step 4)
val stacksWithPositions = stacks.keys.zip(stackPositionsInLine)
for (i in shortStackDef.size - 1 downTo 0) {
val line = shortStackDef[i]
for ((stackNumber, position) in stacksWithPositions) {
val c = line[position]
if (c != ' ') {
stacks[stackNumber]!!.addFirst(c)
}
}
}
return stacks
}
private fun parseMoveCommand(line: String): MoveCommand {
val moveCommandParts = line.split(" ")
val amount = moveCommandParts[1].toInt()
val from = moveCommandParts[3].toInt()
val to = moveCommandParts[5].toInt()
return MoveCommand(amount, from, to)
}
override fun task2(): String {
val stacks = buildStacks(stackDefinition)
val restackedStacks = moveCommands.fold(stacks) { acc, mc ->
mc.executeCraneMover9001(acc)
acc
}
return restackedStacks
.map { (_, deque) -> deque.removeFirst() }
.joinToString(separator = "", prefix = "", postfix = "")
}
}
private data class MoveCommand(val amount: Int, val from: Int, val to: Int) {
fun executeCraneMover9000(stacks: Map<Int, ArrayDeque<Char>>) {
val fromStack = stacks[from]!!
val toStack = stacks[to]!!
repeat(amount) {
val crate = fromStack.removeFirst()
toStack.addFirst(crate)
}
}
fun executeCraneMover9001(stacks: Map<Int, ArrayDeque<Char>>) {
val fromStack = stacks[from]!!
val toStack = stacks[to]!!
val crates = generateSequence { fromStack.removeFirst() }
.take(amount)
.toList()
.reversed()
crates.forEach { crate -> toStack.addFirst(crate) }
}
}
| 0 | Kotlin | 0 | 1 | 3eb9fc6f1b125565d6d999ebd0e0b1043539d192 | 2,920 | aoc2022 | MIT License |
src/Day11.kt | mpythonite | 572,671,910 | false | {"Kotlin": 29542} | fun main() {
class Monkey(var items: ArrayDeque<Long>, val operation: (Long) -> Long, val test: Long, val success: Int, val fail: Int) {
var inspects: Long = 0
}
fun part1(monkeys: List<Monkey>): Long {
for (i in 0 until 20) {
for (currMonkey in monkeys) {
while (currMonkey.items.any()) {
var item = currMonkey.items.removeFirst()
currMonkey.inspects++
item = currMonkey.operation(item)
item /= 3
if (item % currMonkey.test == 0.toLong()) monkeys[currMonkey.success].items.add(item)
else monkeys[currMonkey.fail].items.add(item)
}
}
}
var results = monkeys.map { m -> m.inspects }.sortedByDescending { i -> i }
return results[0] * results[1]
}
fun part2(monkeys: List<Monkey>): Long {
val meditation: Long = monkeys.map {it.test}.reduce(Long::times)
for (i in 0 until 10000) {
for (currMonkey in monkeys) {
while (currMonkey.items.any()) {
var item = currMonkey.items.removeFirst()
currMonkey.inspects++
item = currMonkey.operation(item)
item %= meditation
if (item % currMonkey.test == 0.toLong()) monkeys[currMonkey.success].items.add(item)
else monkeys[currMonkey.fail].items.add(item)
}
}
}
var results = monkeys.map { m -> m.inspects }.sortedByDescending { i -> i }
return results[0] * results[1]
}
val testMonkeys: List<Monkey> =
listOf(
Monkey(ArrayDeque(listOf(79, 98)), {i: Long -> i * 19}, 23, 2, 3),
Monkey(ArrayDeque(listOf(54, 65, 75, 74)), {i: Long -> i + 6}, 19, 2, 0),
Monkey(ArrayDeque(listOf(79, 60, 97)), {i: Long -> i * i}, 13, 1, 3),
Monkey(ArrayDeque(listOf(74)), {i: Long -> i + 3}, 17, 0, 1),
)
// test if implementation meets criteria from the description, like:
// check(part1(testMonkeys) == 10605.toLong())
check(part2(testMonkeys) == 2713310158)
val monkeys: List<Monkey> =
listOf(
)
//println(part1(monkeys))
println(part2(monkeys))
}
| 0 | Kotlin | 0 | 0 | cac94823f41f3db4b71deb1413239f6c8878c6e4 | 2,353 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | MwBoesgaard | 572,857,083 | false | {"Kotlin": 40623} | fun main() {
fun extractCargoLines(input: List<String>): Pair<List<String>, Pair<Int, Int>> {
val cargoLines: MutableList<String> = mutableListOf()
var numOfCargoCols = 0
var numOfRowsProcessed = 0
for ((i, row) in input.withIndex()) {
if (row[1] == '1') {
numOfCargoCols = row.last().toString().toInt()
numOfRowsProcessed = i
break
}
val filteredRow = row
.replace(" ", "x")
.filter { c -> c.isLetter() }
cargoLines.add(filteredRow)
}
return Pair(cargoLines, Pair(numOfCargoCols, numOfRowsProcessed))
}
fun getInitialCargoSetup(input: List<String>): Pair<MutableList<MutableList<String>>, Int> {
val (cargoLines, numberPair) = extractCargoLines(input)
val numOfCargoCols = numberPair.first
val numOfRowsProcessed = numberPair.second
val cargo = mutableListOf<MutableList<String>>()
for (i in 0 until numOfCargoCols) {
cargo.add(mutableListOf())
}
for (line in cargoLines) {
for ((col, char) in line.withIndex()) {
if (char == 'x') {
continue
}
cargo[col].add(char.toString())
}
}
for (line in cargo) {
line.reverse()
}
return Pair(cargo, numOfRowsProcessed)
}
fun moveCargoOneByOne(cargo: MutableList<MutableList<String>>, numberTaken: Int, origin: Int, destination: Int) {
for (move in 0 until numberTaken) {
val elementToMove = cargo[origin].takeLast(1)
if (elementToMove.isEmpty()) {
continue
}
cargo[origin].removeLast()
cargo[destination] += elementToMove
}
}
fun moveCargoInBatches(cargo: MutableList<MutableList<String>>, numberTaken: Int, origin: Int, destination: Int) {
val elementsToMove = cargo[origin].takeLast(numberTaken)
for (x in 0 until numberTaken) {
cargo[origin].removeLast()
}
cargo[destination] += elementsToMove
}
fun part1(input: List<String>): String {
val (cargo, numOfRowsProcessed) = getInitialCargoSetup(input)
for ((i, row) in input.withIndex()) {
if (i <= numOfRowsProcessed + 1) {
continue
}
val instructions = row
.split(" ")
.filter { it.toIntOrNull() != null }
.map { it.toInt() - 1 }
moveCargoOneByOne(cargo, instructions[0] + 1, instructions[1], instructions[2])
}
return cargo.joinToString("") { it.last() }
}
fun part2(input: List<String>): String {
val (cargo, numOfRowsProcessed) = getInitialCargoSetup(input)
for ((i, row) in input.withIndex()) {
if (i <= numOfRowsProcessed + 1) {
continue
}
val instructions = row
.split(" ")
.filter { it.toIntOrNull() != null }
.map { it.toInt() - 1 }
moveCargoInBatches(cargo, instructions[0] + 1, instructions[1], instructions[2])
}
return cargo.joinToString("") { it.last() }
}
printSolutionFromInputLines("Day05", ::part1)
printSolutionFromInputLines("Day05", ::part2)
}
| 0 | Kotlin | 0 | 0 | 3bfa51af6e5e2095600bdea74b4b7eba68dc5f83 | 3,439 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/sk/mkiss/algorithms/dynamic/LongestCommonSubsequence.kt | marek-kiss | 430,858,906 | false | {"Kotlin": 85343} | package sk.mkiss.algorithms.dynamic
import kotlin.math.max
object LongestCommonSubsequence {
fun getSizeOfLongestCommonSubsequence(a: List<Int>, b: List<Int>): Int {
val lcsMemory = mutableMapOf<Pair<Int, Int>, Int>()
lcs(a, b, a.size, b.size, lcsMemory)
return lcsMemory[a.size, b.size]!!
}
fun getLongestCommonSubsequence(a: List<Int>, b: List<Int>): List<Int> {
val lcsMemory = mutableMapOf<Pair<Int, Int>, Int>()
lcs(a, b, a.size, b.size, lcsMemory)
return backtrack(a, b, lcsMemory)
}
private fun lcs(a: List<Int>, b: List<Int>, aSize: Int, bSize: Int, memory: MutableMap<Pair<Int, Int>, Int>): Int {
return memory.getOrPut(Pair(aSize, bSize)) {
if (aSize <= 0 || bSize <= 0) {
0
} else if (a[aSize - 1] != b[bSize - 1]) {
max(lcs(a, b, aSize - 1, bSize, memory), lcs(a, b, aSize, bSize - 1, memory))
} else {
lcs(a, b, aSize - 1, bSize - 1, memory) + 1
}
}
}
private fun backtrack(a: List<Int>, b: List<Int>, memory: Map<Pair<Int, Int>, Int>): List<Int> {
val lcs = mutableListOf<Int>()
var aI = a.size
var bI = b.size
while (aI > 0 && bI > 0) {
when (memory[aI, bI]) {
memory[aI, bI - 1] -> bI -= 1
memory[aI - 1, bI] -> aI -= 1
else -> {
aI -= 1
bI -= 1
if (a[aI] == b[bI]) lcs.add(a[aI])
}
}
}
return lcs.reversed()
}
private operator fun <T> Map<Pair<Int, Int>, T>.get(x: Int, y: Int): T? = get(Pair(x, y))
} | 0 | Kotlin | 0 | 0 | 296cbd2e04a397597db223a5721b6c5722eb0c60 | 1,720 | algo-in-kotlin | MIT License |
src/main/kotlin/recursion/WordSquares.kt | e-freiman | 471,473,372 | false | {"Kotlin": 78010} | package recursion
val squares: MutableList<MutableList<String>> = mutableListOf()
data class TrieNode(val children: MutableMap<Char, TrieNode>)
val root = TrieNode(mutableMapOf())
fun traverse(square: MutableList<String>, cur: TrieNode, word: StringBuilder, words: Array<String>) {
if (word.length == words[0].length) {
square.add(word.toString())
search(square, words)
square.removeAt(square.lastIndex)
}
for (entry in cur.children.entries) {
word.append(entry.key)
traverse(square, entry.value, word, words)
word.deleteCharAt(word.lastIndex)
}
}
fun search(square: MutableList<String>, words: Array<String>) {
val n = square.size
if (square.size == words[0].length) {
squares.add(ArrayList(square))
return
}
// following tries for finding the given prefix of n characters
var cur = root
val sb = StringBuilder()
for (i in 0 until n) {
if (square[i][n] in cur!!.children) {
sb.append(square[i][n])
cur = cur.children[square[i][n]]!!
} else {
break
}
}
// traversing the rest of the trie since all words fit
if (sb.length == n) {
traverse(square, cur, sb, words)
}
}
//O(m^n)
fun wordSquares(words: Array<String>): List<List<String>> {
for(word in words) {
var cur = root
for (ch in word) {
if (ch !in cur.children) {
cur.children[ch] = TrieNode(mutableMapOf())
}
cur = cur.children[ch]!!
}
}
search(ArrayList(words[0].length), words)
return squares
}
fun main() {
println(wordSquares(arrayOf("area","lead","wall","lady","ball")))
}
| 0 | Kotlin | 0 | 0 | fab7f275fbbafeeb79c520622995216f6c7d8642 | 1,733 | LeetcodeGoogleInterview | Apache License 2.0 |
2022/src/main/kotlin/day10_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.IntGrid
import utils.Parser
import utils.Solution
import utils.Vec2i
import utils.cut
import kotlin.math.absoluteValue
fun main() {
Day10Imp.run()
}
object Day10Imp : Solution<List<Day10Imp.Insn>>() {
sealed class Insn {
data class Add(val a: Int) : Insn()
object Nop : Insn()
}
override val name = "day10"
override val parser = Parser.lines.map { lines ->
lines.flatMap {
when (it.trim()) {
"noop" -> listOf(Insn.Nop)
else -> listOf(Insn.Nop, Insn.Add(it.cut(" ").second.toInt()))
}
}
}
override fun part1(input: List<Insn>): Int {
var clock = 1
var x = 1
var answ = 0
for (insn in input) {
if (clock % 20 == 0) {
if (clock == 20 || (clock - 20) % 40 == 0) {
answ += clock * x
}
}
if (insn is Insn.Add) {
x += insn.a
}
clock += 1
}
return answ
}
override fun part2(input: List<Insn>): String {
val screen = IntGrid(40, 6, 0).toMutable()
var clock = 0
var x = 1
for (insn in input) {
val px = Vec2i(clock % 40, clock / 40)
if ((px.x - x).absoluteValue < 2) {
screen[px] = 1
}
if (insn is Insn.Add) {
x += insn.a
}
clock += 1
}
return screen.toString { _, v -> if (v == 1) "#" else " " }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,340 | aoc_kotlin | MIT License |
day22/kotlin/corneil/src/main/kotlin/solution.kt | jensnerche | 317,661,818 | true | {"HTML": 2739009, "Java": 348790, "Kotlin": 271053, "TypeScript": 262310, "Python": 198318, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day22
import com.github.corneil.aoc2019.day22.Instruction.Cut
import com.github.corneil.aoc2019.day22.Instruction.Increment
import com.github.corneil.aoc2019.day22.Instruction.Reverse
import java.io.File
import java.math.BigInteger
infix fun BigInteger.`%%`(b: BigInteger): BigInteger {
val r = this % b
return if (r < BigInteger.ZERO) r + b else r
}
infix fun Long.`%%`(b: Long): Long {
return (this.toBigInteger() `%%` b.toBigInteger()).toLong()
}
sealed class Instruction {
data class Increment(val inc: Int) : Instruction()
data class Cut(val n: Int) : Instruction()
object Reverse : Instruction()
}
fun parse(input: String): Instruction {
val r = mapOf<String, (MatchResult) -> Instruction>(
"deal into new stack" to { _ -> Reverse },
"deal with increment (\\d+)" to { s -> Increment(s.groupValues.get(1).toInt()) },
"cut (-?\\d+)" to { s -> Cut(s.groupValues.get(1).toInt()) }
)
return r.entries.find {
it.key.toRegex().matches(input)
}?.let {
it.value(it.key.toRegex().matchEntire(input)!!)
} ?: error("Could not determine $input")
}
fun reverseIndex(index: Long, deck: Long, iterations: Long = 1L): Long {
return if (iterations % 2L == 0L)
index
else
deck - (index + 1)
}
fun reverse(deck: Array<Int>): Array<Int> {
println("deal into new stack")
val result = Array(deck.size) { -1 }
for (i in 0 until deck.size) {
val newIndex = reverseIndex(i.toLong(), deck.size.toLong())
result[newIndex.toInt()] = deck[i]
}
return result
}
fun cutIndex(index: Long, n: Int, deck: Long, iterations: Long = 1L): Long {
val i = index.toBigInteger()
val cn = n.toBigInteger()
val d = deck.toBigInteger()
val n = iterations.toBigInteger()
return ((n * (i - cn)) `%%` d).toLong()
}
fun cut(deck: Array<Int>, n: Int): Array<Int> {
println("cut $n")
val result = Array(deck.size) { -1 }
for (i in 0 until deck.size) {
val newIndex = cutIndex(i.toLong(), n, deck.size.toLong(), 1)
result[newIndex.toInt()] = deck[i]
}
return result
}
fun incrementIndex(index: Long, inc: Int, deck: Long, iterations: Long = 1L): Long {
if (index == 0L) {
return 0L
}
val n = iterations.toBigInteger()
val i = index.toBigInteger()
val c = inc.toBigInteger()
val d = deck.toBigInteger()
return (n * i * c `%%` d).toLong()
}
fun increment(deck: Array<Int>, inc: Int): Array<Int> {
println("deal with increment $inc")
val result = Array(deck.size) { -1 }
for (i in 0 until deck.size) {
val newIndex = incrementIndex(i.toLong(), inc, deck.size.toLong())
result[newIndex.toInt()] = deck[i]
}
return result
}
fun shuffle(input: String, deck: Array<Int>): Array<Int> {
val instruction = parse(input)
return when (instruction) {
is Reverse -> reverse(deck)
is Increment -> increment(deck, instruction.inc)
is Cut -> cut(deck, instruction.n)
else -> error("Unknown instruction $instruction")
}
}
fun shuffleFrom(lines: List<String>, deck: Array<Int>, printIntermediate: Boolean = false): Array<Int> {
var result = deck
lines.forEach {
val before = result.toList().toSet()
result = shuffle(it, result)
if (printIntermediate) {
println(result.joinToString(","))
}
val after = result.toList().toSet()
require(before == after) {
"Cards missing $before -> $after"
}
}
return result
}
data class Operation(
val deck: BigInteger,
val increment: BigInteger = BigInteger.ONE,
val offset: BigInteger = BigInteger.ZERO
) {
constructor(
deck: Long,
increment: Long = 1L,
offset: Long = 0L
) : this(deck.toBigInteger(), increment.toBigInteger(), offset.toBigInteger())
operator fun times(right: Operation): Operation {
return copy(
increment = increment * right.increment `%%` deck,
offset = ((offset * right.increment `%%` deck) + right.offset) `%%` deck
)
}
fun pow(x: Long): Operation {
require(x >= 0L)
return when {
x == 0L -> Operation(this.deck)
x % 2L == 0L -> (this * this).pow(x / 2L)
else -> this * pow(x - 1L)
}
}
}
fun shuffleOperations(
lines: List<String>,
deck: Long
): Operation {
var r = Operation(deck)
lines.forEach { line ->
println("Reversing $line")
val s = parse(line)
r = when (s) {
is Reverse -> {
r.copy(increment = -r.increment `%%` r.deck, offset = (-r.offset - BigInteger.ONE) `%%` r.deck)
}
is Cut -> {
val n = s.n.toBigInteger()
r.copy(offset = (r.offset - n) `%%` r.deck)
}
is Increment -> {
val inc = s.inc.toBigInteger()
r.copy(
offset = r.offset * inc `%%` r.deck,
increment = r.increment * inc `%%` r.deck
)
}
}
}
return r
}
fun getIndex(s: Operation, index: Long): Long {
val x = index.toBigInteger()
return (((s.increment * x `%%` s.deck) + s.offset) `%%` s.deck).toLong()
}
fun getReverseIndex(s: Operation, index: Long): Long {
require(s.deck.isProbablePrime(10))
return getIndex(s.pow(s.deck.toLong() - 2L), index)
}
fun applyShuffleReverse(lines: List<String>, index: List<Long>, deck: Long, iterations: Long = 1L): List<Long> {
require(deck > 0L) { "Deck must have a positive length not $deck" }
require(iterations > 0L) { "Iteration must be positive not $iterations" }
require(index.all { it >= 0L }) { "Index must be 0 or greater not $index" }
val s = shuffleOperations(lines, deck)
val x = s.pow(iterations)
return index.map {
getReverseIndex(x, it)
}
}
fun applyShuffle(lines: List<String>, index: List<Long>, deck: Long, iterations: Long = 1L): List<Long> {
require(deck > 0L) { "Deck must have a positive length not $deck" }
require(iterations > 0L) { "Iteration must be positive not $iterations" }
require(index.all { it >= 0L }) { "Index must be 0 or greater not $index" }
val s = shuffleOperations(lines, deck)
return index.map {
getIndex(s, it)
}
}
fun main() {
val input = File("input.txt").readLines().map { it.trim() }.filter { it.length > 0 }
require(input.size == 100) { "Expected 100 lines not ${input.size}" }
val deck = (0 until 10007).toList().toTypedArray()
require(deck.indexOf(2019) == 2019)
val result = shuffleFrom(input, deck)
val index = result.indexOf(2019)
val index2 = result.indexOf(2020)
println("Result[2019] = $index, Result[2020] = $index2")
require(index == 7545)
require(index2 == 5078)
// Testing index calculations on same data
val index3 = applyShuffle(input, listOf(2019L, 2020L), deck.size.toLong(), 1L)
require(index3[0] == 7545L) { "Expected ${index3[0]} to be 7545" }
require(index3[1] == 5078L) { "Expected ${index3[1]} to be 5078" }
// Testing reverse on same data
val reverse = applyShuffleReverse(input, listOf(7545L, 5078), deck.size.toLong(), 1L)
val reverseValue = deck[reverse[0].toInt()]
val reverseValue2 = deck[reverse[1].toInt()]
require(reverse.first() == 2019L) { "Expected ${reverse.first()} to be 2019" }
// Large inputs
val largeDeck = 119_315_717_514_047L
val iterations = 101_741_582_076_661L
val largeIndex = applyShuffleReverse(input, listOf(2020L), largeDeck, iterations)
println("Large Number = ${largeIndex.first()}")
require(largeIndex.first() == 12_706_692_375_144L)
}
| 0 | HTML | 0 | 0 | a84c00ddbeb7f9114291125e93871d54699da887 | 7,864 | aoc-2019 | MIT License |
src/Day09.kt | HaydenMeloche | 572,788,925 | false | {"Kotlin": 25699} | fun main() {
val input = readInput("Day09")
val partOnePositions = mutableSetOf<Location>()
val partTwoPositions = mutableSetOf<Location>()
var headLocation = Location(0, 0)
val tails = (0 until 9).map {
Location(0, 0)
}.toMutableList()
input.forEach {
val (direction, amount) = it.split(" ")
when (direction) {
"R" -> {
(0 until amount.toInt()).forEach { _ ->
headLocation = headLocation.moveRight(1)
moveTails(tails, partTwoPositions, headLocation)
partOnePositions.add(tails[0])
}
}
"L" -> {
(0 until amount.toInt()).forEach { _ ->
headLocation = headLocation.moveLeft(1)
moveTails(tails, partTwoPositions, headLocation)
partOnePositions.add(tails[0])
}
}
"U" -> {
(0 until amount.toInt()).forEach { _ ->
headLocation = headLocation.moveUp(1)
moveTails(tails, partTwoPositions, headLocation)
partOnePositions.add(tails[0])
}
}
"D" -> {
(0 until amount.toInt()).forEach { _ ->
headLocation = headLocation.moveDown(1)
moveTails(tails, partTwoPositions, headLocation)
partOnePositions.add(tails[0])
}
}
}
}
println("answer one: ${partOnePositions.size}")
println("answer two: ${partTwoPositions.size}")
}
fun moveTails(tails: MutableList<Location>, partTwoPositions: MutableSet<Location>, headLocation: Location) {
tails.forEachIndexed { index, _ ->
if (index == 0) {
tails[index] = moveTail(headLocation, tails[index])
} else tails[index] = moveTail(tails[index - 1], tails[index])
if (index == tails.size - 1) {
partTwoPositions.add(tails[8])
}
}
}
fun moveTail(headLocation: Location, tailLocation: Location): Location {
var tempLocation = tailLocation
if (!headLocation.withinRange(tailLocation)) {
val moveX: Int
val moveY: Int
if (headLocation.x != tailLocation.x && headLocation.y != tailLocation.y) {
moveX = if (headLocation.x < tailLocation.x) -1 else 1
moveY = if (headLocation.y < tailLocation.y) -1 else 1
tempLocation = tempLocation.moveRight(moveX).moveUp(moveY)
} else if (headLocation.x != tailLocation.x) {
moveX = if (headLocation.x < tailLocation.x) -1 else 1
tempLocation = tempLocation.moveRight(moveX)
} else if (headLocation.y != tailLocation.y) {
moveY = if (headLocation.y < tailLocation.y) -1 else 1
tempLocation = tempLocation.moveUp(moveY)
}
}
return tempLocation
}
data class Location(
val x: Int,
val y: Int
)
fun Location.moveRight(num: Int) = this.copy(x = this.x + num, y = this.y)
fun Location.moveLeft(num: Int) = this.copy(x = this.x - num, y = this.y)
fun Location.moveUp(num: Int) = this.copy(x = this.x, y = this.y + num)
fun Location.moveDown(num: Int) = this.copy(x = this.x, y = this.y - num)
fun Location.withinRange(location: Location): Boolean {
return if (this == location) {
true
} else (this.x + 1 == location.x && this.y == location.y) ||
(this.x - 1 == location.x && this.y == location.y) ||
(this.y + 1 == location.y && this.x == location.x) ||
(this.y - 1 == location.y && this.x == location.x) ||
(this.x + 1 == location.x && this.y + 1 == location.y) ||
(this.x + 1 == location.x && this.y - 1 == location.y) ||
(this.x - 1 == location.x && this.y - 1 == location.y) ||
(this.x - 1 == location.x && this.y + 1 == location.y) ||
(this.y + 1 == location.y && this.x + 1 == location.x) ||
(this.y + 1 == location.y && this.x - 1 == location.x) ||
(this.y - 1 == location.y && this.x - 1 == location.x) ||
(this.y - 1 == location.y && this.x + 1 == location.x)
} | 0 | Kotlin | 0 | 1 | 1a7e13cb525bb19cc9ff4eba40d03669dc301fb9 | 4,230 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxTwinSum.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.Stack
import kotlin.math.max
/**
* 2130. Maximum Twin Sum of a Linked List
* @see <a href="https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/">Source</a>
*/
fun interface MaxTwinSum {
fun pairSum(head: ListNode?): Int
}
/**
* Approach 1: Using List Of Integers
*/
class MaxTwinSumIntList : MaxTwinSum {
override fun pairSum(head: ListNode?): Int {
var current = head
val values: MutableList<Int> = ArrayList()
while (current != null) {
values.add(current.value)
current = current.next
}
var i = 0
var j = values.size - 1
var maximumSum = 0
while (i < j) {
maximumSum = max(maximumSum, values[i] + values[j])
i++
j--
}
return maximumSum
}
}
/**
* Approach 2: Using Stack
*/
class MaxTwinSumStack : MaxTwinSum {
override fun pairSum(head: ListNode?): Int {
var current = head
val st: Stack<Int> = Stack<Int>()
while (current != null) {
st.push(current.value)
current = current.next
}
current = head
val size: Int = st.size
var count = 1
var maximumSum = 0
while (count <= size / 2) {
maximumSum = max(maximumSum, (current?.value ?: 0) + st.peek())
current = current?.next
st.pop()
count++
}
return maximumSum
}
}
/**
* Approach 3: Reverse Second Half In Place
*/
class MaxTwinSumReverse : MaxTwinSum {
override fun pairSum(head: ListNode?): Int {
var slow = head
var fast = head
// Get middle of the linked list.
while (fast?.next != null) {
fast = fast.next?.next
slow = slow?.next
}
// Reverse second half of the linked list.
var nextNode: ListNode?
var prev: ListNode? = null
while (slow != null) {
nextNode = slow.next
slow.next = prev
prev = slow
slow = nextNode
}
var start = head
var maximumSum = 0
while (prev != null) {
maximumSum = max(maximumSum, (start?.value ?: 0) + prev.value)
prev = prev.next
start = start?.next
}
return maximumSum
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,003 | kotlab | Apache License 2.0 |
ImageSegmentation/app/src/main/java/com/example/imagesegmentation/camera/CameraSizes.kt | bbueno5000 | 478,454,063 | false | {"Kotlin": 67304} | package com.example.imagesegmentation.camera
/*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.
*/
import android.graphics.Point
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.params.StreamConfigurationMap
import android.util.Size
import android.view.Display
import kotlin.math.max
import kotlin.math.min
val SIZE_1080P: SmartSize = SmartSize(1920, 1080)
/**
* Returns a [SmartSize] object for the given [Display]
*/
fun getDisplaySmartSize(display: Display): SmartSize {
val outPoint = Point()
display.getRealSize(outPoint)
return SmartSize(outPoint.x, outPoint.y)
}
/**
* Returns the largest available PREVIEW size. For more information, see:
* https://d.android.com/reference/android/hardware/camera2/CameraDevice
*/
fun <T> getPreviewOutputSize(
display: Display, characteristics: CameraCharacteristics, targetClass: Class<T>,
aspectRatio: Size, format: Int? = null): Size {
// Find which is smaller: screen or 1080p
val screenSize = getDisplaySmartSize(display)
val hdScreen = screenSize.long >= SIZE_1080P.long || screenSize.short >= SIZE_1080P.short
val maxSize = if (hdScreen) SIZE_1080P else screenSize
// if image format is provided, use it to determine supported sizes; else use target class
val config = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)!!
if (format == null) {
assert(StreamConfigurationMap.isOutputSupportedFor(targetClass))
} else {
assert(config.isOutputSupportedFor(format))
}
val allSizes = if (format == null) {
config.getOutputSizes(targetClass)
} else {
config.getOutputSizes(format)
}
// get available sizes and sort them by area from largest to smallest
val validSizes = allSizes
.sortedWith(compareBy { it.height * it.width })
.filter { verifyAspectRatio(it.width, it.height, aspectRatio) }
.map { SmartSize(it.width, it.height) }.reversed()
// then, get the largest output size that is smaller or equal than our max size
return validSizes.first { it.long <= maxSize.long && it.short <= maxSize.short }.size
}
/**
* verify that the given width and height are on the expected aspect ratio
*/
fun verifyAspectRatio(width: Int, height: Int, aspectRatio: Size): Boolean {
return (width * aspectRatio.height) == (height * aspectRatio.width)
}
/**
* Helper class used to pre-compute shortest and longest sides of a [Size]
*/
class SmartSize(width: Int, height: Int) {
var size = Size(width, height)
var long = max(size.width, size.height)
var short = min(size.width, size.height)
override fun toString() = "SmartSize(${long}x$short)"
} | 0 | Kotlin | 0 | 0 | 9e7dde119f345ed939c1ece4161bfd4d4ddc8b46 | 3,250 | Image-Segment-App | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem2353/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2353
import java.util.*
/**
* LeetCode page: [2353. Design a Food Rating System](https://leetcode.com/problems/design-a-food-rating-system/);
*/
class FoodRatings(foods: Array<String>, cuisines: Array<String>, ratings: IntArray) {
// entry=(food, (cuisine, rating))
private val menu = hashMapOf<String, Pair<String, Int>>()
// entry=(cuisine, sortedFoods)
private val menuRatings = hashMapOf<String, SortedSet<String>>()
private val ratingCriterion = compareBy<String>(
{ checkNotNull(menu[it]?.second) * -1 }, { it }
)
/* Complexity:
* Time O(NLogN) and Space O(N) where N is the size of foods;
*/
init {
for ((index, food) in foods.withIndex()) {
menu[food] = cuisines[index] to ratings[index]
menuRatings
.computeIfAbsent(cuisines[index]) { TreeSet(ratingCriterion) }
.add(food)
}
}
/* Complexity for each call:
* Time O(LogN) and Space O(1) where N is the size of foods;
*/
fun changeRating(food: String, newRating: Int) {
val cuisine = checkNotNull(menu[food]?.first)
menuRatings[cuisine]?.remove(food)
menu[food] = cuisine to newRating
menuRatings[cuisine]?.add(food)
}
/* Complexity for each call:
* Time O(1) and Space O(1);
*/
fun highestRated(cuisine: String): String {
return checkNotNull(menuRatings[cuisine]?.first())
}
}
/**
* Your FoodRatings object will be instantiated and called as such:
* var obj = FoodRatings(foods, cuisines, ratings)
* obj.changeRating(food,newRating)
* var param_2 = obj.highestRated(cuisine)
*/ | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,698 | hj-leetcode-kotlin | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/SubarraysWithKDistinct.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 992. K 个不同整数的子数组
* 给定一个正整数数组 A,如果 A 的某个子数组中不同整数的个数恰好为 K,则称 A 的这个连续、不一定独立的子数组为好子数组。
*
* (例如,[1,2,3,1,2] 中有 3 个不同的整数:1,2,以及 3。)
*
* 返回 A 中好子数组的数目。
*/
class SubarraysWithKDistinct {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(SubarraysWithKDistinct().solution(intArrayOf(1, 2, 1, 2, 3), 2))
}
}
// 输入:A = [1,2,1,2,3], K = 2
// 输出:7
// 解释:恰好由 2 个不同整数组成的子数组:[1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
fun solution(A: IntArray, K: Int): Int {
return atMostKDistinct(A, K) - atMostKDistinct(A, K - 1)
}
private fun atMostKDistinct(A: IntArray, K: Int): Int {
val size = A.size
var left = 0
var right = 0
var count = 0
var result = 0
val freg = IntArray(size + 1)
while (right < size) {
if (freg[A[right]] == 0) {
count++
}
freg[A[right]]++
right++
while (count > K) {
freg[A[left]]--
if (freg[A[left]] == 0) {
count--
}
left++
}
result += right - left
}
return result
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,537 | daily_algorithm | Apache License 2.0 |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day14/Day14Puzzle1.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day14
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
class Day14Puzzle1 : PuzzleSolver {
override fun solve(inputLines: Sequence<String>) = highestMinusLowestQuantity(inputLines.toList()).toString()
private fun highestMinusLowestQuantity(polymerInstructions: List<String>): Int {
val polymerTemplate = polymerInstructions.first()
val pairInsertionRules = polymerInstructions
.asSequence()
.drop(1)
.filter { it.isNotBlank() }
.map { it.split(" -> ") }
.map { it[0] to it[1] }
.map { (it.first[0] to it.first[1]) to it.second[0] }
.toMap()
val polymer = (0..9)
.fold(polymerTemplate) { previous: String, _: Int -> insertAll(previous, pairInsertionRules) }
val elementCounts = polymer.groupingBy { it }.eachCount()
return elementCounts.values.sorted().let { it.last() - it.first() }
}
private fun insertAll(polymer: String, pairInsertionRules: Map<Pair<Char, Char>, Char>): String {
val newPolymer = StringBuilder()
polymer.windowed(2).forEach {
newPolymer.append(it[0])
pairInsertionRules[it[0] to it[1]]?.let { newElement -> newPolymer.append(newElement) }
}
newPolymer.append(polymer.last())
return newPolymer.toString()
}
} | 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 1,430 | AdventOfCode2021 | Apache License 2.0 |
src/Day01.kt | vitind | 578,020,578 | false | {"Kotlin": 60987} | fun main() {
fun part1(input: List<String>): Int {
var highestCalories = 0
input.fold(0) { totalCalories, value ->
if (value.isNotEmpty()) {
totalCalories + value.toInt()
} else { // value is empty -> check if it is the highest calories
if (highestCalories < totalCalories) {
highestCalories = totalCalories
}
0
}
}
return highestCalories
}
fun part2(input: List<String>): Int {
val allTotalCalories = arrayListOf<Int>()
input.fold(0) { totalCalories, value ->
if (value.isNotEmpty()) {
totalCalories + value.toInt()
} else {
allTotalCalories.add(totalCalories)
0
}
}
return allTotalCalories.sortedDescending().take(3).sum()
}
val input = readInput("Day01")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 2698c65af0acd1fce51525737ab50f225d6502d1 | 1,007 | aoc2022 | Apache License 2.0 |
src/Day07.kt | meierjan | 572,860,548 | false | {"Kotlin": 20066} | import kotlin.math.min
sealed class Command {
data class CD(val path: String) : Command() {
companion object {
const val DISCRIMINATOR = "cd"
fun parse(input: List<String>): CD {
val (_, _, path) = input.first().split(" ")
return CD(path)
}
}
}
data class LS(val files: List<Reference>) : Command() {
companion object {
const val DISCRIMINATOR = "ls"
fun parse(input: List<String>): LS {
return LS(input.drop(1).map {
Reference.parse(it)
})
}
}
}
companion object {
fun parse(input: List<String>): List<Command> {
val inputGroupedByCmd =
input.joinToString("#")
.split("$")
.map {
"$$it".split("#")
.filter {
it.isNotEmpty()
}
}
.drop(1)
return inputGroupedByCmd.map {
val cmdParts = it.first().split(" ")
when (cmdParts[1]) {
LS.DISCRIMINATOR -> LS.parse(it)
CD.DISCRIMINATOR -> CD.parse(it)
else -> throw IllegalArgumentException("${cmdParts[1]} is an unknown discriminator")
}
}
}
}
}
sealed class Reference {
abstract val name: String
abstract val size: Long
abstract var parent: Folder?
data class File(
override val size: Long,
override val name: String,
override var parent: Folder? = null,
) : Reference() {
companion object {
fun parse(string: String): File {
val (size, name) = string.split(" ")
return File(size.toLong(), name)
}
}
override fun toString(): String = name
}
data class Folder(
override val name: String,
var references: List<Reference>? = null,
override var parent: Folder? = null,
) : Reference() {
override val size: Long
get() = references?.sumOf { it.size } ?: 0
override fun toString(): String = name
companion object {
fun parse(string: String): Folder {
val (_, name) = string.split(" ")
return Folder(name)
}
}
}
companion object {
fun parse(string: String): Reference =
when {
string.startsWith("dir") -> Folder.parse(string)
else -> File.parse(string)
}
}
}
object FileTreeBuilder {
fun buildTree(input: List<String>): Reference.Folder {
val cmds = Command.parse(input)
val root = cmds.first() as Command.CD
val rootReference = Reference.Folder(name = root.path)
var currentPointer: Reference.Folder = rootReference
for (cmd in cmds.drop(1)) {
when (cmd) {
is Command.CD -> {
currentPointer = when (cmd.path) {
// move down
".." -> currentPointer.parent!!
// move up
else -> {
currentPointer.references!!
.filterIsInstance<Reference.Folder>()
.first { it.name == cmd.path }
}
}
}
is Command.LS -> {
currentPointer.references = cmd.files
cmd.files.map { it.parent = currentPointer }
}
}
}
return rootReference
}
}
private fun filterBySize(reference: Reference, sizeLimit: Long): Long =
when (reference) {
is Reference.File -> 0
is Reference.Folder -> if (reference.size < sizeLimit) {
reference.size
} else {
0
} + (reference.references?.sumOf { filterBySize(it, sizeLimit) } ?: 0)
}
fun day7_part1(input: List<String>): Long {
val tree = FileTreeBuilder.buildTree(input)
return filterBySize(tree, 100000)
}
private fun getMinSizeAbove(reference: Reference, sizeBarrier: Long, currentMin: Long = Long.MAX_VALUE): Long {
val currentSize = reference.size
return when (reference) {
is Reference.File -> Long.MAX_VALUE
is Reference.Folder -> if (currentSize in sizeBarrier until currentMin) {
min(currentSize, reference.references?.minOf { getMinSizeAbove(it, sizeBarrier, currentMin) } ?: Long.MAX_VALUE)
} else {
reference.references?.minOf { getMinSizeAbove(it, sizeBarrier, currentMin) } ?: Long.MAX_VALUE
}
}
}
fun day7_part2(input: List<String>): Long {
val tree = FileTreeBuilder.buildTree(input)
val diskSpace = 70000000
val spaceNeeded = 30000000
val usedSpace = tree.size
val spaceLeft = diskSpace - usedSpace
val spaceToFree = spaceNeeded - spaceLeft
return getMinSizeAbove(tree, spaceToFree)
}
fun main() {
val testInput = readInput("Day07_1_test")
val realInput = readInput("Day07_1")
check(day7_part1(testInput) == 95437L)
println(day7_part1(realInput))
check(day7_part2(testInput) == 24933642L)
println(day7_part2(realInput))
}
| 0 | Kotlin | 0 | 0 | a7e52209da6427bce8770cc7f458e8ee9548cc14 | 5,467 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/g2001_2100/s2003_smallest_missing_genetic_value_in_each_subtree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2003_smallest_missing_genetic_value_in_each_subtree
// #Hard #Dynamic_Programming #Depth_First_Search #Tree #Union_Find
// #2023_06_23_Time_984_ms_(100.00%)_Space_78.9_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
fun smallestMissingValueSubtree(parents: IntArray, nums: IntArray): IntArray {
val ans = IntArray(parents.size)
val all = arrayOfNulls<Node>(parents.size)
var max = 0
for (i in nums.indices) {
all[i] = Node(i, nums[i])
max = max.coerceAtLeast(nums[i])
}
for (i in 1 until parents.size) {
all[parents[i]]!!.nodes.add(all[i])
}
solve(all[0], ans, UF(++max, nums))
return ans
}
private fun solve(root: Node?, ans: IntArray, uf: UF) {
var max = 1
for (child in root!!.nodes) {
solve(child, ans, uf)
uf.union(root.`val`, child!!.`val`)
max = ans[child.idx].coerceAtLeast(max)
}
while (max <= ans.size && uf.isConnected(max, root.`val`)) {
++max
}
ans[root.idx] = max
}
private class Node internal constructor(var idx: Int, var `val`: Int) {
var nodes: MutableList<Node?> = ArrayList()
}
private class UF internal constructor(n: Int, nums: IntArray) {
var rank: IntArray
var parent: IntArray
init {
rank = IntArray(n)
parent = IntArray(n)
for (m in nums) {
parent[m] = m
}
}
private fun find(x: Int): Int {
if (x == parent[x]) {
return x
}
parent[x] = find(parent[x])
return parent[x]
}
fun union(x: Int, y: Int) {
var x = x
var y = y
x = find(x)
y = find(y)
if (rank[x] > rank[y]) {
parent[y] = x
} else {
parent[x] = y
if (rank[x] == rank[y]) {
rank[y]++
}
}
}
fun isConnected(x: Int, y: Int): Boolean {
return find(x) == find(y)
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,219 | LeetCode-in-Kotlin | MIT License |
Chapter06/RabinKarp.kt | PacktPublishing | 125,371,513 | false | null | fun search(text: String, pattern: String): Int {
val patternLen = pattern.length
val textLen = text.length - patternLen
val patternHash = hash(pattern)
var subText = text.substring(0, patternLen)
var subTextHash = hash(subText)
var isFound = false
if ((patternHash == subTextHash) and subText.equals(pattern)) return 0
for (i in 1..textLen) {
subTextHash = rolledHash(text[i - 1], text[i + patternLen - 1], subTextHash, patternLen)
if ((patternHash == subTextHash) and text.substring(i, i + patternLen).equals(pattern)) return i
}
return -1
}
private fun hash(input: String): Long {
var result = 0L
input.forEachIndexed { index, char ->
result += (char.toDouble() * Math.pow(97.0, index.toDouble())).toLong()
}
return result
}
private fun rolledHash(oldChar: Char, newChar: Char, oldHash: Long, patternLen: Int): Long {
val newHash = (((oldHash - oldChar.toLong()) / 97)
+ newChar.toDouble() * Math.pow(97.0, (patternLen - 1).toDouble())).toLong()
return newHash
}
fun main(args: Array<String>) {
// Testing Hash function
println(hash("hello"))
val output: Long = 104L + 101L * 97L + 108L * 97L * 97L + 108L * 97L * 97L * 97L + 111L * 97L * 97L * 97L * 97L
println(output)
// Testing rolled Hash function
println(hash("he"))
val output1: Long = 104L + 101L * 97L
println(output1)
println(hash("el"))
println(rolledHash('h', 'l', hash("he"), 2))
val output2: Long = 101L + 108L * 97L
println(output2)
println(search("Hello", "el"))
println(search("Hello Kotlin", "owel"))
println(search("Hello", "lo"))
println(search("Hello", "llw"))
println(search("Hello", "llo"))
}
| 0 | Kotlin | 62 | 162 | f125372a286a3bf4f0248db109a7427f6bc643a7 | 1,742 | Hands-On-Data-Structures-and-Algorithms-with-Kotlin | MIT License |
src/main/kotlin/days/Day2.kt | andilau | 726,429,411 | false | {"Kotlin": 37060} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2023/day/2",
date = Date(day = 2, year = 2023)
)
class Day2(input: List<String>) : Puzzle {
private val games = input.map { Game.from(it) }
override fun partOne(): Int = games.filter { it.possible() }.sumOf { it.id }
override fun partTwo(): Int = games.sumOf { it.multiple() }
data class Game(val id: Int, val sets: Map<String, Int>) {
fun possible(): Boolean = sets.run {
getOrDefault("red", 0) <= 12 &&
getOrDefault("green", 0) <= 13 &&
getOrDefault("blue", 0) <= 14
}
fun multiple(): Int = sets.run {
getOrDefault("red", 1) *
getOrDefault("green", 1) *
getOrDefault("blue", 1)
}
companion object {
fun from(record: String) = Game(
record.substringBefore(':').substringAfter("Game ").toInt(),
record.substringAfter(": ").split("; ")
.map { it.split(", ").associate { it.split(" ").let { it[1] to it[0].toInt() } } }
.reduce { m1, m2 ->
(m1.asSequence() + m2.asSequence()).groupBy({ it.key }, { it.value })
.mapValues { it.value.max() }
}
)
}
}
}
| 3 | Kotlin | 0 | 0 | 9a1f13a9815ab42d7fd1d9e6048085038d26da90 | 1,401 | advent-of-code-2023 | Creative Commons Zero v1.0 Universal |
Retos/Reto #38 - LAS SUMAS [Media]/kotlin/pisanowp.kt | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | fun main() {
/*
* Reto #38 25/09/2023 LAS SUMAS
*
* Crea una función que encuentre todas las combinaciones de los números
* de una lista que suman el valor objetivo.
* - La función recibirá una lista de números enteros positivos
* y un valor objetivo.
* - Para obtener las combinaciones sólo se puede usar
* una vez cada elemento de la lista (pero pueden existir
* elementos repetidos en ella).
* - Ejemplo: Lista = [1, 5, 3, 2], Objetivo = 6
* Soluciones: [1, 5] y [1, 3, 2] (ambas combinaciones suman 6)
* (Si no existen combinaciones, retornar una lista vacía)
*
*/
// val lista = listOf(1, 5, 3)
// val objetivo = 6
val lista = listOf(1, 5, 3, 2,4,1)
val objetivo = 7
println( "Lista => ${lista}")
println( "Combinaciones para conseguir $objetivo => ${getCombinaciones(lista, objetivo)}" )
}
fun getCombinaciones(lista: List<Int>, objetivo: Int): List<List<Int>> {
var combinaciones = mutableListOf<List<Int>>()
combinaciones.add(lista)
// Voy a crear una lista de listas con TODAS las posibles combinaciones de números
combinaciones = getAllCombinaciones(combinaciones)
// Ahora solo me quedo con aquellas, cuya suma de elementos sea igual al objetivo
val aux = combinaciones.filter{
it.sum() == objetivo
}
// ... Y quito los duplciados
val conjuntoDeListas = aux.toSet()
val listaSinDuplicados = conjuntoDeListas.toList()
// Devuelvo el resutlado
return listaSinDuplicados
}
fun getAllCombinaciones(combinaciones: MutableList<List<Int>>): MutableList<List<Int>> {
var retornoCombinaciones = mutableListOf<List<Int>>()
//println ("getAllCombinaciones => ${combinaciones}")
if ( ( combinaciones.size >= 1 )
&& ( combinaciones[0].size > 2 ) ){
combinaciones.forEach(){
retornoCombinaciones.add(it)
val dummyVariaciones = getCombinacion(it)
//println(dummyVariaciones)
dummyVariaciones.forEach(){
retornoCombinaciones.add(it)
getAllCombinaciones(mutableListOf<List<Int>>(it)).forEach(){
retornoCombinaciones.add(it)
}
}
}
}
return retornoCombinaciones
}
fun getCombinacion(lista: List<Int>): List<List<Int>> {
var combinacion = mutableListOf<Int>()
var combinaciones = mutableListOf<List<Int>>()
(0 until lista.size).forEach() { i ->
(0 until lista.size).forEach() { j ->
if ( i!=j ){
// Para no tomar el valor guia
combinacion.add( lista[j])
}
}
combinaciones.add(combinacion)
combinacion = mutableListOf<Int>()
}
return combinaciones
} | 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 2,821 | retos-programacion-2023 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.