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/Day22.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | enum class Direction {
UP, DOWN, LEFT, RIGHT;
fun getRightDirection(): Direction {
return when (this) {
UP -> RIGHT
DOWN -> LEFT
RIGHT -> DOWN
LEFT -> UP
}
}
fun getLeftDirection(): Direction {
return when (this) {
RIGHT -> UP
LEFT -> DOWN
DOWN -> RIGHT
UP -> LEFT
}
}
}
class State22(val currentDir: Direction, val currentPos: Position, val grid: MutableList<MutableList<Char>>)
class Square(val minPos: Position, val maxPos: Position)
class Day22 {
private val NOTHING = ' '
private val EMPTY = '.'
private val WALL = '#'
fun part1(input: List<String>): Int {
val grid = mutableListOf<MutableList<Char>>()
val commandsString = input.last()
val steps = commandsString.split('L', 'R')
val turns = commandsString.split(Regex("[0-9]+")).filter { it.isNotEmpty() }
val commands = mutableListOf<String>()
for (i in steps.indices) {
commands.add(steps[i])
if (i < turns.size)
commands.add(turns[i])
}
println(commands)
val longestRow = input.subList(0, input.size - 2).maxOf { it.length }
for (line in input.subList(0, input.size - 2)) {
val row = CharArray(longestRow) { ' ' }
for (i in line.indices) {
row[i] = line[i]
}
grid.add(row.toMutableList())
}
val currentPos = Position(input[0].indexOfFirst { it == EMPTY }, 0)
var state = State22(Direction.RIGHT, currentPos, grid)
for (command in commands) {
// for (y in 0 until grid.size) {
// for (x in 0 until grid[0].size) {
// if (x == state.currentPos.x && y == state.currentPos.y) {
// print("A")
// } else {
// print(grid[y][x])
// }
// }
// println()
// }
// println()
val step = command.toIntOrNull()
if (step != null) {
repeat(step) {
state = stepInCurrentDirection(state)
}
} else {
state = changeDirection(command, state)
}
}
return 1000 * (state.currentPos.y + 1) + 4 * (state.currentPos.x + 1) + getFacingScore(state.currentDir)
}
private fun getFacingScore(currentDir: Direction): Int {
return when (currentDir) {
Direction.UP -> 3
Direction.DOWN -> 1
Direction.RIGHT -> 0
Direction.LEFT -> 2
}
}
private fun changeDirection(dir: String, state: State22): State22 {
if (dir == "L") {
return State22(state.currentDir.getLeftDirection(), state.currentPos, state.grid)
} else if (dir == "R") {
return State22(state.currentDir.getRightDirection(), state.currentPos, state.grid)
}
throw RuntimeException("Invalid turn direction")
}
private fun stepInCurrentDirection(state: State22): State22 {
val grid = state.grid
val currentPos = state.currentPos
when (state.currentDir) {
Direction.UP -> {
return if (currentPos.y - 1 < 0 || grid[currentPos.y - 1][currentPos.x] == NOTHING) {
val newPos = findMaxYInColumnOrSameIfWall(currentPos, grid)
State22(state.currentDir, newPos, state.grid)
} else if (grid[currentPos.y - 1][currentPos.x] == WALL) {
state
} else {
State22(state.currentDir, Position(currentPos.x, currentPos.y - 1), state.grid)
}
}
Direction.DOWN -> {
return if (currentPos.y + 1 == grid.size || grid[currentPos.y + 1][currentPos.x] == NOTHING) {
val newPos = findMinYInColumnOrSameIfWall(currentPos, grid)
State22(state.currentDir, newPos, state.grid)
} else if (grid[currentPos.y + 1][currentPos.x] == WALL) {
state
} else {
State22(state.currentDir, Position(currentPos.x, currentPos.y + 1), state.grid)
}
}
Direction.LEFT -> {
return if (currentPos.x - 1 < 0 || grid[currentPos.y][currentPos.x - 1] == NOTHING) {
val newPos = findMaxXInRowOrSameIfWall(currentPos, grid[currentPos.y])
State22(state.currentDir, newPos, state.grid)
} else if (grid[currentPos.y][currentPos.x - 1] == WALL) {
state
} else {
State22(state.currentDir, Position(currentPos.x - 1, currentPos.y), state.grid)
}
}
Direction.RIGHT -> {
return if (currentPos.x + 1 == grid[currentPos.y].size || grid[currentPos.y][currentPos.x + 1] == NOTHING) {
val newPos = findMinXInRowOrSameIfWall(currentPos, grid[currentPos.y])
State22(state.currentDir, newPos, state.grid)
} else if (grid[currentPos.y][currentPos.x + 1] == WALL) {
state
} else {
State22(state.currentDir, Position(currentPos.x + 1, currentPos.y), state.grid)
}
}
}
}
private fun findMaxXInRowOrSameIfWall(currentPos: Position, row: MutableList<Char>): Position {
for (x in row.size - 1 downTo 0) {
if (row[x] == EMPTY) {
return Position(x, currentPos.y)
}
if (row[x] == WALL) {
return currentPos
}
}
return currentPos
}
private fun findMinXInRowOrSameIfWall(currentPos: Position, row: MutableList<Char>): Position {
for (x in 0 until row.size) {
if (row[x] == EMPTY) {
return Position(x, currentPos.y)
}
if (row[x] == WALL) {
return currentPos
}
}
return currentPos
}
private fun findMaxYInColumnOrSameIfWall(currentPos: Position, grid: MutableList<MutableList<Char>>): Position {
for (y in grid.size - 1 downTo 0) {
if (grid[y][currentPos.x] == EMPTY) {
return Position(currentPos.x, y)
}
if (grid[y][currentPos.x] == WALL) {
return currentPos
}
}
return currentPos
}
private fun findMinYInColumnOrSameIfWall(currentPos: Position, grid: MutableList<MutableList<Char>>): Position {
for (y in 0 until grid.size) {
if (grid[y][currentPos.x] == EMPTY) {
return Position(currentPos.x, y)
}
if (grid[y][currentPos.x] == WALL) {
return currentPos
}
}
return currentPos
}
private val A = Square(Position(50, 0), Position(99, 49))
private val B = Square(Position(100, 0), Position(149, 49))
private val C = Square(Position(50, 50), Position(99, 99))
private val D = Square(Position(0, 100), Position(49, 149))
private val E = Square(Position(50, 100), Position(99, 149))
private val F = Square(Position(0, 150), Position(49, 199))
fun part2(input: List<String>): Int {
val grid = mutableListOf<MutableList<Char>>()
val commandsString = input.last()
val steps = commandsString.split('L', 'R')
val turns = commandsString.split(Regex("[0-9]+")).filter { it.isNotEmpty() }
val commands = mutableListOf<String>()
for (i in steps.indices) {
commands.add(steps[i])
if (i < turns.size)
commands.add(turns[i])
}
println(commands)
val longestRow = input.subList(0, input.size - 2).maxOf { it.length }
for (line in input.subList(0, input.size - 2)) {
val row = CharArray(longestRow) { ' ' }
for (i in line.indices) {
row[i] = line[i]
}
grid.add(row.toMutableList())
}
val currentPos = Position(input[0].indexOfFirst { it == EMPTY }, 0)
var state = State22(Direction.RIGHT, currentPos, grid)
for (y in 0 until grid.size) {
print(y)
for (x in 0 until grid[0].size) {
if (x == state.currentPos.x && y == state.currentPos.y) {
print("A")
} else {
print(grid[y][x])
}
}
println()
}
println()
println(commands)
for (command in commands) {
val step = command.toIntOrNull()
if (step != null) {
repeat(step) {
state = stepInCurrentDirection2(state)
// for (y in 0 until grid.size) {
// print(y)
// for (x in 0 until grid[0].size) {
// if (x == state.currentPos.x && y == state.currentPos.y) {
// print("A")
// } else {
// print(grid[y][x])
// }
// }
// println()
// }
// println()
}
} else {
state = changeDirection(command, state)
}
}
return 1000 * (state.currentPos.y + 1) + 4 * (state.currentPos.x + 1) + getFacingScore(state.currentDir)
}
private fun stepInCurrentDirection2(state: State22): State22 {
val grid = state.grid
val currentPos = state.currentPos
when (state.currentDir) {
Direction.UP -> {
return if (currentPos.y - 1 < 0 || grid[currentPos.y - 1][currentPos.x] == NOTHING) {
val newPos: Position
val newDirection: Direction
if (currentPos.y == B.minPos.y && currentPos.x >= B.minPos.x) { // B -> F ok
newPos = Position(currentPos.x % 50, F.maxPos.y)
newDirection = Direction.UP
} else if (currentPos.y == A.minPos.y && currentPos.x >= A.minPos.x) { // A -> F ok
newPos = Position(F.minPos.x, F.minPos.y + currentPos.x % 50)
newDirection = Direction.RIGHT
} else { // D -> C ok
newPos = Position(C.minPos.x, C.minPos.y + currentPos.x % 50)
newDirection = Direction.RIGHT
}
if (grid[newPos.y][newPos.x] == WALL) {
state
} else {
State22(newDirection, newPos, state.grid)
}
} else if (grid[currentPos.y - 1][currentPos.x] == WALL) {
state
} else {
State22(state.currentDir, Position(currentPos.x, currentPos.y - 1), state.grid)
}
}
Direction.DOWN -> {
return if (currentPos.y + 1 == grid.size || grid[currentPos.y + 1][currentPos.x] == NOTHING) {
val newPos: Position
val newDirection: Direction
if (currentPos.y == B.maxPos.y && currentPos.x >= B.minPos.x) { // B -> C ok
newPos = Position(C.maxPos.x, C.minPos.y + currentPos.x % 50)
newDirection = Direction.LEFT
} else if (currentPos.y == E.maxPos.y && currentPos.x >= E.minPos.x) { // E -> F ok
newPos = Position(F.maxPos.x, F.minPos.y + currentPos.x % 50)
newDirection = Direction.LEFT
} else { // F -> B ok
newPos = Position(B.minPos.x + currentPos.x % 50, B.minPos.y)
newDirection = Direction.DOWN
}
if (grid[newPos.y][newPos.x] == WALL) {
state
} else {
State22(newDirection, newPos, state.grid)
}
} else if (grid[currentPos.y + 1][currentPos.x] == WALL) {
state
} else {
State22(state.currentDir, Position(currentPos.x, currentPos.y + 1), state.grid)
}
}
Direction.LEFT -> {
return if (currentPos.x - 1 < 0 || grid[currentPos.y][currentPos.x - 1] == NOTHING) {
val newPos: Position
val newDirection: Direction
if (currentPos.x == A.minPos.x && currentPos.y <= A.maxPos.y) { // A -> D ok
newPos = Position(D.minPos.x, D.maxPos.y - currentPos.y % 50)
newDirection = Direction.RIGHT
} else if (currentPos.x == C.minPos.x && currentPos.y <= C.maxPos.y) { // C -> D ok
newPos = Position(currentPos.y % 50, D.minPos.y)
newDirection = Direction.DOWN
} else if (currentPos.x == D.minPos.x && currentPos.y <= D.maxPos.y) { // D -> A ok
newPos = Position(A.minPos.x, A.maxPos.y - currentPos.y % 50)
newDirection = Direction.RIGHT
} else { // F -> A ok
newPos = Position(A.minPos.x + currentPos.y % 50, A.minPos.y)
newDirection = Direction.DOWN
}
if (grid[newPos.y][newPos.x] == WALL) {
state
} else {
State22(newDirection, newPos, state.grid)
}
} else if (grid[currentPos.y][currentPos.x - 1] == WALL) {
state
} else {
State22(state.currentDir, Position(currentPos.x - 1, currentPos.y), state.grid)
}
}
Direction.RIGHT -> {
return if (currentPos.x + 1 == grid[currentPos.y].size || grid[currentPos.y][currentPos.x + 1] == NOTHING) {
val newPos: Position
val newDirection: Direction
if (currentPos.x == B.maxPos.x && currentPos.y <= B.maxPos.y) { // B -> E ok
newPos = Position(E.maxPos.x, E.maxPos.y - currentPos.y % 50)
newDirection = Direction.LEFT
} else if (currentPos.x == C.maxPos.x && currentPos.y <= C.maxPos.y) { // C -> B ok
newPos = Position(B.minPos.x + currentPos.y % 50, B.maxPos.y)
newDirection = Direction.UP
} else if (currentPos.x == E.maxPos.x && currentPos.y <= E.maxPos.y) { // E -> B ok
newPos = Position(B.maxPos.x, B.maxPos.y - currentPos.y % 50)
newDirection = Direction.LEFT
} else { // F -> E
newPos = Position(E.minPos.x + currentPos.y % 50, E.maxPos.y)
newDirection = Direction.UP
}
if (grid[newPos.y][newPos.x] == WALL) {
state
} else {
State22(newDirection, newPos, state.grid)
}
} else if (grid[currentPos.y][currentPos.x + 1] == WALL) {
state
} else {
State22(state.currentDir, Position(currentPos.x + 1, currentPos.y), state.grid)
}
}
}
}
}
fun main() {
val input = readInput("input22_1")
//println(Day22().part1(input))
println(Day22().part2(input))
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 16,100 | advent-of-code | Apache License 2.0 |
src/main/kotlin/y2023/day04/Day04.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2023.day04
import kotlin.math.pow
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
data class ScratchCard(
val winningNumber: Set<Int>,
val drawnNumbers: Set<Int>,
var copies: Int,
)
fun input() =
AoCGenerics.getInputLines("/y2023/day04/input.txt")
.map {
val winning = it.split(":")[1].split("|")[0]
val drawn = it.split(":")[1].split("|")[1]
ScratchCard(
copies = 1,
winningNumber = winning.trim().split(" ").filter { number -> number != "" }.map { number -> number.trim().toInt() }.toSet(),
drawnNumbers = drawn.trim().split(" ").filter { number -> number != "" }.map { number -> number.trim().toInt() }.toSet()
)
}
fun part1() =
input().sumOf { card ->
val matches = card.drawnNumbers.intersect(card.winningNumber)
when {
matches.isEmpty() -> 0.0
else -> 2.0.pow((matches.size - 1).toDouble())
}
}.toInt()
fun part2(): Int {
val cards = input()
cards.forEachIndexed { index, card ->
val matches = card.winningNumber.intersect(card.drawnNumbers).size
repeat(matches) {
if (index + 1 + it < cards.size) {
cards[index + 1 + it].copies += card.copies
}
}
}
return cards.sumOf { it.copies }
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 1,443 | AdventOfCode | MIT License |
src/main/kotlin/days/Day9.kt | jgrgt | 433,952,606 | false | {"Kotlin": 113705} | package days
import kotlin.streams.toList
class Day9 : Day(9) {
override fun runPartOne(lines: List<String>): Any {
// let's add a border of 9's
val firstLine = lines[0]
val width: Int = firstLine.length
val heightMap: List<List<Int>> = buildHeightMap(lines)
val lowSpots = (1..width).flatMap { y ->
(1..lines.size).mapNotNull { x ->
val here = heightMap[x][y]
val above = heightMap[x][y - 1]
val below = heightMap[x][y + 1]
val left = heightMap[x - 1][y]
val right = heightMap[x + 1][y]
if (here < above && here < below && here < left && here < right) {
here
} else {
null
}
}
}
return lowSpots.sum() + lowSpots.size
}
override fun runPartTwo(lines: List<String>): Any {
// let's add a border of 9's
val firstLine = lines[0]
val width: Int = firstLine.length
val heightMap: List<List<Int>> = buildHeightMap(lines)
val lowSpotCoordinates = (1..width).flatMap { y ->
(1..lines.size).mapNotNull { x ->
val here = heightMap[x][y]
val above = heightMap[x][y - 1]
val below = heightMap[x][y + 1]
val left = heightMap[x - 1][y]
val right = heightMap[x + 1][y]
if (here < above && here < below && here < left && here < right) {
x to y
} else {
null
}
}
}
val basinSizes = lowSpotCoordinates.map { (x, y) ->
basinSize(heightMap, x, y)
}.sorted().reversed()
return basinSizes[0] * basinSizes[1] * basinSizes[2]
}
fun basinSize(heightMap: List<List<Int>>, x: Int, y: Int): Int {
val start = Point(x, y)
val covered = mutableSetOf(start)
var newMembers = newMembers(heightMap, start)
while (newMembers.isNotEmpty()) {
covered.addAll(newMembers)
newMembers = newMembers.map { newMembers(heightMap, it) }.fold(emptySet()) { acc, m -> acc.union(m) }
newMembers = newMembers.subtract(covered)
covered.addAll(newMembers)
}
return covered.size
}
fun newMembers(heightMap: List<List<Int>>, p: Point): Set<Point> {
val candidates = listOf(p.up(), p.down(), p.left(), p.right())
return candidates.filter { (x, y) ->
heightMap[x][y] != 9
}.toSet()
}
private fun buildHeightMap(lines: List<String>): List<List<Int>> {
val width: Int = lines[0].length
val border = listOf(9) + List(width) { 9 } + listOf(9)
return listOf(border) + lines.map { line ->
val heights = line.trim().chars().map { char ->
char - '0'.code
}.toList()
listOf(9) + heights + listOf(9)
} + listOf(border)
}
data class Point(val x: Int, val y: Int) {
fun up(): Point {
return Point(x, y - 1)
}
fun down(): Point {
return Point(x, y + 1)
}
fun left(): Point {
return Point(x - 1, y)
}
fun right(): Point {
return Point(x + 1, y)
}
}
}
| 0 | Kotlin | 0 | 0 | 6231e2092314ece3f993d5acf862965ba67db44f | 3,393 | aoc2021 | Creative Commons Zero v1.0 Universal |
advent-of-code/src/main/kotlin/DayThirteen.kt | pauliancu97 | 518,083,754 | false | {"Kotlin": 36950} | typealias RelationshipsMap = Map<String, Map<String, Int>>
class DayThirteen {
data class Input(
val mainPerson: String,
val secondaryPerson: String,
val happinessUnits: Int
) {
companion object {
val GAIN_REGEX = """([a-zA-Z]+) would gain (\d+) happiness units by sitting next to ([a-zA-Z]+)\."""
.toRegex()
val LOSE_REGEX = """([a-zA-Z]+) would lose (\d+) happiness units by sitting next to ([a-zA-Z]+)\."""
.toRegex()
}
}
private fun String.toInput(): Input? {
val (happinessUnitsSign, regex) = when {
Input.GAIN_REGEX.matches(this) -> 1 to Input.GAIN_REGEX
Input.LOSE_REGEX.matches(this) -> -1 to Input.LOSE_REGEX
else -> return null
}
val matchResult = regex.matchEntire(this) ?: return null
val mainPerson = matchResult.groupValues.getOrNull(1) ?: return null
val happinessUnits = matchResult.groupValues.getOrNull(2)?.toIntOrNull()?.times(happinessUnitsSign) ?:
return null
val secondaryPerson = matchResult.groupValues.getOrNull(3) ?: return null
return Input(mainPerson, secondaryPerson, happinessUnits)
}
private fun getRelationshipsForPerson(person: String, inputs: List<Input>): Map<String, Int> =
inputs
.mapNotNull { input ->
if (input.mainPerson == person) {
input.secondaryPerson to input.happinessUnits
} else {
null
}
}
.toMap()
private fun getRelationshipMap(inputs: List<Input>): RelationshipsMap {
val persons = inputs.flatMap { listOf(it.mainPerson, it.secondaryPerson) }.distinct()
return persons.associateWith { person ->
getRelationshipsForPerson(person, inputs)
}
}
private fun readInputs(path: String) =
readLines(path).mapNotNull { it.toInput() }
private fun getCostOfSeating(seating: List<String>, relationshipsMap: RelationshipsMap): Int {
var cost = 0
for ((index, person) in seating.withIndex()) {
val firstNeighbour = if (index == 0) {
seating.last()
} else {
seating[index - 1]
}
val secondNeighbour = if (index == seating.size - 1) {
seating.first()
} else {
seating[index + 1]
}
cost += relationshipsMap[person]?.getOrDefault(firstNeighbour, 0) ?: 0
cost += relationshipsMap[person]?.getOrDefault(secondNeighbour, 0) ?: 0
}
return cost
}
private fun getOptimalTotalHappiness(relationshipsMap: RelationshipsMap): Int {
val persons = relationshipsMap.keys.toList()
return getPermutations(persons).maxOfOrNull { seating -> getCostOfSeating(seating, relationshipsMap) } ?: 0
}
private fun getOptimalTotalHappinessWithExtraPerson(relationshipsMap: RelationshipsMap): Int {
val persons = relationshipsMap.keys.toList() + "Paul"
return getPermutations(persons).maxOfOrNull { seating -> getCostOfSeating(seating, relationshipsMap) } ?: 0
}
fun solvePartOne() {
val inputs = readInputs("day_thirteen.txt")
val relationshipsMap = getRelationshipMap(inputs)
val optimalTotalHappiness = getOptimalTotalHappiness(relationshipsMap)
println(optimalTotalHappiness)
}
fun solvePartTwo() {
val inputs = readInputs("day_thirteen.txt")
val relationshipsMap = getRelationshipMap(inputs)
val optimalTotalHappiness = getOptimalTotalHappinessWithExtraPerson(relationshipsMap)
println(optimalTotalHappiness)
}
}
fun main() {
DayThirteen().solvePartTwo()
} | 0 | Kotlin | 0 | 0 | 3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6 | 3,821 | advent-of-code-2015 | MIT License |
src/Day09.kt | kecolk | 572,819,860 | false | {"Kotlin": 22071} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class Move(val move: Char, val count: Int)
data class Knot(var x: Int = 0, var y: Int = 0)
fun parseInput(input: List<String>): List<Move> = input.map {
val parts = it.split(" ")
Move(parts[0].first(), parts[1].toInt())
}
fun shouldMoveKnot(head: Knot, tail: Knot): Boolean =
abs(head.y - tail.y) > 1 || abs(head.x - tail.x) > 1
fun moveTail(head: Knot, tail: Knot) {
if (shouldMoveKnot(head, tail)) {
tail.x += (head.x - tail.x).sign
tail.y += (head.y - tail.y).sign
}
}
fun executeMoves(moves: List<Move>, numberOfKnots: Int): Int {
val knots = List(numberOfKnots) { Knot() }
val visited = HashSet<Int>()
moves.forEach { move ->
for (i in 0 until move.count) {
when (move.move) {
'R' -> knots.first().x += 1
'L' -> knots.first().x -= 1
'U' -> knots.first().y += 1
'D' -> knots.first().y -= 1
}
knots.windowed(2, 1) {
moveTail(it.first(), it.last())
}
knots.last().apply {
visited.add(1000 * x + y)
}
}
}
return visited.count()
}
val testMoves = parseInput(readTextInput("Day09_test"))
val testMoves2 = parseInput(readTextInput("Day09_test2"))
val moves = parseInput(readTextInput("Day09"))
check(executeMoves(testMoves, 2) == 13)
check(executeMoves(testMoves2, 10) == 36)
println(executeMoves(moves, 2))
println(executeMoves(moves, 10))
}
| 0 | Kotlin | 0 | 0 | 72b3680a146d9d05be4ee209d5ba93ae46a5cb13 | 1,728 | kotlin_aoc_22 | Apache License 2.0 |
src/Day04.kt | carotkut94 | 572,816,808 | false | {"Kotlin": 7508} | fun prepare(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map { line ->
line.split(",")
.let { (left, right) ->
Pair(
left.split("-").let { (first, last) -> first.toInt()..last.toInt() },
right.split("-").let { (first, last) -> first.toInt()..last.toInt() }
)
}
}
}
fun main() {
val rawInput = readInput("Day04")
val processedInput = prepare(rawInput)
println(part1(processedInput))
println(part2(processedInput))
}
fun part1(processedInput: List<Pair<IntRange, IntRange>>): Int {
return processedInput.count { it.first inRange it.second || it.second inRange it.first }
}
fun part2(processedInput: List<Pair<IntRange, IntRange>>): Int {
return processedInput.count { it.first intersect it.second }
}
infix fun IntRange.inRange(other: IntRange): Boolean = other.first in this && other.last in this
infix fun IntRange.intersect(other: IntRange): Boolean =
first in other || last in other || other.first in this || other.last in this
| 0 | Kotlin | 0 | 0 | ef3dee8be98abbe7e305e62bfe8c7d2eeff808ad | 1,098 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Rope.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
Rope.solve()
}
private object Rope {
fun solve() {
val moves = readInput()
println("tail visited ${getTailPath(moves, 10).toSet().size}")
}
private fun readInput(): Sequence<Move> {
return generateSequence(::readLine).map {
val parts = it.split(" ")
val direction = when (parts[0]) {
"U" -> Direction.Up
"D" -> Direction.Down
"L" -> Direction.Left
"R" -> Direction.Right
else -> throw Error("Unexpected direction ${parts[0]}")
}
val length = parts[1].toInt(10)
Move(direction, length)
}
}
private fun getTailPath(moves: Sequence<Move>, ropeSize: Int): List<Pos> {
var head = Pos(0, 0)
var rope = Array<Pos>(ropeSize) { head }
val path = mutableListOf<Pos>()
moves.forEach {
println("Move $it")
for (i in 0 until it.length) {
head = when (it.direction) {
Direction.Up -> Pos(head.x, head.y + 1)
Direction.Down -> Pos(head.x, head.y - 1)
Direction.Left -> Pos(head.x - 1, head.y)
Direction.Right -> Pos(head.x + 1, head.y)
}
var prev = head
rope = Array<Pos>(ropeSize) { j ->
if (i == 0)
head
else {
val pos = nextTailPos(prev, rope[j])
prev = pos
pos
}
}
path.add(rope.last())
}
}
return path
}
private fun nextTailPos(headPos: Pos, tailPos: Pos): Pos {
val dx = headPos.x - tailPos.x
val dy = headPos.y - tailPos.y
if (abs(dx) > 1 || abs(dy) > 1) {
var (x, y) = tailPos
x += sign(dx.toDouble()).toInt()
y += sign(dy.toDouble()).toInt()
return Pos(x, y)
}
return tailPos
}
}
private data class Pos(val x: Int, val y: Int)
private enum class Direction {
Up,
Down,
Left,
Right,
}
private data class Move(val direction: Direction, val length: Int) | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 2,338 | aoc2022 | MIT License |
src/Day09.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | import kotlin.math.abs
import kotlin.math.sign
object Day09 {
const val EXPECTED_PART1_CHECK_ANSWER = 13
const val EXPECTED_PART2_CHECK_ANSWER = 1
const val TAIL_SIZE_PART_2 = 9
}
enum class MovementDirection { U, D, L, R }
fun main() {
data class Location(val x: Int, val y: Int) {
fun move(direction: MovementDirection) = when (direction) {
MovementDirection.U -> copy(y = y + 1)
MovementDirection.D -> copy(y = y - 1)
MovementDirection.R -> copy(x = x + 1)
MovementDirection.L -> copy(x = x - 1)
}
fun moveAfterPrecursor(precursorPosition: Location): Location {
val xDiff = precursorPosition.x - x
val yDiff = precursorPosition.y - y
if (abs(xDiff) > 1 || abs(yDiff) > 1) {
return copy(
x = x + (xDiff + xDiff.sign) / 2,
y = y + (yDiff + yDiff.sign) / 2,
)
}
return this
}
}
fun part1(input: List<String>): Int {
val tailVisitedPositions = mutableSetOf<Location>()
var currentHeadPosition = Location(0, 0)
var currentTailPosition = Location(0, 0)
tailVisitedPositions.add(currentTailPosition)
input.forEach { movement ->
val directionAndSteps = movement.split(" ")
val (direction, steps) = Pair(MovementDirection.valueOf(directionAndSteps[0]), directionAndSteps[1].toInt())
repeat(steps) {
currentHeadPosition = currentHeadPosition.move(direction)
currentTailPosition = currentTailPosition.moveAfterPrecursor(currentHeadPosition)
tailVisitedPositions.add(currentTailPosition)
}
}
return tailVisitedPositions.size
}
fun part2(input: List<String>): Int {
val tailVisitedPositions = mutableSetOf<Location>()
var currentHeadPosition = Location(0, 0)
val trailPositions = MutableList(Day09.TAIL_SIZE_PART_2) { Location(0, 0) }
tailVisitedPositions.add(trailPositions.last())
input.forEach { movement ->
val directionAndSteps = movement.split(" ")
val (direction, steps) = Pair(MovementDirection.valueOf(directionAndSteps[0]), directionAndSteps[1].toInt())
repeat(steps) {
currentHeadPosition = currentHeadPosition.move(direction)
trailPositions.forEachIndexed { idx, trailPosition ->
val newTrailPosition =
trailPosition.moveAfterPrecursor(if (idx == 0) currentHeadPosition else trailPositions[idx - 1])
trailPositions[idx] = newTrailPosition
}
tailVisitedPositions.add(trailPositions.last())
}
}
return tailVisitedPositions.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == Day09.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day09.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 3,250 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day19.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
import java.util.PriorityQueue
// Advent of Code 2022, Day 19: Not Enough Minerals
private const val PATTERN =
"""Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay """ +
"""robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. """ +
"""Each geode robot costs (\d+) ore and (\d+) obsidian."""
data class Costs(val blueprintNum: Int, val oreRobotCost: Int, val clayRobotOreCost: Int, val obsidianRobotOreCost: Int,
val obsidianRobotClayCost: Int, val geodeRobotOreCost: Int, val geodeRobotObsidianCost: Int)
data class OreState(val numOreRobots: Int, val numOre: Int, val numClayRobots: Int, val numClay: Int,
val numObsidianRobots: Int, val numObsidian: Int, val numGeodeRobots: Int, val numGeode: Int, val time: Int)
fun main() {
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
fun solve(input: List<String>, part1: Boolean): Int {
val size = if (part1) input.size else 3
val blueprints = input.take(size).map { line ->
val (blueprint, oreRobotCost, clayRobotCost, obsidianRobotOreCost, obsidianRobotClayCost,
geodeRobotOreCost, geodeRobotObsidianCost) =
requireNotNull(PATTERN.toRegex().matchEntire(line)) { line }.destructured
Costs(blueprint.toInt(), oreRobotCost.toInt(), clayRobotCost.toInt(), obsidianRobotOreCost.toInt(),
obsidianRobotClayCost.toInt(), geodeRobotOreCost.toInt(), geodeRobotObsidianCost.toInt())
}
val stateComparator = Comparator<OreState> { a, b ->
when { // sort descending
a.numGeode != b.numGeode -> b.numGeode - a.numGeode
a.numObsidian != b.numObsidian -> b.numObsidian - a.numObsidian
a.numClay != b.numClay -> b.numClay - a.numClay
else -> b.numOre - a.numOre
}
}
val totalTime = if (part1) 24 else 32
val results = mutableListOf<Int>()
blueprints.forEach { cost->
val states = PriorityQueue(stateComparator)
val bluePrint = cost.blueprintNum
val maxOreCost = maxOf(cost.oreRobotCost, cost.clayRobotOreCost, cost.obsidianRobotOreCost, cost.geodeRobotOreCost)
val initialState = OreState(1, 0, 0, 0, 0, 0, 0, 0, totalTime)
states.add(initialState)
val cache = hashSetOf<OreState>()
var maxGeodes = Int.MIN_VALUE
while (states.isNotEmpty()) {
var state = states.remove()
maxGeodes = maxOf(maxGeodes, state.numGeode)
if (state in cache || state.time <= 0) continue
// if we can't beat the max score, cull it.
// Assume we can make 1 geode robot per term, best case scenario.
val maxGeodesPossible = state.numGeode + (state.numGeodeRobots * state.time) + (state.time * (state.time - 1)) /2
if (maxGeodes > maxGeodesPossible) continue
cache.add(state)
// See https://github.com/ritesh-singh/aoc-2022-kotlin/blob/main/src/day19/Day19.kt
// Reduce state by removing resources not required per minute
if (state.numOre >= state.time * maxOreCost - state.numOreRobots * (state.time - 1)) {
state = state.copy(
numOre = state.time * maxOreCost - state.numOreRobots * (state.time - 1)
)
}
if (state.numClay >= state.time * cost.obsidianRobotClayCost - state.numClayRobots * (state.time - 1)) {
state = state.copy(
numClay = state.time * cost.obsidianRobotClayCost - state.numClayRobots * (state.time - 1)
)
}
if (state.numObsidian >= state.time * cost.geodeRobotObsidianCost - state.numObsidianRobots * (state.time - 1)) {
state = state.copy(
numObsidian = state.time * cost.geodeRobotObsidianCost - state.numObsidianRobots * (state.time - 1)
)
}
// mine more minerals
states.add(
state.copy(
numOre = state.numOreRobots + state.numOre,
numClay = state.numClayRobots + state.numClay,
numObsidian = state.numObsidianRobots + state.numObsidian,
numGeode = state.numGeodeRobots + state.numGeode,
time = state.time - 1
)
)
// Can only make 1 robot per turn
if (state.numOre >= cost.oreRobotCost && state.numOreRobots < maxOreCost) { // make ore robot
val oreLeft = state.numOre - cost.oreRobotCost
states.add(
state.copy(
numOre = state.numOreRobots + oreLeft,
numClay = state.numClayRobots + state.numClay,
numObsidian = state.numObsidianRobots + state.numObsidian,
numGeode = state.numGeodeRobots + state.numGeode,
numOreRobots = state.numOreRobots + 1,
time = state.time - 1
)
)
}
if (state.numOre >= cost.clayRobotOreCost && state.numClayRobots < cost.obsidianRobotClayCost) { // make clay robot
val oreLeft = state.numOre - cost.clayRobotOreCost
states.add(
state.copy(
numOre = state.numOreRobots + oreLeft,
numClay = state.numClayRobots + state.numClay,
numObsidian = state.numObsidianRobots + state.numObsidian,
numGeode = state.numGeodeRobots + state.numGeode,
numClayRobots = state.numClayRobots + 1,
time = state.time - 1
)
)
}
if (state.numOre >= cost.obsidianRobotOreCost && state.numClay >= cost.obsidianRobotClayCost &&
state.numObsidianRobots < cost.geodeRobotObsidianCost) {// make obsidian robot
val oreLeft = state.numOre - cost.obsidianRobotOreCost
val clayLeft = state.numClay - cost.obsidianRobotClayCost
states.add(
state.copy(
numOre = state.numOreRobots + oreLeft,
numClay = state.numClayRobots + clayLeft,
numObsidian = state.numObsidianRobots + state.numObsidian,
numGeode = state.numGeodeRobots + state.numGeode,
numObsidianRobots = state.numObsidianRobots + 1,
time = state.time - 1
)
)
}
if (state.numOre >= cost.geodeRobotOreCost && state.numObsidian >= cost.geodeRobotObsidianCost) { // make geode robot
val oreLeft = state.numOre - cost.geodeRobotOreCost
val obsidianLeft = state.numObsidian - cost.geodeRobotObsidianCost
states.add(
state.copy(
numOre = state.numOreRobots + oreLeft,
numClay = state.numClayRobots + state.numClay,
numObsidian = state.numObsidianRobots + obsidianLeft,
numGeode = state.numGeodeRobots + state.numGeode,
numGeodeRobots = state.numGeodeRobots + 1,
time = state.time - 1
)
)
}
}
if (part1) {
results.add(bluePrint * maxGeodes)
} else {
results.add(maxGeodes)
}
}
return if (part1) results.sum() else results.fold(1) {total, it -> total * it }
}
val testInput = readInput("Day19_test")
check(solve(testInput, true) == 33)
check(solve(testInput, false) == 56 * 62)
val input = readInput("Day19")
println(solve(input, true))
println(solve(input, false))
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 8,508 | AdventOfCode2022 | Apache License 2.0 |
src/Day08.kt | BionicCa | 574,904,899 | false | {"Kotlin": 20039} | fun CharSequence.splitIgnoreEmpty(vararg delimiters: String): List<String> {
return this.split(*delimiters).filter {
it.isNotEmpty()
}
}
fun main() {
fun part1(input: List<String>): Int {
val grid = input.map { it.splitIgnoreEmpty("").map { it.toInt() } }
// Count the number of visible trees
var visibleTrees = 0
for (row in grid.indices) {
for (col in grid[row].indices) {
// check if we are on the edge
if (row == 0 || col == 0 || grid[row].size - 1 == col || grid.size - 1 == row) {
visibleTrees++
continue
}
val isVisible = isTreeVisible(row, col, grid)
if (isVisible) {
visibleTrees++
}
}
}
return visibleTrees
}
fun part2(input: List<String>): Int {
val grid = input.map { it.splitIgnoreEmpty("").map { it.toInt() } }
val scores = mutableListOf<Int>()
for (row in grid.indices) {
for (col in grid[row].indices) {
// skip check if we are on the edge
if (row == 0 || col == 0 || grid[row].size - 1 == col || grid.size - 1 == row) {
continue
}
val score = countScoreOfVisibleTrees(row, col, grid)
scores.add(score)
// println("${grid[row][col]} -> score: $score")
}
}
return scores.max()
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
fun isTreeVisible(i: Int, j: Int, grid: List<List<Int>>): Boolean {
val current = grid[i][j]
val tallestLeft = grid[i].slice(0 until j).max()
val tallestRight = grid[i].slice(j + 1 until grid[i].size).max()
val tallestTop = grid.map { it[j] }.slice(0 until i).max()
val tallestDown = grid.map { it[j] }.slice(i + 1 until grid.size).max()
// check top
return if (grid[i - 1][j] < current && tallestTop < current) true
// check down
else if (grid[i + 1][j] < current && tallestDown < current) true
// check left
else if (grid[i][j - 1] < current && tallestLeft < current) true
// check right
else grid[i][j + 1] < current && tallestRight < current
}
fun countScoreOfVisibleTrees(i: Int, j: Int, grid: List<List<Int>>): Int {
val current = grid[i][j]
var countLeft = 0
var countRight = 0
var countTop = 0
var countDown = 0
for (left in j - 1 downTo 0) {
countLeft++
if (grid[i][left] >= current) break
}
for (right in j + 1 until grid.size) {
countRight++
if (grid[i][right] >= current) break
}
for (top in i - 1 downTo 0) {
countTop++
if (grid[top][j] >= current) break
}
for (down in i + 1 until grid[i].size) {
countDown++
if (grid[down][j] >= current) break
}
return countTop * countLeft * countDown * countRight
} | 0 | Kotlin | 0 | 0 | ed8bda8067386b6cd86ad9704bda5eac81bf0163 | 3,021 | AdventOfCode2022 | Apache License 2.0 |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem023.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.common.properDivisors
/**
* Problem 23
*
* A perfect number is a number for which the sum of its proper divisors is exactly equal to the
* number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
* which means that 28 is a perfect number.
*
* A number n is called deficient if the sum of its proper divisors is less than n and it is called
* abundant if this sum exceeds n.
*
* As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be
* written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that
* all integers greater than 28123 can be written as the sum of two abundant numbers. However, this
* upper limit cannot be reduced any further by analysis even though it is known that the greatest
* number that cannot be expressed as the sum of two abundant numbers is less than this limit.
*
* Find the sum of all the positive integers which cannot be written as the sum of two abundant
* numbers.
*/
class Problem023 : Problem {
private fun Int.isAbundant(): Boolean =
properDivisors.sum() > this
override fun solve(): Long {
val numbers = (0..28123).map { it.isAbundant() }
fun Int.isSumOfTwoAbundant(): Boolean {
for (i in 1 until this) {
if (numbers[i] && numbers[this - i]) {
return true
}
}
return false
}
return (1..28123).filterNot { it.isSumOfTwoAbundant() }
.map { it.toLong() }
.sum()
}
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 1,664 | project-euler | MIT License |
src/Day10.kt | rod41732 | 728,131,475 | false | {"Kotlin": 26028} | fun main() {
fun part1(input: List<String>): Int {
val (startPos, graph) = parseGraph(input)
val distance = bfs(startPos, graph)
return distance.values.max()
}
fun part2(input: List<String>): Int {
val (startPos, graph) = parseGraph(input)
// prune graph so it contains only point in main loop (necessary for correct hit testing)
val distance = bfs(startPos, graph)
val mainLoopPoints = distance.keys.toSet()
val prunedGraph: Graph = graph.filterKeys { mainLoopPoints.contains(it) }
.mapValues { (_, v) -> v.filter { mainLoopPoints.contains(it) }.toSet() }
return input.withIndex().sumOf { (r, row) ->
row.withIndex().count { (c, _) ->
// draw intersecting line upwards at col = c + 0.5, point is inside loop if it intersects a *main loop* pipe there
when {
r to c in mainLoopPoints -> false
else -> {
(0..r - 1).count { testRow ->
prunedGraph.isConnected(testRow to c, testRow to c + 1)
} % 2 == 1
}
}
}
}
}
val testInput = readInput("Day10_test").formatInput()
assertEqual(part1(testInput), 4)
val testInput2 = readInput("Day10_test2").formatInput()
// Example at: Here's the more complex loop again: ...
assertEqual(part1(testInput2), 8)
assertEqual(part2(testInput), 1)
// Example at: To determine whether it's even worth taking the time ...
val testInput3 = readInput("Day10_test3").formatInput()
// Example at: In fact, there doesn't even need to be a full tile path ...
assertEqual(part2(testInput3), 4)
// Example at: Here's a larger example: ...
val testInput4 = readInput("Day10_test4").formatInput()
assertEqual(part2(testInput4), 4)
// Example at: Any tile that isn't part of the main loop can count as being enclosed by the loop...
val testInput5 = readInput("Day10_test5").formatInput()
assertEqual(part2(testInput5), 10)
val input = readInput("Day10").formatInput()
println("Part1: ${part1(input)}") // 6828
println("Part2: ${part2(input)}") // 459
}
private typealias Point = Pair<Int, Int>
private typealias Graph = Map<Point, Set<Point>>
private typealias MutableGraph = MutableMap<Point, MutableSet<Point>>
// replace chars with box drawing to ease debugging
private val PIPE_SE = '┌'
private val PIPE_SW = '┐'
private val PIPE_NE = '└'
private val PIPE_NW = '┘'
private val PIPE_NS = '│'
private val PIPE_EW = '─'
private val replaceMap = "F7LJ|-".zip("┌┐└┘│─").toMap()
private fun String.replaceWithBoxDrawing(): String = this.map {
replaceMap.getOrDefault(it, it)
}.joinToString("")
private fun List<String>.formatInput() = map { it.replaceWithBoxDrawing() }
private fun Pair<Int, Int>.south() = Pair(first + 1, second)
private fun Pair<Int, Int>.north() = Pair(first - 1, second)
private fun Pair<Int, Int>.east() = Pair(first, second + 1)
private fun Pair<Int, Int>.west() = Pair(first, second - 1)
private fun Graph.isConnected(p1: Point, p2: Point): Boolean {
return (get(p1)?.contains(p2) ?: false) && (get(p2)?.contains(p1) ?: false)
}
private fun MutableGraph.getDefault(p: Point) = getOrPut(p) { mutableSetOf() }
private fun parseGraph(input: List<String>): Pair<Point, Graph> {
val graph = mutableMapOf<Point, MutableSet<Point>>()
lateinit var startPos: Point
input.forEachIndexed { r, row ->
row.forEachIndexed { c, char ->
val p = r to c
with(graph.getDefault(p)) {
when (char) {
PIPE_EW -> { add(p.east()); add(p.west()) }
PIPE_NS -> { add(p.north()); add(p.south()) }
PIPE_NW -> { add(p.north()); add(p.west()) }
PIPE_NE -> { add(p.north()); add(p.east()) }
PIPE_SW -> { add(p.south()); add(p.west()) }
PIPE_SE -> { add(p.south()); add(p.east()) }
'S' -> {
startPos = p
add(p.south()); add(p.west()); add(p.north()); add(p.east())
}
}
}
}
}
return startPos to graph
}
private fun bfs(startPos: Point, graph: Graph): Map<Point, Int> {
val q = ArrayDeque<Point>()
q.addFirst(startPos)
val distance = mutableMapOf(startPos to 0)
while (!q.isEmpty()) {
val cur = q.removeLast()
val curDist = distance.get(cur)!!
graph.get(cur)?.forEach {
if (it in distance) return@forEach
if (graph[it]?.contains(cur) == true) {
distance[it] = curDist + 1
q.addFirst(it)
}
}
}
return distance
}
| 0 | Kotlin | 0 | 0 | 05a308a539c8a3f2683b11a3a0d97a7a78c4ffac | 4,889 | aoc-23 | Apache License 2.0 |
src/Day11.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | fun main() {
data class Monkey(
val id: Int,
val items: ArrayDeque<Long>,
val operation: Char,
val operationParam: String,
val testParam: Int,
val onSuccessTarget: Int,
val onFailedTarget: Int,
)
val inputLineRegex = """\d+""".toRegex()
fun monkeyBusiness(input: List<String>, rounds: Int, divisor: Int): Long {
val monkeys = mutableListOf<Monkey>()
val inspections = mutableMapOf<Int, Int>()
input.chunked(7).forEach { line ->
Monkey(
id = inputLineRegex.findAll(line[0]).map { it.value.toInt() }.first(),
items = ArrayDeque(inputLineRegex.findAll(line[1]).map { it.value.toLong() }.toList()),
operation = line[2].split("= old").last()[1],
operationParam = line[2].split("= old").last().substring(3),
testParam = inputLineRegex.findAll(line[3]).map { it.value.toInt() }.first(),
onSuccessTarget = inputLineRegex.findAll(line[4]).map { it.value.toInt() }.first(),
onFailedTarget = inputLineRegex.findAll(line[5]).map { it.value.toInt() }.first(),
).let {
monkeys.add(it)
inspections[it.id] = 0
}
}
val maxDiv = monkeys.map { it.testParam }.toSet().reduce(Int::times)
repeat(rounds) {
monkeys.forEach { monkey ->
inspections[monkey.id] = inspections[monkey.id]!! + monkey.items.size
while (monkey.items.isNotEmpty()) {
val worryLevel = monkey.items.removeFirst()
val operationParameter: Long = if (monkey.operationParam == "old") worryLevel else monkey.operationParam.toLong()
val newWorryLevel = when (monkey.operation) {
'*' -> worryLevel * operationParameter
'+' -> worryLevel + operationParameter
else -> throw Exception("Unknown operation $monkey.operation")
} / divisor % maxDiv
monkeys[if (newWorryLevel % monkey.testParam == 0L) monkey.onSuccessTarget else monkey.onFailedTarget].items.addLast(newWorryLevel)
}
}
}
return inspections.values.sorted().takeLast(2).map { it.toLong() }.reduce(Long::times)
}
fun part1(input: List<String>) = monkeyBusiness(input, rounds = 20, divisor = 3)
fun part2(input: List<String>) = monkeyBusiness(input, rounds = 10000, divisor = 1)
test(
day = 11,
testTarget1 = 10605,
testTarget2 = 2713310158L,
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 2,709 | aoc2022 | Apache License 2.0 |
src/main/kotlin/problems/Day9.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
class Day9(override val input: String) : Problem {
override val number: Int = 9
private val board: Board = Board.fromStr(input)
override fun runPartOne(): String {
return board
.localMinima()
.sumOf { point -> point.riskLevel }
.toString()
}
override fun runPartTwo(): String {
return board
.basins()
.map { basin -> basin.size }
.sortedDescending()
.take(3)
.fold(1) { mul, i -> mul * i }
.toString()
}
data class Board(val board: List<List<Point>>) {
companion object {
fun fromStr(input: String): Board {
return Board(input.lines()
.mapIndexed { row, line ->
line
.toCharArray()
.mapIndexed { col, i -> Point(row, col, i.digitToInt()) }
})
}
}
private val width = board.first().size
private val height = board.size
fun localMinima(): List<Point> {
return board
.flatten()
.filter { point ->
neighbours(point)
.all { neighbour -> neighbour > point }
}
}
fun basins(): Set<Set<Point>> {
return localMinima()
.map { point -> basin(point) }
.toSet()
}
private fun basin(startingPoint: Point): Set<Point> {
val toVisit = mutableListOf(startingPoint)
val visited = mutableSetOf<Point>()
while (toVisit.isNotEmpty()) {
val point = toVisit.removeAt(0)
toVisit.addAll(neighbours(point)
.filter { neighbour -> neighbour.height != 9 }
.filter { neighbour -> !visited.contains(neighbour) }
)
visited.add(point)
}
return visited
}
private fun neighbours(point: Point): List<Point> {
return listOf(
Pair(point.m + 1, point.n),
Pair(point.m - 1, point.n),
Pair(point.m, point.n + 1),
Pair(point.m, point.n - 1)
)
.filter { (m, n) -> m in 0 until height && n in 0 until width }
.map { (m, n) -> board[m][n] }
}
data class Point(val m: Int, val n: Int, val height: Int) : Comparable<Point> {
val riskLevel = height + 1
override fun compareTo(other: Point): Int {
return this.height.compareTo(other.height)
}
}
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 2,740 | AdventOfCode2021 | MIT License |
src/main/kotlin/day19/Day19.kt | Arch-vile | 317,641,541 | false | null | package day19
import java.io.File
fun main(args: Array<String>) {
val input = File("./src/main/resources/day19Input.txt")
.readText()
.split("\n\n")
val rulesInput =
input[0].split("\n")
.map {
if( it.take(2) == "8:" ) {
"8: ( 42 ) +"
} else if (it.take(3) == "11:") {
"11: " + rule11Mod()
}
else it
}
.map { it.split(" ") }
val superMegaRegex = buildReqex(rulesInput)
val messagesInput = input[1].split("\n")
val matchingMessages = messagesInput
.map { superMegaRegex.matches(it) }
.filter { it }
.count()
println(matchingMessages)
}
fun rule11Mod(): String {
return IntRange(1, 10)
.joinToString(" | ") { "( 42 {$it} 31 {$it} )" }
}
fun buildReqex(rulesInput: List<List<String>>): Regex {
val rulesMap = buildRulesMap(rulesInput)
var ruleZero = rulesMap[0]!!
while (hasRuleReferences(ruleZero)) {
ruleZero = ruleZero
.flatMap {
if (isNumber(it)) {
listOf("(").plus(rulesMap[it.toInt()]!!).plus(")")
} else {
listOf(it)
}
}
}
val regExAsString =
ruleZero
.joinToString("")
.replace("""(\(")|("\))""".toRegex(),"")
println(regExAsString)
return regExAsString.toRegex()
}
fun buildRulesMap(rulesInput: List<List<String>>): Map<Int, List<String>> {
return rulesInput.groupBy(
{ value -> value[0].split(":")[0].toInt() },
{ value -> value.drop(1) })
.map { it.key to it.value[0] }
.toMap()
}
fun hasRuleReferences(ruleZero: List<String>): Boolean {
val numberRegex = """\d+""".toRegex()
return ruleZero.any { numberRegex.matches(it) }
}
fun isNumber(it: String): Boolean {
return """\d+""".toRegex().matches(it)
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 1,755 | adventOfCode2020 | Apache License 2.0 |
src/Day02.kt | gilbertw1 | 573,027,692 | false | {"Kotlin": 5703} | data class Round(val elfPick: Selection, val selfPick: Selection) {
fun result(): Result {
return when (Pair(selfPick, elfPick)) {
Pair(Selection.Rock, Selection.Paper) -> Result.Loss
Pair(Selection.Rock, Selection.Scissors) -> Result.Win
Pair(Selection.Paper, Selection.Rock) -> Result.Win
Pair(Selection.Paper, Selection.Scissors) -> Result.Loss
Pair(Selection.Scissors, Selection.Paper) -> Result.Win
Pair(Selection.Scissors, Selection.Rock) -> Result.Loss
else -> Result.Draw
}
}
fun resultScore(): Int {
return when (result()) {
Result.Win -> 6
Result.Draw -> 3
Result.Loss -> 0
}
}
fun fullScore(): Int {
return resultScore() + selfPick.value()
}
}
enum class Selection {
Rock {
override fun value() = 1
},
Paper {
override fun value() = 2
},
Scissors {
override fun value() = 3
};
companion object {
fun fromChar(ch: Char): Selection {
return when (ch) {
'A', 'X' -> Rock
'B', 'Y' -> Paper
'C', 'Z' -> Scissors
else -> throw Exception("Invalid Selection Char: $ch")
}
}
}
abstract fun value(): Int
fun selectionForResult(result: Result): Selection {
return when (Pair(this, result)) {
Pair(Rock, Result.Win) -> Paper
Pair(Rock, Result.Loss) -> Scissors
Pair(Paper, Result.Win) -> Scissors
Pair(Paper, Result.Loss) -> Rock
Pair(Scissors, Result.Win) -> Rock
Pair(Scissors, Result.Loss) -> Paper
else -> this
}
}
}
enum class Result {
Loss,
Win,
Draw;
companion object {
fun fromChar(ch: Char): Result {
return when (ch) {
'X' -> Loss
'Y' -> Draw
'Z' -> Win
else -> throw Exception("Invalid Result Char: $ch")
}
}
}
}
fun main() {
fun parsePart1Rounds(input: List<String>): List<Round> {
val rounds = mutableListOf<Round>()
for (line in input) {
val round = Round(Selection.fromChar(line[0]), Selection.fromChar(line[2]))
rounds.add(round)
}
return rounds
}
fun parsePart2Rounds(input: List<String>): List<Round> {
val rounds = mutableListOf<Round>()
for (line in input) {
val elfPick = Selection.fromChar(line[0])
val selfPick = elfPick.selectionForResult(Result.fromChar(line[2]))
val round = Round(elfPick, selfPick)
rounds.add(round)
}
return rounds
}
fun part1(input: List<String>): Int {
val rounds = parsePart1Rounds(input)
return rounds.sumOf { it.fullScore() }
}
fun part2(input: List<String>): Int {
val rounds = parsePart2Rounds(input)
return rounds.sumOf { it.fullScore() }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e9e66d26125caa1bcf1af7a53b38f05ac55d77fd | 3,176 | aoc-2022-kotlin | Apache License 2.0 |
src/Day03.kt | Migge | 572,695,764 | false | {"Kotlin": 9496} | private fun part1(input: List<String>): Int = input
.map { it.toList() }
.map { it.chunked(it.size / 2) }
.map { (a, b) -> (a.toSet() intersect b.toSet()).first() }
.sumOf { alphabet.indexOf(it) + 1 }
private fun part2(input: List<String>): Int = input
.chunked(3)
.map { it.map { str -> str.toSet() } }
.map { (it[0] intersect it[1] intersect it[2]).first() }
.sumOf { alphabet.indexOf(it) + 1 }
private val alphabet = (('a'..'z').toList() + ('A'..'Z').toList())
fun main() {
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c7ca68b2ec6b836e73464d7f5d115af3e6592a21 | 715 | adventofcode2022 | Apache License 2.0 |
src/Day02.kt | alfr1903 | 573,468,312 | false | {"Kotlin": 9628} |
fun main() {
operator fun String.component1() = this[0]
operator fun String.component2() = this[1]
operator fun String.component3() = this[2]
fun part1(input: List<String>): Int {
fun shapeScore(shape: Char) = (shape - 'X' + 1)
fun resultScore(theirShape: Char, myShape: Char): Int {
return when (theirShape to myShape) {
'B' to 'X', 'C' to 'Y', 'A' to 'Z' -> 0
'A' to 'X', 'B' to 'Y', 'C' to 'Z' -> 3
'C' to 'X', 'A' to 'Y', 'B' to 'Z' -> 6
else -> error("Check you inputs")
}
}
return input.sumOf { round ->
val (theirShape, _, myShape) = round
shapeScore(myShape) + resultScore(theirShape, myShape)
}
}
fun part2(input: List<String>): Int {
fun shapeScore(theirShape: Char, desiredResult: Char): Int {
return when (theirShape to desiredResult) {
'A' to 'Y', 'B' to 'X', 'C' to 'Z' -> 1
'B' to 'Y', 'C' to 'X', 'A' to 'Z' -> 2
'C' to 'Y', 'A' to 'X', 'B' to 'Z' -> 3
else -> error("Check you inputs")
}
}
fun resultScore(result: Char) = (result - 'X') * 3
return input.sumOf { round ->
val (theirShape, _, result) = round
shapeScore(theirShape, result) + resultScore(result)
}
}
val input = readInputAsList("Day02Input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c1d1fbf030ac82c643fa5aea4d9f7c302051c38c | 1,521 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | daividssilverio | 572,944,347 | false | {"Kotlin": 10575} | fun main() {
val logs = readInput("Day07_test")
val root = Node(
name = "/",
parent = null,
children = mutableMapOf(),
isFolder = true,
size = 0
)
var currentFolder: Node = root
for (entry in logs) {
when {
entry.startsWith("$ cd") -> {
currentFolder = when (val dest = entry.removePrefix("$ cd ")) {
"/" -> root
".." -> currentFolder.parent ?: root
else -> {
currentFolder.children.computeIfAbsent(dest) {
Node("${currentFolder.name}/$it", currentFolder, isFolder = true)
}
}
}
}
entry.startsWith("$ ls") -> {}
entry.startsWith("dir") -> {
val folderListing = entry.removePrefix("dir ")
currentFolder.children.computeIfAbsent(folderListing) {
Node("${currentFolder.name}/$it", currentFolder, isFolder = true)
}
}
else -> {
val (size, fileName) = entry.split(" ").let { it[0].toInt() to it[1] }
currentFolder.children.computeIfAbsent(fileName) {
Node(it, parent = currentFolder, size = size)
}
}
}
}
println(part1(root))
println(part2(root))
}
private fun part1(root: Node): Int {
val nodesToCalculate = mutableListOf(root)
var sum = 0
while (nodesToCalculate.isNotEmpty()) {
val currentNode: Node = nodesToCalculate.removeFirst()
val size = nodeSize(currentNode)
if (size <= 100000) {
sum += size
}
nodesToCalculate.addAll(currentNode.children.values.filter { it.isFolder })
}
return sum
}
private fun part2(root: Node): Int {
val diskSize = 70000000
val usedSpace = nodeSize(root)
val availableSpace = diskSize - usedSpace
val spaceNecessaryForUpdate = 30000000
println(availableSpace)
val nodesToCalculate = mutableListOf(root)
val folderSizes = mutableListOf<Int>()
while (nodesToCalculate.isNotEmpty()) {
val currentNode: Node = nodesToCalculate.removeFirst()
val size = nodeSize(currentNode)
if (availableSpace + size >= spaceNecessaryForUpdate) {
folderSizes += size
}
nodesToCalculate.addAll(currentNode.children.values.filter { it.isFolder })
}
return folderSizes.min()
}
private fun nodeSize(node: Node): Int {
return if (node.isFolder) node.children.values.sumOf { nodeSize(it) }
else node.size
}
private class Node(
val name: String,
val parent: Node?,
val children: MutableMap<String, Node> = mutableMapOf(),
val isFolder: Boolean = false,
val size: Int = 0,
) | 0 | Kotlin | 0 | 0 | 141236c67fe03692785e0f3ab90248064a1693da | 2,870 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | sushovan86 | 573,586,806 | false | {"Kotlin": 47064} | fun main() {
fun Char.priority(): Int = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> 0
}
infix fun String.commonItemsIn(other: String) = if (this.isBlank() || other.isBlank()) {
""
} else {
(this.toSet() intersect other.toSet())
.joinToString()
}
fun part1(lines: List<String>): Int = lines
.sumOf { items: String ->
val (firstPart, secondPart) = items.chunked(items.length / 2)
val commonItems = firstPart commonItemsIn secondPart
commonItems.firstOrNull()?.priority() ?: 0
}
fun part2(lines: List<String>): Int = lines
.chunked(3)
.sumOf { itemsOf3Elves: List<String> ->
val (elf1Items, elf2Items, elf3Items) = itemsOf3Elves
val commonItems = elf1Items commonItemsIn elf2Items commonItemsIn elf3Items
commonItems.firstOrNull()?.priority() ?: 0
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val actualInput = readInput("Day03")
println(part1(actualInput))
println(part2(actualInput))
}
| 0 | Kotlin | 0 | 0 | d5f85b6a48e3505d06b4ae1027e734e66b324964 | 1,206 | aoc-2022 | Apache License 2.0 |
src/Day16.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | fun main() {
val day = 16
data class Valve(val id: Int, val flowRate: Int, val nextValves: List<Int>)
fun prepareInput(input: List<String>): List<Valve> {
val grouping = input.map {
Regex("Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)")
.matchEntire(it)!!
.groupValues
.drop(1)
}
val nameToId = grouping.map { it.first() }
.sorted()
.mapIndexed { index, name -> name to index }
.toMap()
return grouping.map { (valveName, valveFlowRateStr, nextValvesStr) ->
val valveId = nameToId[valveName]!!
val valveFlowRate = valveFlowRateStr.toInt()
val nextValvesId = nextValvesStr.split(", ").map { otherValveName -> nameToId[otherValveName]!! }
Valve(valveId, valveFlowRate, nextValvesId)
}
}
fun <K> MutableMap<K, Int>.maxOrSet(k: K, v: Int) {
val prevValue = this[k]
if (prevValue == null || prevValue < v)
this[k] = v
}
fun part1(input: List<String>, maxTimeMinutes: Int): Int {
val valves = prepareInput(input)
//dp[currentTimeMinutes][valveId][maskOfOpenedValves] = maximum score
val dp = List(maxTimeMinutes + 1) {
List(valves.size) { mutableMapOf<ULong, Int>() }
}
dp[0][0][0UL] = 0
for (time in 0 until maxTimeMinutes)
for (valve in valves)
for ((mask, score) in dp[time][valve.id]) {
val valveBit = (1UL shl valve.id)
if (valve.flowRate > 0 && (mask and valveBit) == 0UL)
dp[time + 1][valve.id].maxOrSet(
mask or valveBit,
score + (maxTimeMinutes - time - 1) * valve.flowRate
)
for (nextValveId in valve.nextValves)
dp[time + 1][nextValveId].maxOrSet(mask, score)
}
return dp[maxTimeMinutes].maxOf { it.maxOfOrNull { (_, v) -> v } ?: 0 }
}
fun part2(input: List<String>, maxTimeMinutes: Int): Int {
val valves = prepareInput(input)
//dp[currentTimeMinutes][valveId][maskOfOpenedValves] = maximum score
val dp = List(maxTimeMinutes + 1) {
List(valves.size) { mutableMapOf<ULong, Int>() }
}
dp[0][0][0UL] = 0
for (time in 0 until maxTimeMinutes)
for (valve in valves)
for ((mask, score) in dp[time][valve.id]) {
val valveBit = (1UL shl valve.id)
if (valve.flowRate > 0 && (mask and valveBit) == 0UL)
dp[time + 1][valve.id].maxOrSet(
mask or valveBit,
score + (maxTimeMinutes - time - 1) * valve.flowRate
)
for (nextValveId in valve.nextValves)
dp[time + 1][nextValveId].maxOrSet(mask, score)
}
val possibleMasks = mutableMapOf<ULong, Int>()
for ((mask, score) in dp[maxTimeMinutes].flatMap { it.toList() })
possibleMasks.maxOrSet(mask, score)
return possibleMasks.maxOf { (mask, score) ->
score + possibleMasks.maxOf { (elephantMask, elephantScore) ->
if (elephantMask and mask == 0UL) elephantScore else 0
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput, 30) == 1651)
check(part2(testInput, 26) == 1707)
val input = readInput("Day${day}")
println(part1(input, 30))
println(part2(input, 26))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 3,777 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | qmchenry | 572,682,663 | false | {"Kotlin": 22260} | fun main() {
fun bagOverlap(contents: String): Char {
val (first, second) = contents.chunked(contents.length / 2)
return first.toSet().intersect(second.toSet()).first()
}
fun priority(item: Char): Int {
return when (item) {
in 'a'..'z' -> item - 'a' + 1
in 'A'..'Z' -> item - 'A' + 27
else -> throw IllegalArgumentException("Unknown item: $item")
}
}
fun part1(input: List<String>): Int {
return input
.map { bagOverlap(it) }
.sumOf { priority(it) }
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.chunked(3)
.map { it.map { it.toSet() } }
.map { (a, b, c) -> a.intersect(b).intersect(c).first() }
.sumOf { priority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_sample")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val realInput = readInput("Day03_input")
println("Part 1: ${part1(realInput)}")
println("Part 2: ${part2(realInput)}")
}
| 0 | Kotlin | 0 | 0 | 2813db929801bcb117445d8c72398e4424706241 | 1,171 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2022/Day11.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2022
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day11: AdventDay(2022, 11) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day11()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun parseInput(input: List<String>): List<Monkey> {
return input.chunked(7).map { monkey ->
val id = monkey.first().substringAfter(" ").substringBefore(":").toInt()
val items = monkey[1].substringAfter("Starting items: ").split(", ").map { it.toLong() }
val operationText = monkey[2].substringAfter("Operation: new = old").trim()
val (op, opValue) = operationText.split(" ")
val test = monkey[3].substringAfter("Test: divisible by ").toInt()
val trueMonkey = monkey[4].substringAfter("If true: throw to monkey ").substringBefore("\n").toInt()
val falseMonkey = monkey[5].substringAfter("If false: throw to monkey ").substringBefore("\n").toInt()
val operation = { old: Long, divisor: Int, modNumber: Int ->
val v = if (opValue == "old") old else opValue.toLong()
val newValue = when (op) {
"*" -> old * v
"+" -> old + v
else -> error("only + and * implemented")
}
newValue / divisor % modNumber
}
val action = { newValue: Long -> if (newValue.mod(test) == 0) { trueMonkey } else { falseMonkey } }
Monkey(id = id, items = ArrayDeque(items), test, operation, action)
}
}
fun part1(): Long {
return parseInput(inputAsLines).rounds(20, 3).monkeyBusiness()
}
fun part2(): Long {
return parseInput(inputAsLines).rounds(10000, 1).monkeyBusiness()
}
data class Monkey(val id: Int, val items: ArrayDeque<Long>, val modNumber: Int, val operation: (Long, Int, Int) -> Long, val next: (Long) -> Int) : MutableList<Long> by items {
var count = 0
fun inspectAndCount(old: Long, divisor: Int, modNumber: Int): Long {
count++
return operation(old, divisor, modNumber)
}
}
}
fun List<Day11.Monkey>.rounds(rounds: Int, divisor: Int): List<Day11.Monkey> {
val modNumber = asSequence().map { monkey -> monkey.modNumber }.reduce(Int::times)
repeat(rounds) { round(divisor, modNumber) }
return this
}
fun List<Day11.Monkey>.round(divisor: Int, modNumber: Int) {
forEach { monkey ->
monkey.removeAll { item ->
val newValue = monkey.inspectAndCount(item, divisor, modNumber)
val newMonkey = monkey.next(newValue)
get(newMonkey).add(newValue)
}
}
}
fun List<Day11.Monkey>.monkeyBusiness() = asSequence().map { it.count }.sortedDescending().take(2).map { it.toLong() }.reduce(Long::times)
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 3,004 | adventofcode | MIT License |
src/main/kotlin/days/Day8.kt | VictorWinberg | 433,748,855 | false | {"Kotlin": 26228} | package days
class Day8 : Day(8) {
override fun partOne(): Any {
val input = inputList.map { it.split(" | ")[1].split(" ") }
return input.sumOf { it.count { it.length == 2 || it.length == 4 || it.length == 3 || it.length == 7 } }
}
override fun partTwo(): Any {
return inputList.sumOf { line -> decrypt(line) }
}
private fun decrypt(string: String): Int {
val input = string.split(" | ")[0].split(" ")
val output = string.split(" | ")[1].split(" ")
val mutation = allPermutations("abcdefg".toSet()).find { chars ->
input.all { segment -> sevenSegment(segment.map { chars[it - 'a'] }) != null }
} ?: throw Error("Couldn't find mutation!")
return output
.map { segment ->
sevenSegment(segment.map { mutation[it - 'a'] }) ?: throw Error("Incorrect mutation!")
}
.joinToString("").toInt()
}
private fun sevenSegment(input: List<Char>): Int? {
val sortedIn = input.sorted().joinToString("")
if (sortedIn == "abcefg") return 0
if (sortedIn == "cf") return 1
if (sortedIn == "acdeg") return 2
if (sortedIn == "acdfg") return 3
if (sortedIn == "bcdf") return 4
if (sortedIn == "abdfg") return 5
if (sortedIn == "abdefg") return 6
if (sortedIn == "acf") return 7
if (sortedIn == "abcdefg") return 8
if (sortedIn == "abcdfg") return 9
return null
}
private fun <T> allPermutations(set: Set<T>): Set<List<T>> {
if (set.isEmpty()) return emptySet()
fun <T> recAllPermutations(list: List<T>): Set<List<T>> {
if (list.isEmpty()) return setOf(emptyList())
val result: MutableSet<List<T>> = mutableSetOf()
for (i in list.indices) {
recAllPermutations(list - list[i]).forEach { item ->
result.add(item + list[i])
}
}
return result
}
return recAllPermutations(set.toList())
}
}
| 0 | Kotlin | 0 | 0 | d61c76eb431fa7b7b66be5b8549d4685a8dd86da | 2,081 | advent-of-code-kotlin | Creative Commons Zero v1.0 Universal |
src/Day15.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | import kotlin.concurrent.thread
import kotlin.math.abs
const val Y_PART_1 = 2000000
const val MAX_XY_PART_2 = 4000000
fun main() {
fun part1(input: List<List<Point>>): Int {
val xSensors = input.map{it.first()}.filter{it.y == Y_PART_1}.map{it.x}
val xBeacons = input.map{it.last()}.filter{it.y == Y_PART_1}.map{it.x}.distinct()
val xCannotContainBeacon = mutableListOf<Int>()
xCannotContainBeacon.addAll(xSensors)
for (line in input) {
val sensor = line.first()
val beacon = line.last()
val manhattanDistance = abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y)
// If we calculate the distanceToY, we know the leftover range on the x-axis where the beacon cannot be.
val distanceToY = if (sensor.y > Y_PART_1) sensor.y - Y_PART_1 else Y_PART_1 - sensor.y
val distanceToX = manhattanDistance - distanceToY
if (distanceToX >= 0) {
for (x in sensor.x - distanceToX..sensor.x + distanceToX) {
if (!xBeacons.contains(x)) {
xCannotContainBeacon.add(x)
}
}
}
}
return xCannotContainBeacon.distinct().count()
}
fun part2(input: List<List<Point>>): Long {
val chunkSize = MAX_XY_PART_2 / NUM_THREADS
for (i in 0 until NUM_THREADS) {
thread {
for (y in i * chunkSize..(i+1) * chunkSize) {
val xSensors = input.map{it.first()}.filter{it.y == y}.map{it.x}
val xBeacons = input.map{it.last()}.filter{it.y == y}.map{it.x}.distinct()
val xCannotContainBeacon = BooleanArray(MAX_XY_PART_2 + 1)
for (x in xSensors) {
xCannotContainBeacon[x] = true
}
for (x in xBeacons) {
xCannotContainBeacon[x] = true
}
for (line in input) {
val sensor = line.first()
val beacon = line.last()
val manhattanDistance = abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y)
// If we calculate the distanceToY, we know the leftover range on the x-axis where the beacon cannot be.
val distanceToY = if (sensor.y > y) sensor.y - y else y - sensor.y
val distanceToX = manhattanDistance - distanceToY
if (distanceToX >= 0) {
for (x in sensor.x - distanceToX..sensor.x + distanceToX) {
if (x in 0..MAX_XY_PART_2) {
xCannotContainBeacon[x] = true
}
}
}
}
val x = xCannotContainBeacon.indexOfFirst { !it }
// If there is a true x (that cannot contain a beacon), print result.
if (x != -1) {
println("FINAL X: $x")
println("FINAL Y: $y")
println("RESULT: ${x.toLong() * MAX_XY_PART_2 + y}")
return@thread
}
}
}
}
return 0
}
val input = readInputAsStrings("Day15")
.map{line -> line.split(": ")
.map{xy -> xy.split("Sensor at x=", ", y=", "closest beacon is at x=")
.filter{it.isNotEmpty()}}
.map{Point(it.first().toInt(), it.last().toInt())}}
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 3,676 | AoC2022 | Apache License 2.0 |
app/src/main/kotlin/com/resurtm/aoc2023/day19/Structs.kt | resurtm | 726,078,755 | false | {"Kotlin": 119665} | package com.resurtm.aoc2023.day19
internal data class Input(val rules: Map<String, Rule>, val workflows: List<Workflow>)
internal data class Rule(val name: String, val conditions: List<Condition>)
internal sealed class Condition(open val nextRule: String) {
data class Short(override val nextRule: String) : Condition(nextRule)
data class Full(
val token: Token,
val compOp: CompOp,
val compVal: Long,
override val nextRule: String
) : Condition(nextRule)
}
internal enum class Token(val value: Char) {
X('x'), M('m'), A('a'), S('s');
companion object {
fun fromValue(ch: Char): Token = when (ch) {
X.value -> X
M.value -> M
A.value -> A
S.value -> S
else -> throw Exception("An invalid token value passed for parse")
}
}
}
internal enum class CompOp(val value: Char) {
Less('<'), Greater('>');
companion object {
fun fromRawCondition(rawCondition: String): CompOp {
if (rawCondition.indexOf('<') != -1) return Less
if (rawCondition.indexOf('>') != -1) return Greater
throw Exception("An invalid condition passed for parse")
}
}
}
internal data class Workflow(val entries: Map<Token, Long>) {
fun findSum(): Long = entries.values.reduce { acc, x -> acc + x }
}
internal data class Slice(
val rule: String,
val x: LongRange, val m: LongRange, val a: LongRange, val s: LongRange
) {
fun isEmpty(): Boolean = x.isEmpty() && m.isEmpty() && a.isEmpty() && s.isEmpty()
fun split(c: Condition.Full): Pair<Slice, Slice> = when (c.compOp) {
CompOp.Less -> {
val sl0 = Slice(
rule = c.nextRule,
x = if (c.token == Token.X) x.first..<c.compVal else x,
m = if (c.token == Token.M) m.first..<c.compVal else m,
a = if (c.token == Token.A) a.first..<c.compVal else a,
s = if (c.token == Token.S) s.first..<c.compVal else s,
)
val sl1 = Slice(
rule = "",
x = if (c.token == Token.X) c.compVal..x.last else x,
m = if (c.token == Token.M) c.compVal..m.last else m,
a = if (c.token == Token.A) c.compVal..a.last else a,
s = if (c.token == Token.S) c.compVal..s.last else s,
)
Pair(sl0, sl1)
}
CompOp.Greater -> {
val sl0 = Slice(
rule = c.nextRule,
x = if (c.token == Token.X) c.compVal + 1..x.last else x,
m = if (c.token == Token.M) c.compVal + 1..m.last else m,
a = if (c.token == Token.A) c.compVal + 1..a.last else a,
s = if (c.token == Token.S) c.compVal + 1..s.last else s,
)
val sl1 = Slice(
rule = "",
x = if (c.token == Token.X) x.first..c.compVal else x,
m = if (c.token == Token.M) m.first..c.compVal else m,
a = if (c.token == Token.A) a.first..c.compVal else a,
s = if (c.token == Token.S) s.first..c.compVal else s,
)
Pair(sl0, sl1)
}
}
fun findSum(): Long =
(x.last - x.first + 1) * (m.last - m.first + 1) * (a.last - a.first + 1) * (s.last - s.first + 1)
}
| 0 | Kotlin | 0 | 0 | fb8da6c246b0e2ffadb046401502f945a82cfed9 | 3,371 | advent-of-code-2023 | MIT License |
src/day02/Day02.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day02
import utils.*
val SHAPES = mapOf(
'A' to 'R',
'B' to 'P',
'C' to 'S',
'X' to 'R',
'Y' to 'P',
'Z' to 'S'
)
const val ORDER = "RPS"
const val RESULTS = "XYZ"
fun getGames(input: List<String>): List<Pair<Char, Char>> =
input.map { line -> Pair(line.first(), line.last()) }
fun part1(input: List<String>): Int = getGames(input).sumOf { (other, self) ->
val selfTurn = SHAPES[self]!!
val otherTurn = SHAPES[other]!!
val selfOrder = ORDER.indexOf(selfTurn)
val otherOrder = ORDER.indexOf(otherTurn)
val turnScore = selfOrder + 1
val winScore = 3 +
(if (selfOrder == (otherOrder + 1) % ORDER.length) 3 else 0) +
(if (otherOrder == (selfOrder + 1) % ORDER.length) -3 else 0)
turnScore + winScore
}
fun part2(input: List<String>): Int = getGames(input).sumOf { (other, result) ->
val otherTurn = SHAPES[other]!!
val otherTurnOrder = ORDER.indexOf(otherTurn)
val resultIdx = RESULTS.indexOf(result)
val winScore = resultIdx * 3
val delta = resultIdx - 1
val turnScore = (otherTurnOrder + delta + ORDER.length) % ORDER.length + 1
winScore + turnScore
}
fun main() {
val testInput = readInput("Day02_test")
expect(part1(testInput), 15)
expect(part2(testInput), 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 1,381 | AOC-2022-Kotlin | Apache License 2.0 |
app/src/main/kotlin/day11/Day11.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day11
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 11
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay11Part1, ::solveDay11Part2)
}
fun solveDay11Part1(input: List<String>): Int {
var grid = parseInput(input)
val steps = 100
var counter = 0
repeat(steps) {
grid = increaseAllCounters(grid)
val flashed = triggerFlashes(grid)
flashed.forEach { grid[it.y][it.x] = 0 }
counter += flashed.size
}
return counter
}
fun solveDay11Part2(input: List<String>): Int {
var grid = parseInput(input)
val octopusCount = grid.size * grid[0].size
var step = 1
while (true) {
grid = increaseAllCounters(grid)
val flashed = triggerFlashes(grid)
if (flashed.size == octopusCount) return step
flashed.forEach { grid[it.y][it.x] = 0 }
step++
}
}
private fun triggerFlashes(grid: Array<Array<Int>>): MutableSet<Point> {
val flashed = mutableSetOf<Point>()
var previousFlashed = -1
while (previousFlashed != flashed.size) {
previousFlashed = flashed.size
grid.forEachIndexed { y, row ->
row.forEachIndexed { x, octopus ->
val point = Point(x, y)
if (octopus > 9 && !flashed.contains(point)) {
flashed.add(point)
val neighbors = point.getNeighbors()
neighbors.forEach { grid[it.y][it.x]++ }
}
}
}
}
return flashed
}
private fun increaseAllCounters(grid: Array<Array<Int>>): Array<Array<Int>> {
return grid.map { row -> row.map { it + 1 }.toTypedArray() }.toTypedArray()
}
private fun parseInput(input: List<String>): Array<Array<Int>> {
return input.map { row -> row.toCharArray().map { it.digitToInt() }.toTypedArray() }.toTypedArray()
}
data class Point(val x: Int, val y: Int)
fun Point.getNeighbors(width: Int = 10, height: Int = 10): List<Point> {
return listOf(
-1 to -1,
-1 to 0,
-1 to 1,
0 to -1,
0 to 1,
1 to -1,
1 to 0,
1 to 1,
)
.map { Point(x + it.first, y + it.second) }
.filterNot { it.x < 0 || it.y < 0 || it.x >= width || it.y >= height }
}
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 2,374 | advent-of-code-kt | Apache License 2.0 |
src/Day03.kt | jandryml | 573,188,876 | false | {"Kotlin": 6130} | private fun part1(input: List<String>): Int {
return input.asSequence()
.map { it.chunked(it.length / 2) }
.map { (a, b) -> a.find { it in b } }
.sumOf { it?.toPriority() ?: 0 }
}
private fun part2(input: List<String>): Int {
return input.chunked(3)
.map { (a, b, c) -> a.find { it in b && it in c } }
.sumOf { it?.toPriority() ?: 0 }
}
private fun Char.toPriority() =
when (this) {
in 'A'..'Z' -> this - 'A' + 27
in 'a'..'z' -> this - 'a' + 1
else -> throw Exception("Invalid char")
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 90c5c24334c1f26ee1ae5795b63953b22c7298e2 | 918 | Aoc-2022 | Apache License 2.0 |
src/day18/Day18.kt | gautemo | 317,316,447 | false | null | package day18
import shared.getLines
fun calculate(input: String): Long{
var expression = input
while(expression.contains(Regex("""\*|\+"""))){
val first = Regex("""\(?\d+ (\*|\+) \d+\)?""").find(expression)
val toCalculate = first!!.value.replace("(", "").replace(")", "")
val toReplace = if(first.value.contains("(") && first.value.contains(")")) {
first.value
}else{
first.value.replace("(", "").replace(")", "")
}
val result = if(toCalculate.contains('+')){
val (f, l) = toCalculate.split('+').map { it.trim().toLong() }
f + l
}else{
val (f, l) = toCalculate.split('*').map { it.trim().toLong()}
f * l
}
expression = expression.replaceFirst(toReplace, result.toString())
}
return expression.toLong()
}
fun calculatePrecedence(input: String): Long{
var expression = input
while(expression.contains(Regex("""\*|\+"""))){
val parentheses = Regex("""\([^()]*\)""").find(expression)
if(parentheses != null){
val result = calculatePrecedence(parentheses.value.trimStart('(').trimEnd(')'))
expression = expression.replaceFirst(parentheses.value, result.toString())
continue
}
val addition = Regex("""\d+ (\+) \d+""").find(expression)
if(addition != null){
val result = addition.value.split('+').map { it.trim().toLong() }.sum()
expression = expression.replaceFirst(addition.value, result.toString())
continue
}
val multiplication = Regex("""\d+ (\*) \d+""").find(expression)
if(multiplication != null){
val (a, b) = multiplication.value.split('*').map { it.trim().toLong() }
val result = a * b
expression = expression.replaceFirst(multiplication.value, result.toString())
continue
}
}
return expression.toLong()
}
fun sumOfCalculations(calculations: List<String>) = calculations.map { calculate(it) }.sum()
fun sumOfCalculationsPrecedence(calculations: List<String>) = calculations.map { calculatePrecedence(it) }.sum()
fun main(){
val input = getLines("day18.txt")
val sum = sumOfCalculations(input)
println(sum)
val sumPrecedence = sumOfCalculationsPrecedence(input)
println(sumPrecedence)
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 2,384 | AdventOfCode2020 | MIT License |
src/Day03.kt | colmmurphyxyz | 572,533,739 | false | {"Kotlin": 19871} | fun main() {
val priorityOf: (Char) -> Int = { c ->
val code = c.code
if (code in 97..122) { // lower case letters
code - 96
} else if (code in 65..90) { // upper case letters
code - 38
} else throw IllegalArgumentException() // non-letter characters
}
fun part1_old(): Int {
var priorities = 0
val input = readInput("Day03")
for (rucksack in input) {
val halfway = rucksack.length / 2
val compartment1 = rucksack.slice(0 until halfway)
val compartment2 = rucksack.slice(halfway until rucksack.length)
val comp1Chars = HashMap<Char, Int>(52)
val comp2Chars = HashMap<Char, Int>(52)
for (i in compartment1.indices) {
comp1Chars[compartment1[i]] = comp1Chars.getOrDefault(compartment1[i], 0) + 1
comp2Chars[compartment2[i]] = comp2Chars.getOrDefault(compartment2[i], 0) + 1
}
for (key in comp1Chars.keys) {
if (comp1Chars.getOrDefault(key, 0) > 0 && comp2Chars.getOrDefault(key, 0) > 0) {
priorities += priorityOf(key)
}
}
}
return priorities
}
fun part1(): Int {
var priorities = 0
val input = readInput("Day03")
for (rucksack in input) {
val halfway = rucksack.length / 2
val compartment1 = rucksack.slice(0 until halfway).toSet()
val compartment2 = rucksack.slice(halfway until rucksack.length).toSet()
val commonCharacters = compartment1 intersect compartment2
for (c in commonCharacters) {
priorities += priorityOf(c)
}
}
return priorities
}
fun part2(): Int {
var priorities = 0
val input = readInput("Day03")
for (i in 0..input.size-2 step 3) {
// find the one letter in common among all 3 lines
val commonCharacter = (input[i].toSet() intersect input[i + 1].toSet() intersect input[i + 2].toSet())
if (commonCharacter.size != 1) {
throw IllegalArgumentException("commonCharacter.size = ${commonCharacter.size}, should be 1")
}
priorities += priorityOf(commonCharacter.first())
}
return priorities
}
println("Part 1 answer: ${part1()}")
println("Part 2 answer: ${part2()}")
} | 0 | Kotlin | 0 | 0 | c5653691ca7e64a0ee7f8e90ab1b450bcdea3dea | 2,456 | aoc-2022 | Apache License 2.0 |
src/day03/Day03.kt | hamerlinski | 572,951,914 | false | {"Kotlin": 25910} | package day03
import readInput
fun main() {
val input = readInput("Day03", "day03")
val inputIterator = input.iterator()
fun part1(inputIterator: Iterator<String>) {
var part1Solution = 0
inputIterator.forEach {
val rucksack = Rucksack(it.toList())
val priority = Priority(rucksack.errorsItem().filter { true }[0])
part1Solution += priority.value()
}
println(part1Solution)
}
fun part2() {
var part2solution = 0
for (i in 0..input.lastIndex step 3) {
val firstRucksack = Rucksack(input[i].toList())
val secondRucksack = Rucksack(input[i + 1].toList())
val thirdRucksack = Rucksack(input[i + 2].toList())
val group = Group(firstRucksack, secondRucksack, thirdRucksack)
val priority = Priority(group.badge())
part2solution += priority.value()
}
println(part2solution)
}
part1(inputIterator)
part2()
}
class Priority(private val item: Char) {
fun value(): Int {
return if (item.isLowerCase())
item.code.minus(96)
else item.code.minus(38)
}
}
class Rucksack(items: List<Char>) {
private val firstCompartment: List<Char> = items.subList(0, items.size.div(2))
private val secondCompartment: List<Char> = items.subList(items.size.div(2), items.size)
fun errorsItem(): Set<Char> {
return firstCompartment.intersect(secondCompartment.toSet())
}
val allItemsSet: Set<Char> = items.toSet()
}
class Group(private val elf1: Rucksack, private val elf2: Rucksack, private val elf3: Rucksack) {
fun badge(): Char {
val elf1AndElf2: Set<Char> = elf1.allItemsSet.intersect(elf2.allItemsSet)
val elf1AndElf3: Set<Char> = elf1.allItemsSet.intersect(elf3.allItemsSet)
val elf2AndElf3: Set<Char> = elf2.allItemsSet.intersect(elf3.allItemsSet)
val elf1elf2AndElf1Elf3: Set<Char> = elf1AndElf2.intersect(elf1AndElf3)
return elf2AndElf3.intersect(elf1elf2AndElf1Elf3).filter { true }[0]
}
} | 0 | Kotlin | 0 | 0 | bbe47c5ae0577f72f8c220b49d4958ae625241b0 | 2,090 | advent-of-code-kotlin-2022 | Apache License 2.0 |
app/src/main/kotlin/day05/Day05.kt | W3D3 | 433,748,408 | false | {"Kotlin": 72893} | package day05
import common.InputRepo
import common.readSessionCookie
import common.solve
import kotlin.math.abs
import kotlin.math.max
fun main(args: Array<String>) {
val day = 5
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay05Part1, ::solveDay05Part2)
}
data class Line(val start: Coord, val end: Coord) {
fun isNonDiagonal(): Boolean {
return (start.x == end.x) or (start.y == end.y)
}
fun getAffectedCoords(): Collection<Coord> {
val affectedCoords = ArrayList<Coord>()
fun calcStepSize(from: Int, to: Int): Int = when {
from < to -> 1
from == to -> 0
else -> -1
}
val stepX = calcStepSize(start.x, end.x)
val stepY = calcStepSize(start.y, end.y)
val xDiff = abs(start.x - end.x)
val yDiff = abs(start.y - end.y)
// Note, this assumes that all diagonal lines are 45°.
val numSteps: Int = max(xDiff, yDiff)
for (i in 0..numSteps) {
affectedCoords.add(Coord(start.x + stepX * i, start.y + stepY * i))
}
return affectedCoords
}
}
data class Coord(val x: Int, val y: Int)
private fun parseLine(line: String): Line {
val regex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex()
val matchResult = regex.find(line)
val (x1, y1, x2, y2) = matchResult!!.destructured
return Line(Coord(x1.toInt(), y1.toInt()), Coord(x2.toInt(), y2.toInt()))
}
fun solveDay05Part1(input: List<String>): Int {
val coverMap = HashMap<Coord, Int>()
input.map { line -> parseLine(line) }
.filter(Line::isNonDiagonal)
.forEach { line ->
line.getAffectedCoords()
.forEach { coord -> coverMap.compute(coord) { _, cnt -> if (cnt == null) 1 else cnt + 1 } }
}
return coverMap.count { entry -> entry.value >= 2 }
}
fun solveDay05Part2(input: List<String>): Int {
val coverMap = HashMap<Coord, Int>()
input.map { line -> parseLine(line) }
.forEach { line ->
line.getAffectedCoords()
.forEach { coord -> coverMap.compute(coord) { _, cnt -> if (cnt == null) 1 else cnt + 1 } }
}
return coverMap.count { entry -> entry.value >= 2 }
} | 0 | Kotlin | 0 | 0 | df4f21cd99838150e703bcd0ffa4f8b5532c7b8c | 2,314 | AdventOfCode2021 | Apache License 2.0 |
2022/src/day02/day02.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day02
import GREEN
import RESET
import printTimeMillis
import readInput
fun String.shape(startLetter: Char) = (this.first() - startLetter) + 1
// A == "Rock" -- B == "Paper" -- C == "Scissors"
// lose == 0, draw == 3, win == 6
val shapeToScore = mapOf(
"X" to mapOf("A" to 3, "B" to 0, "C" to 6),
"Y" to mapOf("A" to 6, "B" to 3, "C" to 0),
"Z" to mapOf("A" to 0, "B" to 6, "C" to 3),
)
fun part1(input: List<String>) = input.fold(0) { acc, line ->
val plays = line.split(" ")
acc + shapeToScore[plays[1]]!![plays[0]]!! + plays[1].shape('X')
}
val outcomeToShape = mapOf(
"A" to mapOf("Y" to "A", "X" to "C", "Z" to "B"),
"B" to mapOf("Y" to "B", "X" to "A", "Z" to "C"),
"C" to mapOf("Y" to "C", "X" to "B", "Z" to "A")
)
val wantedScore = mapOf("X" to 0, "Y" to 3, "Z" to 6)
fun part2(input: List<String>) = input.fold(0) { acc, line ->
val plays = line.split(" ")
val wantedScore = wantedScore[plays[1]]!!
val wantedPlay = outcomeToShape[plays[0]]!![plays[1]]!!
acc + wantedScore + wantedPlay.shape('A')
}
fun main() {
val testInput = readInput("day02_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day02.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 1,498 | advent-of-code | Apache License 2.0 |
src/main/aoc2020/Day16.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2020
class Day16(input: List<String>) {
private data class Rule(val name: String, val r1: IntRange, val r2: IntRange) {
fun validate(i: Int) = i in r1 || i in r2
}
private data class Ticket(val fields: List<Int>, val invalidFields: List<Int>) {
fun isValid() = invalidFields.isEmpty()
fun scanningErrorRate() = invalidFields.sum()
fun isColumnValidUnderRule(column: Int, rule: Rule) = rule.validate(fields[column])
companion object {
fun parse(fields: List<Int>, rules: List<Rule>): Ticket {
val valid = mutableListOf<Int>()
val invalid = mutableListOf<Int>()
fields.forEach { if (rules.any { rule -> rule.validate(it) }) valid.add(it) else invalid.add(it) }
return Ticket(valid, invalid)
}
}
}
private val rules: List<Rule>
private val myTicket: List<Int>
private val nearbyTickets: List<Ticket>
private fun String.toIntRange() = split("-").let { it.first().toInt()..it.last().toInt() }
private fun String.toIntList() = split(",").map { it.toInt() }
init {
val lineIterator = input.iterator()
rules = buildList {
for (line in lineIterator) {
if (line.isEmpty()) {
break
}
"([a-z ]+): ([0-9-]+) or ([0-9-]+)".toRegex()
.matchEntire(line)!!
.destructured
.let { (rule, r1, r2) -> add(Rule(rule, r1.toIntRange(), r2.toIntRange())) }
}
}
lineIterator.next() // your ticket:
myTicket = lineIterator.next().toIntList()
lineIterator.next()
lineIterator.next() // nearby tickets:
nearbyTickets = buildList {
for (line in lineIterator) {
add(Ticket.parse(line.toIntList(), rules))
}
}
}
private fun findRulesToColumnMapping(tickets: List<Ticket>): MutableMap<Rule, Int> {
// Map with rule to set of columns that it could apply to mapping
val possible = rules.associateWith { mutableSetOf<Int>() }.toMutableMap()
rules.forEach { rule ->
for (column in myTicket.indices) {
if (tickets.all { it.isColumnValidUnderRule(column, rule) }) {
possible[rule]!!.add(column)
}
}
}
val fixed = mutableMapOf<Rule, Int>()
while (possible.isNotEmpty()) {
// Pick the rule that could only apply to one column and fix it
val (knownRule, knownColumn) = possible.minByOrNull { it.value.size }!!
fixed[knownRule] = knownColumn.single()
possible.remove(knownRule)
// then remove it's column from all other rules
possible.forEach { it.value.remove(knownColumn.single()) }
}
return fixed
}
fun solvePart1(): Int {
return nearbyTickets.sumOf { it.scanningErrorRate() }
}
fun solvePart2(): Long {
return findRulesToColumnMapping(nearbyTickets.filter { it.isValid() })
.filterKeys { it.name.contains("departure") }
.values
.map { myTicket[it] }
.fold(1L) { acc, value -> acc * value }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,348 | aoc | MIT License |
src/Day16.kt | shepard8 | 573,449,602 | false | {"Kotlin": 73637} | import java.util.PriorityQueue
fun main() {
class Valve(val name: String, val rate: Int, val accessible: MutableList<Valve>) {
override fun toString() = name
}
class State(val currentValve: Valve, val openedValves: List<Valve>, val currentRate: Int, val currentOut: Int, val timeElapsed: Int) {
fun open() =
if (currentValve in openedValves) State(currentValve, openedValves, currentRate, currentOut + currentRate, timeElapsed + 1)
else State(currentValve, openedValves + currentValve, currentRate + currentValve.rate, currentOut + currentRate, timeElapsed + 1)
fun goTo(valve: Valve) = State(valve, openedValves, currentRate, currentOut + currentRate, timeElapsed + 1)
override fun toString() = "$currentValve - $currentRate - $currentOut - $timeElapsed"
fun potential() = currentOut + 20 * (30 - timeElapsed)
}
class State2(val myValve: Valve, val elephantValve: Valve, val openedValves: List<Valve>, val seenValves: Set<Valve>, val currentRate: Int, val currentOut: Int, val timeElapsed: Int) {
fun move(elephantMove: Valve, myMove: Valve): State2 {
val newlyOpened = listOfNotNull(
elephantValve.takeIf { elephantMove == elephantValve && elephantValve !in openedValves },
myValve.takeIf { myMove == myValve && myValve != elephantValve && myValve !in openedValves },
)
return State2(
myMove, elephantMove,
openedValves + newlyOpened,
seenValves + (setOf(myValve, elephantValve) - newlyOpened.toSet()),
currentRate + newlyOpened.sumOf { it.rate },
currentOut + currentRate,
timeElapsed + 1
)
}
override fun toString() = "$myValve - $elephantValve - $currentRate - $currentOut - $timeElapsed"
fun potential(): Int {
return currentOut + (26 - timeElapsed) * currentRate + (if (myValve !in seenValves) 10000 else 0) + (if (elephantValve !in seenValves) 10000 else 0)
}
}
fun parseData(input: List<String>, print: Boolean): List<Valve> {
val valves = mutableMapOf<String, Valve>()
if (print) println("graph {")
input.forEach { line ->
val regex = Regex("^Valve (..) has flow rate=(\\d+); tunnels? leads? to valves? (.+)$")
val match = regex.matchEntire(line)!!
val values = match.groupValues.drop(1)
if (print) {
val label = "${values[0]} (${values[1]})"
val color = if (values[1] == "0") "black" else "red"
println("${values[0]} [label=\"$label\",color=$color]")
values[2].split(", ").filter { it > values[0] }.forEach {
println("${values[0]} -- $it")
}
}
val valve = Valve(values[0], values[1].toInt(), values[2].split(", ").mapNotNull { valves[it] }.toMutableList())
valves[values[0]] = valve
}
if (print) println("}")
valves.values.forEach { valve -> valve.accessible.forEach { valves[it.name]!!.accessible.add(valve) } }
return valves.values.toList()
}
fun part1(input: List<String>): Int {
val valves = parseData(input, true)
val start = State(
valves.find { it.name == "AA" }!!,
listOf(),
0,
0,
0
)
val toExplore = PriorityQueue<State> { s1, s2 -> s2.potential() - s1.potential() }
toExplore.add(start)
var maxOut = 0
var i: Long = 0
while (toExplore.isNotEmpty()) {
val state = toExplore.poll()
if (++i % 100_000_000 == 0.toLong()) {
println("$i : ${toExplore.count()} left to explore - Next state : $state - Current max - $maxOut")
}
if (state.currentOut > maxOut) {
maxOut = state.currentOut
println(state)
}
if (state.timeElapsed == 30)
continue
if (state.currentValve.rate > 0 && state.currentValve !in state.openedValves) {
toExplore.add(state.open())
}
state.currentValve.accessible.forEach {
toExplore.add(state.goTo(it))
}
}
return maxOut
}
fun part2(input: List<String>): Int {
val valves = parseData(input, true)
val start = State2(
valves.find { it.name == "AA" }!!,
valves.find { it.name == "AA" }!!,
listOf(),
setOf(),
0,
0,
0
)
val toExplore = PriorityQueue<State2> { s1, s2 -> s2.potential() - s1.potential() }
toExplore.add(start)
var maxOut = 0
var i: Long = 0
while (toExplore.isNotEmpty()) {
val state = toExplore.poll()
if (++i % 100_000_000 == 0.toLong()) {
println("$i : ${toExplore.count()} left to explore - Next state : $state - Current max - $maxOut")
}
if (state.currentOut > maxOut) {
maxOut = state.currentOut
println(state)
}
// Prune
if (state.currentOut + 217 * (26 - state.timeElapsed) <= maxOut)
continue
val elephantMoves = if (state.elephantValve.rate > 0 && state.elephantValve !in state.openedValves) listOf(state.elephantValve) else state.elephantValve.accessible
val myMoves = if (state.myValve.rate > 0 && state.myValve !in state.openedValves) listOf(state.myValve) else state.myValve.accessible
elephantMoves.forEach { eMove ->
myMoves.filter { it != eMove }.forEach { mMove ->
toExplore.add(state.move(eMove, mMove))
}
}
}
return maxOut
}
val input = readInput("Day16")
// Uncomment either of these lines. Answer comes after a few minutes for part 1 and a few seconds for part 2. I don't feel like managing this mess, sorry :-]
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 81382d722718efcffdda9b76df1a4ea4e1491b3c | 6,209 | aoc2022-kotlin | Apache License 2.0 |
src/Day09.kt | anisch | 573,147,806 | false | {"Kotlin": 38951} | import kotlin.math.abs
private fun Vec.isTouching(o: Vec): Boolean =
abs(x - o.x) <= 1 && abs(y - o.y) <= 1
private fun Vec.move(dir: String): Vec = when (dir) {
"U" -> Vec(x, y + 1)
"D" -> Vec(x, y - 1)
"L" -> Vec(x - 1, y)
"R" -> Vec(x + 1, y)
else -> error("wtf???")
}
fun main() {
fun part1(input: List<String>): Int {
var head = Vec(0, 0)
val tails = mutableListOf(head)
input
.map { it.split(" ") }
.forEach { (dir, steps) ->
for (step in 0 until steps.toInt()) {
val tmp = head
head = tmp.move(dir)
if (tails[tails.lastIndex].isTouching(head)) continue
tails += tmp
}
}
return tails.toSet().size
}
fun part2(input: List<String>): Int {
val rope = Array(10) { Vec(0, 0) }
val tails = mutableListOf(rope[rope.lastIndex])
input
.map { it.split(" ") }
.forEach { (dir, steps) ->
(0 until steps.toInt()).forEach { _ ->
val tmp = rope[0]
rope[0] = tmp.move(dir)
for (rdx in 0 until 9) {
val head = rope[rdx]
val tail = rope[rdx + 1]
if (tail.isTouching(head)) continue
val offset = head - tail
val normalized = Vec(
offset.x.coerceIn(-1..1),
offset.y.coerceIn(-1..1),
)
rope[rdx + 1] = tail + normalized
}
tails += rope[rope.lastIndex]
}
}
return tails.toSet().size
}
// test if implementation meets criteria from the description, like:
val testInput1 = readInput("Day09_test_part1")
val testInput2 = readInput("Day09_test_part2")
val input = readInput("Day09")
check(part1(testInput1) == 13)
println(part1(input))
check(part2(testInput2) == 36)
println(part2(input)) // 2607
}
| 0 | Kotlin | 0 | 0 | 4f45d264d578661957800cb01d63b6c7c00f97b1 | 2,245 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day05.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | import java.util.Stack
fun main() {
fun buildStacks(input: String): List<Stack<String>> {
val rows = input.split("\n")
val stacks = MutableList<Stack<String>>(rows.last().split(" \\d ".toRegex()).size) {
Stack()
}
rows.reversed().drop(1).map { row ->
row.chunked(4).map { it[1].toString() } // [A] [B] [C] .....
}.forEach {
it.forEachIndexed { index, crate ->
if (crate.isBlank()) return@forEachIndexed
val stack = stacks.getOrNull(index)
if (stack == null) {
stacks.add(Stack<String>().apply { add(crate) })
} else {
stack.add(crate)
}
}
}
return stacks
}
fun getMoves(input: List<String>) = input[1].split("\n").filter { it.isNotBlank() }.map {
it.split(" ").mapNotNull { it.toIntOrNull() }.map { it - 1 }
}
fun part1(input: List<String>) {
val stacks = buildStacks(input[0])
getMoves(input).forEach { (e1, e2, e3) ->
repeat(e1 + 1) { _ ->
stacks[e2].pop().let { stacks[e3].add(it) }
}
}
stacks.joinToString("") { it.pop() }.log("part1")
}
fun part2(input: List<String>) {
val stacks = buildStacks(input[0])
getMoves(input).forEach { (e1, e2, e3) ->
(0..e1).map { _ ->
stacks[e2].pop()
}.reversed().let { stacks[e3].addAll(it) }
}
stacks.joinToString("") { it.pop() }.log("part2")
}
val input = readInput("Day05", "\n\n")
part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 1,685 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val card = line.substringAfter(":").trim()
val (winning, numbers) = card.split('|').map { it.trim().split("\\s+".toRegex()).map(String::toInt).toSet() }
val intersections = numbers.intersect(winning).size
if (intersections == 0) 0 else 1 shl (intersections - 1)
}
}
fun part2(input: List<String>): Int {
val cardNumberToCopies = mutableMapOf<Int, Int>()
return input.mapIndexed { index, line ->
val copies = cardNumberToCopies[index] ?: 1
val card = line.substringAfter(":").trim()
val (winning, numbers) = card.split('|').map { it.trim().split("\\s+".toRegex()).map(String::toInt).toSet() }
val intersections = numbers.intersect(winning).size
(index + 1..index + intersections).forEach { cardNumber ->
cardNumberToCopies[cardNumber] = (cardNumberToCopies[cardNumber] ?: 1) + copies
}
copies
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 13)
check(part2(testInput) == 30)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 1,424 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Day11.kt | Vampire | 572,990,104 | false | {"Kotlin": 57326} | fun main() {
data class Monkey(
val id: Int,
val items: MutableList<Long> = mutableListOf(),
var operation: (Long) -> Long = { it },
var testDivisor: Int = -1,
var trueTarget: Int = -1,
var falseTarget: Int = -1,
var activity: Long = 0
) {
fun test(dividend: Long) = dividend % testDivisor == 0L
}
fun part1(input: List<String>, reliefFactor: Int = 3, rounds: Int = 20): Long {
val notebook = input.filter { it.isNotBlank() }.iterator()
val monkeys = mutableMapOf<Int, Monkey>()
for (monkeyId in notebook) {
check(monkeyId.endsWith(":"))
val monkey = Monkey(monkeyId.dropLast(1).substringAfter("Monkey ").toInt())
monkeys[monkey.id] = monkey
val startingItems = notebook.next()
monkey.items.addAll(
startingItems
.substringAfter(" Starting items: ")
.split(", ")
.map(String::toLong)
.toMutableList()
)
val operation = notebook.next()
val (operator, operand) = operation
.substringAfter(" Operation: new = old ")
.split(" ")
monkey.operation = when (operator) {
"+" -> if (operand == "old") ({ it + it }) else (operand.toLong().let { intOperand -> { it + intOperand } })
"*" -> if (operand == "old") ({ it * it }) else (operand.toLong().let { intOperand -> { it * intOperand } })
else -> error("Unexpected operator $operator")
}
val testDivisor = notebook.next()
monkey.testDivisor = testDivisor
.substringAfter(" Test: divisible by ")
.toInt()
val trueTarget = notebook.next()
monkey.trueTarget = trueTarget.substringAfter(" If true: throw to monkey ").toInt()
val falseTarget = notebook.next()
monkey.falseTarget = falseTarget.substringAfter(" If false: throw to monkey ").toInt()
}
val sanitizingDivisor = if (reliefFactor == 1) monkeys
.values
.map(Monkey::testDivisor)
.reduce(Int::times) else Int.MAX_VALUE
for (round in 1..rounds) {
for (monkey in monkeys.values) {
for (item in monkey.items) {
val newItem = monkey.operation(item) / reliefFactor % sanitizingDivisor
monkeys[if (monkey.test(newItem)) monkey.trueTarget else monkey.falseTarget]!!.items.add(newItem)
}
monkey.activity += monkey.items.size
monkey.items.clear()
}
}
return monkeys
.values
.map(Monkey::activity)
.sortedDescending()
.take(2)
.reduce(Long::times)
}
fun part2(input: List<String>) = part1(input, reliefFactor = 1, rounds = 10_000)
val testInput = readStrings("Day11_test")
check(part1(testInput) == 10_605L)
val input = readStrings("Day11")
println(part1(input))
check(part2(testInput) == 2_713_310_158)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f | 3,234 | aoc-2022 | Apache License 2.0 |
advent_of_code/2018/solutions/day_6_a.kt | migafgarcia | 63,630,233 | false | {"C++": 121354, "Kotlin": 38202, "C": 34840, "Java": 23043, "C#": 10596, "Python": 8343} | import java.io.File
import java.lang.Math.abs
fun main(args: Array<String>) {
val ids = generateSequence(1) { it + 1 }
val points = ids.zip(File(args[0]).readLines().map { line ->
val s = line.split(",").map { it.trim() }
Pair(s[0].toInt(), s[1].toInt())
}.asSequence()).toMap()
val xMax = points.values.maxBy { it.first }!!.first
val yMax = points.values.maxBy { it.second }!!.second
val areas = HashMap<Int, Int>()
val infinites = HashSet<Int>()
points.forEach { k, _ -> areas.put(k, 0) }
for (x in 0..xMax) {
for (y in 0..yMax) {
val infinite = x == 0 || y == 0 || x == xMax || y == yMax
val distances = points.map { entry ->
Pair(entry.key, manhattanDistance(Pair(x, y), entry.value))
}.sortedBy { entry -> entry.second }
if(distances[0].second < distances[1].second) {
if(infinite) infinites.add(distances[0].first)
areas.computeIfPresent(distances[0].first, { _, v -> v + 1 })
}
}
}
infinites.forEach { areas.remove(it) }
println(areas.maxBy { it.value }!!.value)
}
fun manhattanDistance(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Int = abs(p1.first - p2.first) + abs(p1.second - p2.second)
| 0 | C++ | 3 | 9 | 82f5e482c0c3c03fd39e46aa70cab79391ed2dc5 | 1,298 | programming-challenges | MIT License |
src/main/Utils.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | import java.io.File
import kotlin.math.abs
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
fun <T> List<T>.second() = this[1]
fun <T, R> Pair<T, R>.reverse() = second to first
data class Point(val x: Int, val y: Int) {
fun neighbours(includeCenter: Boolean = false): List<Point> =
if (includeCenter) listOf(Point(x, y + 1), Point(x + 1, y), this, Point(x, y - 1), Point(x - 1, y))
else listOf(Point(x, y + 1), Point(x + 1, y), Point(x, y - 1), Point(x - 1, y))
fun allNeighbours(): Set<Point> =
setOf(
Point(x - 1, y - 1),
Point(x, y - 1),
Point(x + 1, y - 1),
Point(x - 1, y),
Point(x + 1, y),
Point(x - 1, y + 1),
Point(x, y + 1),
Point(x + 1, y + 1)
)
fun distanceTo(other: Point) = abs(x - other.x) + abs(y - other.y)
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}
fun IntRange.fullyContains(other: IntRange) =
contains(other.first) && contains(other.last)
fun IntRange.overlapsWith(other: IntRange) =
contains(other.first) || contains(other.last)
fun IntRange.union(other: IntRange): IntRange? {
return if (overlapsWith(other))
IntRange(minOf(first, other.first), maxOf(last, other.last))
else null
}
fun List<Int>.findPattern(startIndex: Int = 1): Pair<Int, Int> {
(startIndex..size / 2).forEach { windowSize ->
print("$windowSize\r")
val tmp = this.windowed(windowSize)
tmp.forEachIndexed { index, intList ->
if (index + windowSize >= tmp.size)
return@forEachIndexed
if (intList == tmp[index + windowSize])
return index + 1 to windowSize
}
}
error("no pattern")
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 1,848 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/jetbrains/typofixer/search/SearchResults.kt | bronti | 96,321,194 | false | {"Java": 321793, "Kotlin": 127493} | package com.jetbrains.typofixer.search
import com.jetbrains.typofixer.search.distance.Distance
import com.jetbrains.typofixer.search.index.CombinedIndex
class SortedSearchResults(
private val base: String,
private val maxRoundedError: Int,
wordsByMinPossibleError: Map<Int, Iterator<FoundWord>>,
private val distanceProvider: Distance,
private val sorter: Sorter
) {
private var isValid = true
private val unsortedResult = SearchResults(maxRoundedError, wordsByMinPossibleError, { distanceProvider.roundedMeasure(base, it) })
private fun wordsForRoundedError(error: Int): Sequence<FoundWord> {
assert(error <= maxRoundedError)
assert(error >= 0)
unsortedResult.refillMap(error)
val nextWords = unsortedResult.wordsByMeasure[error] ?: return emptySequence()
return sorter.sort(nextWords.asSequence(), base)
}
fun asSequence(): Sequence<FoundWord> {
if (!isValid) throw IllegalStateException("Search result read twice")
val result = (0..maxRoundedError).asSequence().flatMap { wordsForRoundedError(it) }
isValid = false
return result
}
}
private class SearchResults(
private val maxRoundedError: Int,
private val wordsByMinPossibleError: Map<Int, Iterator<FoundWord>>,
private val measure: (String) -> Int
) {
var wordsByMeasure: Map<Int, Iterator<FoundWord>> = emptyMap()
fun refillMap(minPossibleError: Int) {
val additionalWords: HashMap<Int, MutableList<FoundWord>> = hashMapOf()
wordsByMinPossibleError.keys.filter { it <= minPossibleError }.sorted().forEach { index ->
val nextWords = wordsByMinPossibleError[index]!!
while (nextWords.hasNext()) {
val nextWord = nextWords.next()
val nextError = measure(nextWord.word)
if (nextError > maxRoundedError) continue
if (additionalWords[nextError] == null) {
additionalWords[nextError] = mutableListOf()
}
additionalWords[nextError]!!.add(nextWord)
}
}
val newKeys = wordsByMeasure.keys.toSet() + additionalWords.keys
fun getOldWords(error: Int) = wordsByMeasure[error]?.asSequence() ?: emptySequence()
fun getAdditionalWords(error: Int) = additionalWords[error]?.asSequence() ?: emptySequence()
wordsByMeasure = newKeys.map { it to (getOldWords(it) + getAdditionalWords(it)).iterator() }.toMap()
}
}
class FoundWord(val word: String, val type: FoundWordType)
enum class FoundWordType {
IDENTIFIER_NOT_CLASS, IDENTIFIER_CLASS, KEYWORD;
companion object {
fun getByIndexType(type: CombinedIndex.IndexType) = when (type) {
CombinedIndex.IndexType.KEYWORD -> KEYWORD
CombinedIndex.IndexType.CLASSNAME -> IDENTIFIER_CLASS
CombinedIndex.IndexType.LOCAL_IDENTIFIER,
CombinedIndex.IndexType.KOTLIN_SPECIFIC_FIELD,
CombinedIndex.IndexType.NOT_CLASSNAME -> IDENTIFIER_NOT_CLASS
}
}
}
| 0 | Java | 0 | 0 | 33e436b815a86cc7980fbbd18ffda543fb895122 | 3,105 | typofixer | Apache License 2.0 |
src/Day08.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | import java.lang.Integer.max
private fun heights(): List<List<Int>> {
return readInput("Day08").map { it.map { c -> c.digitToInt() } }
}
private fun part1(h: List<List<Int>>): Int {
val size = h.size
val visible = Array(size) { i ->
BooleanArray(size) { j ->
i == 0 || i == size - 1 || j == 0 || j == size - 1
}
}
for (i in 1 until size - 1) {
var curH = h[i][0]
for (j in 1 until size - 1) {
if (h[i][j] > curH) {
visible[i][j] = true
curH = h[i][j]
}
}
curH = h[i][size - 1]
for (j in size - 2 downTo 1) {
if (h[i][j] > curH) {
visible[i][j] = true
curH = h[i][j]
}
}
}
for (j in 1 until size - 1) {
var curH = h[0][j]
for (i in 1 until size - 1) {
if (h[i][j] > curH) {
visible[i][j] = true
curH = h[i][j]
}
}
curH = h[size - 1][j]
for (i in size - 2 downTo 1) {
if (h[i][j] > curH) {
visible[i][j] = true
curH = h[i][j]
}
}
}
return visible.sumOf { arr -> arr.count { it } }
}
private fun part2(h: List<List<Int>>): Int {
var max = 0
val size = h.size
for (i in 0 until size) {
for (j in 0 until size) {
var left = j
for (k in j - 1 downTo 0) {
if (h[i][k] >= h[i][j]) {
left = j - k
break
}
}
var right = size - j - 1
for (k in j + 1 until size) {
if (h[i][k] >= h[i][j]) {
right = k - j
break
}
}
var down = i
for (k in i - 1 downTo 0) {
if (h[k][j] >= h[i][j]) {
down = i - k
break
}
}
var up = size - i - 1
for (k in i + 1 until size) {
if (h[k][j] >= h[i][j]) {
up = k - i
break
}
}
val cur = left * right * down * up
max = max(cur, max)
}
}
return max
}
fun main() {
println(part1(heights()))
println(part2(heights()))
}
| 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 2,424 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day22_reactor_reboot/ReactorReboot.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day22_reactor_reboot
import geom.Cuboid
/**
* Three-space math is easy when it's small! Those huge lines at the end imply
* it's not going to stay that way, however. But whatever. Little looping, a bit
* of filtering, a smidge of cringe, and done!
*
* Part two is simply "remove the 100x100x100 constraint". This requires a
* smarter approach: treating the cuboids as the entity of interest not the
* cubes themselves. As cuboids turn on and off, subdivide them as necessary to
* track cuboids that are entirely on. Once all the steps are completed, compute
* the number of cubes in each lit cuboid and add them up.
*/
fun main() {
util.solve(587785, ::partOne)
util.solve(1167985679908143, ::partTwo)
}
data class Step(val on: Boolean, val cuboid: Cuboid)
// x=10..12,y=10..12,z=10..12
fun String.toCuboid(): Cuboid {
val (x, y, z) = split(',')
.map { dim ->
val (a, b) = dim.split('=')[1]
.split("..")
.map(String::toLong)
a..b
}
return Cuboid(x, y, z)
}
// on x=10..12,y=10..12,z=10..12
fun String.toStep(region: Cuboid? = null): Step {
val parts = split(' ')
var c = parts[1].toCuboid()
if (region != null) {
c = c.intersection(region)
}
return Step(parts[0] == "on", c)
}
fun partOne(input: String) =
Cuboid(-50..50L, -50..50L, -50..50L).let { region ->
solve(input
.lines()
.map { it.toStep(region) })
}
private fun solve(steps: List<Step>) =
steps
.fold(HashSet<Cuboid>()) { reactor, step ->
val next = HashSet<Cuboid>(reactor)
if (step.on) {
next.add(step.cuboid)
}
reactor.forEach { existing ->
val surg = performSurgery(existing, step.cuboid)
if (!surg.isNoop) {
next.remove(existing)
next.addAll(surg.fromOne)
}
}
next
}
.sumOf(Cuboid::size)
fun partTwo(input: String) =
solve(
input
.lines()
.map(String::toStep)
)
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 2,153 | aoc-2021 | MIT License |
src/Day12/Day12.kt | AllePilli | 572,859,920 | false | {"Kotlin": 47397} | package Day12
import checkAndPrint
import get
import getDirectNeighbouringIndices
import indicesOf
import measureAndPrintTimeMillis
import readInput
import java.math.BigInteger
fun main() {
fun prepareInput(input: List<String>): List<List<Int>> = input.map { line ->
line.map { c -> c.code }
}
fun part1(input: List<String>): BigInteger {
val grid = prepareInput(input)
val graph = Graph()
for (i in grid.indices) {
for (j in grid[i].indices) {
val currPos = i to j
val currHeight = when (val height = grid[currPos]) {
'S'.code -> 'a'.code
'E'.code -> 'z'.code
else -> height
}
grid.getDirectNeighbouringIndices(currPos)
.associateWith { neighbourPos ->
when (val height = grid[neighbourPos]) {
'S'.code -> 'a'.code
'E'.code -> 'z'.code
else -> height
}
}
.filterValues { neighbourHeight -> neighbourHeight <= currHeight || neighbourHeight == currHeight + 1 }
.forEach { graph.addDirectedEdge(currPos, it.key) }
}
}
val startPos = grid.indicesOf('S'.code)
val endPos = grid.indicesOf('E'.code)
return graph.dijkstra(startPos, endPos)
}
fun part2(input: List<String>): BigInteger {
val grid = prepareInput(input)
val graph = Graph()
val potentialStartingPositions = mutableListOf<Pair<Int, Int>>()
for (i in grid.indices) {
for (j in grid[i].indices) {
val currPos = i to j
val currHeight = when (val height = grid[currPos]) {
'S'.code -> 'a'.code
'E'.code -> 'z'.code
else -> height
}
if (currHeight == 'a'.code) potentialStartingPositions.add(currPos)
grid.getDirectNeighbouringIndices(currPos)
.associateWith { neighbourPos ->
when (val height = grid[neighbourPos]) {
'S'.code -> 'a'.code
'E'.code -> 'z'.code
else -> height
}
}
.filterValues { neighbourHeight -> neighbourHeight <= currHeight || neighbourHeight == currHeight + 1 }
.forEach { graph.addDirectedEdge(currPos, it.key) }
}
}
val endPos = grid.indicesOf('E'.code)
val virtualStart = Pair(-1, -1)
potentialStartingPositions.forEach { pos ->
graph.addDirectedEdge(virtualStart, pos)
}
return graph.dijkstra(virtualStart, endPos) - BigInteger.ONE // minus one for weight of virtualStart edge
}
val testInput = readInput("Day12_test")
check(part1(testInput) == BigInteger("31"))
check(part2(testInput) == BigInteger("29"))
val input = readInput("Day12")
measureAndPrintTimeMillis {
checkAndPrint(part1(input), BigInteger("497"))
}
measureAndPrintTimeMillis {
checkAndPrint(part2(input), BigInteger("492"))
}
}
private class Graph {
val adjacencyMap: HashMap<Pair<Int, Int>, HashSet<Pair<Int, Int>>> = HashMap()
val weightMap: HashMap<Pair<Int, Int>, HashMap<Pair<Int, Int>, BigInteger>> = HashMap()
fun addDirectedEdge(srcVertex: Pair<Int, Int>, destVertex: Pair<Int, Int>) {
adjacencyMap
.computeIfAbsent(srcVertex) { HashSet() }
.add(destVertex)
weightMap.computeIfAbsent(srcVertex) { HashMap() }[destVertex] = BigInteger.ONE
}
fun dijkstra(srcVertex: Pair<Int, Int>, destVertex: Pair<Int, Int>): BigInteger {
val inf = Int.MAX_VALUE.toBigInteger()
val shortestDistances = adjacencyMap.keys
.associateWith { inf }
.toMutableMap()
.apply { this[srcVertex] = BigInteger.ZERO }
val unvisitedVertices = adjacencyMap.keys.toList().toMutableSet()
var currentVertex: Pair<Int, Int>? = srcVertex
while (unvisitedVertices.isNotEmpty()) {
unvisitedVertices.remove(currentVertex)
adjacencyMap[currentVertex]!!
.filter { it in unvisitedVertices }
.forEach { v ->
val distance = shortestDistances[v]!!
val currDistance = shortestDistances[currentVertex]!! + weightMap[currentVertex]!![v]!!
if (currDistance < distance) {
shortestDistances[v] = currDistance
}
}
currentVertex = unvisitedVertices
.takeUnless { it.isEmpty() }
?.minBy { shortestDistances[it]!! }
}
return shortestDistances[destVertex]!!
}
} | 0 | Kotlin | 0 | 0 | 614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643 | 5,018 | AdventOfCode2022 | Apache License 2.0 |
src/day14/Day14.kt | iulianpopescu | 572,832,973 | false | {"Kotlin": 30777} | package day14
import readInput
private const val DAY = "14"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
fun part1(input: List<String>): Int {
val lines = input.map { it.toPoints() }
return Cave(lines).countSandUnits()
}
fun part2(input: List<String>): Int {
val lines = input.map { it.toPoints() }
return Cave(lines, false).countSandUnits()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(DAY_TEST)
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput(DAY_INPUT)
println(part1(input)) // 901
println(part2(input)) // 24589
}
private class Cave(lines: List<List<Point>>, isInfinite: Boolean = true) {
private val minY: Int = lines.minOf { line -> line.minOf { it.y } }
private val maxY: Int = lines.maxOf { line -> line.maxOf { it.y } }
private val maxX: Int = lines.maxOf { line -> line.maxOf { it.x } }
private val bottomMargin = if (isInfinite) maxX + 1 else maxX + 3
private val leftMargin = if (isInfinite) minY else minY - 250
private val rightMargin = if (isInfinite) maxY else maxY + 250
private val matrix: Array<Array<Char>> = Array(bottomMargin) { Array(rightMargin - leftMargin + 1) { '.' } }
init {
// setting sand source at Point(500, 0), but internal it's stored as (0, 500) reduced to the current bounds
matrix[0][500.reduceY()] = '+'
if (!isInfinite) {
for (i in matrix.last().indices)
matrix.last()[i] = '#'
}
lines.forEach { line ->
line.windowed(2).forEach { (start, end) ->
if (start.y == end.y) {
for (x in minOf(start.x, end.x)..maxOf(start.x, end.x))
matrix[x][start.y.reduceY()] = '#'
} else {
for (y in minOf(start.y, end.y).reduceY()..maxOf(start.y, end.y).reduceY())
matrix[start.x][y] = '#'
}
}
}
}
fun countSandUnits(): Int {
var sandUnits = 0
while (matrix[0][500.reduceY()] == '+' && fall(Point(500.reduceY(), 0))) {
sandUnits++
}
println(this)
return sandUnits
}
private fun nextPosition(point: Point): Point? = when {
matrix[point.x + 1][point.y] == '.' -> point.copy(x = point.x + 1)
matrix[point.x + 1][point.y - 1] == '.' -> point.copy(y = point.y - 1, x = point.x + 1)
matrix[point.x + 1][point.y + 1] == '.' -> point.copy(y = point.y + 1, x = point.x + 1)
else -> null
}
private fun fall(point: Point): Boolean {
var sandPosition = point
var next: Point? = point
try {
while (next != null) {
sandPosition = next
next = nextPosition(next)
}
} catch (e: IndexOutOfBoundsException) {
return false
}
matrix[sandPosition.x][sandPosition.y] = 'o'
return true
}
override fun toString(): String {
return matrix.joinToString(separator = "\n") { it.joinToString(separator = "") }
}
private fun Int.reduceY() = this - leftMargin
}
private data class Point(val y: Int, val x: Int)
private fun String.toPoints() = this
.split(" -> ")
.map { it.split(",") }
.map { (x, y) -> Point(x.toInt(), y.toInt()) }
| 0 | Kotlin | 0 | 0 | 4ff5afb730d8bc074eb57650521a03961f86bc95 | 3,512 | AOC2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day19.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import readInput
import kotlin.math.max
private enum class Material { ORE, CLAY, OBSIDIAN, GEODE }
private typealias Robot = Material
private data class BuildCost(val type: Material, val amount: Int)
private data class Blueprint(val id: Int, val costs: Map<Robot, List<BuildCost>>) {
companion object {
fun fromString(input: String): Blueprint {
// Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 4 ore. Each obsidian robot costs 4 ore and 20 clay. Each geode robot costs 2 ore and 12 obsidian.
val split = input.drop("Blueprint ".length).split(":")
val id = split[0].toInt()
val costs = mutableMapOf<Robot, List<BuildCost>>()
split[1].split(".").filter { it.isNotBlank() }.map { recipe ->
val type = Robot.valueOf(recipe.drop(" Each ".length).takeWhile { it != ' ' }.uppercase())
val cost = recipe.dropWhile { !it.isDigit() }.split(" and ").map {
val (amount, material) = it.split(" ")
BuildCost(Material.valueOf(material.uppercase()), amount.toInt())
}.toList()
costs[type] = cost
}
return Blueprint(id, costs)
}
}
override fun toString() = id.toString()
val maxCost by lazy {
intArrayOf(
costs.values.maxOf { buildCosts -> buildCosts.find { it.type == Material.ORE }?.amount ?: 0 },
costs.values.maxOf { buildCosts -> buildCosts.find { it.type == Material.CLAY }?.amount ?: 0 },
costs.values.maxOf { buildCosts -> buildCosts.find { it.type == Material.OBSIDIAN }?.amount ?: 0 },
Int.MAX_VALUE
)
}
val obsidianForGeode = costs[Material.GEODE]!!.find { it.type == Material.OBSIDIAN }!!.amount
val clayForObsidian = costs[Material.OBSIDIAN]!!.find { it.type == Material.CLAY }!!.amount
}
private class State(
val blueprint: Blueprint,
val timePassed: Int,
val remainingTime: Int,
val inventory: IntArray,
val robots: IntArray
) {
fun canBuild(robot: Robot) =
blueprint.costs[robot]!!.all { (material, amount) -> inventory[material.ordinal] >= amount }
fun shouldBuild(robot: Robot): Boolean {
if (robot == Robot.GEODE) return true
// false, if we already produce more than the most expensive robot costs
return (robots[robot.ordinal] < blueprint.maxCost[robot.ordinal]) &&
// or our inventory is already full enough to the build most expensive robot in each remaining round
(inventory[robot.ordinal] < blueprint.maxCost[robot.ordinal] * remainingTime)
}
fun harvest(): State {
val newInventory = inventory.clone()
Robot.values().forEach { type ->
newInventory[type.ordinal] = inventory[type.ordinal] + robots[type.ordinal]
}
return State(blueprint, timePassed + 1, remainingTime - 1, newInventory, robots)
}
fun build(robot: Robot): State {
val newInventory = inventory.clone()
val newRobots = robots.clone()
blueprint.costs[robot]!!.forEach { (material, amount) ->
newInventory[material.ordinal] = inventory[material.ordinal] - amount
}
newRobots[robot.ordinal] = robots[robot.ordinal] + 1
return State(blueprint, timePassed, remainingTime, newInventory, newRobots)
}
/**
* Upper bound on how much geode we can harvest in this state
*/
val maxGeodePossible by lazy {
var geodeRobots = robots[Robot.GEODE.ordinal]
var obsidianRobots = robots[Robot.OBSIDIAN.ordinal]
var clayRobots = robots[Robot.CLAY.ordinal]
var geodes = inventory[Material.GEODE.ordinal]
var obsidian = inventory[Material.OBSIDIAN.ordinal]
var clay = inventory[Material.CLAY.ordinal]
repeat(remainingTime) {
// for the maximum, we can just assume that we build every possible robot in each round (ignoring ore as we
// should be able to "build nothing" to save ore etc.)
if (obsidian >= blueprint.obsidianForGeode) {
geodeRobots++
obsidianRobots++
clayRobots++
obsidian -= blueprint.obsidianForGeode
} else if (clay >= blueprint.clayForObsidian) {
obsidianRobots++
clayRobots++
clay -= blueprint.clayForObsidian
} else {
clayRobots++
}
geodes += geodeRobots
obsidian += obsidianRobots
clay += clayRobots
}
geodes
}
}
private var globalBest = 0
private fun collectGeodesRecursive(state: State): Int {
return if (state.remainingTime == 1) {
val s = state.harvest()
s.inventory[Material.GEODE.ordinal]
} else if (state.maxGeodePossible < globalBest) {
0
} else {
// every robot harvests its material
val stateHarvesting = state.harvest()
// build nothing
var bestResult = collectGeodesRecursive(stateHarvesting)
Robot.values().filter { state.canBuild(it) }.filter { state.shouldBuild(it) }.forEach { robot ->
val newState = stateHarvesting.build(robot)
val result = collectGeodesRecursive(newState)
bestResult = max(result, bestResult)
}
globalBest = max(bestResult, globalBest)
bestResult
}
}
private fun part1(input: List<String>): Int {
val blueprints = input.map { Blueprint.fromString(it) }
return blueprints.sumOf { blueprint ->
globalBest = 0
val start = System.currentTimeMillis()
val inventory = IntArray(Material.values().size)
val robots = IntArray(Robot.values().size).also { it[Robot.ORE.ordinal] = 1 }
val state = State(blueprint, 0, 24, inventory, robots)
val geodes = collectGeodesRecursive(state)
println("Blueprint $blueprint -> $geodes, time=${System.currentTimeMillis() - start} ms")
geodes * blueprint.id
}
}
private fun part2(input: List<String>): Int {
val blueprints = input.map { Blueprint.fromString(it) }.take(3)
return blueprints.map { blueprint ->
globalBest = 0
val start = System.currentTimeMillis()
val inventory = IntArray(Material.values().size)
val robots = IntArray(Robot.values().size).also { it[Robot.ORE.ordinal] = 1 }
val state = State(blueprint, 0, 32, inventory, robots)
val geodes = collectGeodesRecursive(state)
println("Blueprint $blueprint -> $geodes, time=${System.currentTimeMillis() - start} ms")
geodes
}.reduce { acc, i -> acc * i }
}
fun main() {
val testInput = readInput("Day19_test", 2022)
check(part1(testInput) == 33)
check(part2(testInput) == 56 * 62)
val input = readInput("Day19", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 6,970 | adventOfCode | Apache License 2.0 |
src/Day07.kt | ChrisCrisis | 575,611,028 | false | {"Kotlin": 31591} | import java.lang.IllegalStateException
const val MAX_DIR_SIZE = 100000
const val MIN_FREE_SPACE = 30000000
const val FILE_SYSTEM_TOTAL = 70000000
class FileTree{
val rootNode: Node = Node("/", null)
fun findDirectoriesWhere(condition: (Node) -> Boolean): List<Node> {
fun Node.getSmallerDirsRec(): List<Node>{
return this.getSubdirs().flatMap {
if (condition.invoke(it)){
listOf(it) + it.getSmallerDirsRec()
} else {
it.getSmallerDirsRec()
}
}
}
return rootNode.getSmallerDirsRec()
}
data class Node constructor(
val name: String,
val parent: Node?,
val children: MutableMap<String, Node>,
private val fileSize: Int = -1
){
val isDirectory = fileSize == -1
fun getSize(): Int{
return if(fileSize == -1)
children.values.sumOf { it.getSize() }
else
fileSize
}
fun getSubdirs() = children.values.filter { it.isDirectory }
override fun toString(): String {
val type = when(fileSize){
-1 -> "dir"
else -> "file"
}
return "$name ($type, size=$fileSize)"
}
constructor(name: String, parent: Node, fileSize: Int): this(name, parent, mutableMapOf(), fileSize)
constructor(name: String, parent: Node?, children: MutableMap<String, Node> = mutableMapOf()): this(name, parent, children, -1)
}
}
fun main() {
fun FileTree.Node.createChildren(data: List<String>){
if(this.children.isNotEmpty()) throw IllegalStateException()
data.forEach {
val split = it.split(" ")
val nodeName = split[1]
children[nodeName] = when(split[0]){
"dir" -> FileTree.Node(nodeName, this)
else -> FileTree.Node(nodeName, this, split[0].toInt())
}
}
}
fun parseData(data: String): FileTree {
val commands = data.split("\n$ ")
val fileTree = FileTree()
var currentPositionInTree = fileTree.rootNode
commands.forEach {
when{
it.startsWith("ls") -> {
val listData = it.split("\n")
currentPositionInTree.createChildren(listData.subList(1,listData.size))
}
it.startsWith("cd") -> {
it.removePrefix("cd ").let {
currentPositionInTree = when(it){
"/" -> fileTree.rootNode
".." -> currentPositionInTree.parent!!
else -> currentPositionInTree.children[it]!!
}
}
}
}
}
return fileTree
}
fun part1(data: FileTree): Int {
return data.findDirectoriesWhere{ it.getSize() < MAX_DIR_SIZE }
.sumOf { it.getSize() }
}
fun part2(data: FileTree): Int {
val usedSize = data.rootNode.getSize()
val spaceToFreeUp = MIN_FREE_SPACE + usedSize - FILE_SYSTEM_TOTAL
return data.findDirectoriesWhere{ it.getSize() >= spaceToFreeUp }
.minOf { it.getSize() }
}
val testInput = readInputText("Day07_test")
val testTree = parseData(testInput)
println(part1(testTree))
println(part2(testTree))
check(testTree.rootNode.getSize() == 48381165)
check(part1(testTree) == 95437)
check(part2(testTree) == 24933642)
val input = readInputText("Day07")
val fileTree = parseData(input)
println(part1(fileTree))
println(part2(fileTree))
} | 1 | Kotlin | 0 | 0 | 732b29551d987f246e12b0fa7b26692666bf0e24 | 3,782 | aoc2022-kotlin | Apache License 2.0 |
src/Day05.kt | esteluk | 572,920,449 | false | {"Kotlin": 29185} | fun main() {
fun parseInitialState(input: List<String>): Array<String> {
val rows = input.dropLast(1)
val stackCount = input.last().trim().split(" ").last().toInt()
val stacks = Array<String>(stackCount) { "" }
for (i in rows.lastIndex downTo 0) {
for (j in 0 until stackCount) {
if (rows[i].lastIndex >= (j*4)+2) {
stacks[j] += rows[i].substring((j * 4) + 1, (j * 4) + 2).trim()
}
}
}
println(stacks.joinToString())
return stacks
}
fun part1(input: List<String>): String {
val splitIndex = input.indexOf("")
val initialStateStrings = input.subList(0, splitIndex)
val instructions = input.subList(splitIndex+1, input.size)
val state = parseInitialState(initialStateStrings)
for (row in instructions) {
// println(row)
val count = row.split(" from ").first().split(" ").last().toInt()
val sourceColumnIndex = row.split(" to ").first().takeLast(1).toInt()-1
val destinationColumnIndex = row.split(" to ").last().take(1).toInt()-1
for (i in 1..count) {
val moving = state[sourceColumnIndex].takeLast(1)
state[sourceColumnIndex] = state[sourceColumnIndex].dropLast(1)
state[destinationColumnIndex] = state[destinationColumnIndex] + moving
}
// println(state.joinToString())
}
return state.fold("") { acc, element -> acc + element.last() }
}
fun part2(input: List<String>): String {
val splitIndex = input.indexOf("")
val initialStateStrings = input.subList(0, splitIndex)
val instructions = input.subList(splitIndex+1, input.size)
val state = parseInitialState(initialStateStrings)
for (row in instructions) {
// println(row)
val count = row.split(" from ").first().split(" ").last().toInt()
val sourceColumnIndex = row.split(" to ").first().takeLast(1).toInt()-1
val destinationColumnIndex = row.split(" to ").last().take(1).toInt()-1
val moving = state[sourceColumnIndex].takeLast(count)
state[sourceColumnIndex] = state[sourceColumnIndex].dropLast(count)
state[destinationColumnIndex] = state[destinationColumnIndex] + moving
// println(state.joinToString())
}
return state.fold("") { acc, element -> acc + element.last() }
}
// test if implementation meets criteria from the description, like:
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 | 5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73 | 2,808 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/day07/NoSpaceLeftOnDevice.kt | iamwent | 572,947,468 | false | {"Kotlin": 18217} | package day07
import readInput
class NoSpaceLeftOnDevice(
private val name: String
) {
private fun readDirectories(): Directory {
var root = Directory("/")
var pwd: Directory? = root
return readInput(name)
.drop(1)
.fold(root) { acc, line ->
when {
line == "\$ ls" -> {
}
line == "\$ cd .." -> {
pwd = pwd?.parent
}
line.startsWith("dir") -> {
val chileName = line.split(" ").last()
pwd?.addDirectory(Directory(chileName, pwd))
}
line.startsWith("\$ cd ") -> {
val childName = line.split(" ").last()
pwd = pwd?.cd(childName)
}
else -> {
val (size, name) = line.split(" ")
pwd?.addFile(File(size.toLong(), name))
}
}
acc
}
}
private fun total(directory: Directory, max: Long): Long {
val mySize = if (directory.size > max) 0 else directory.size
val children = directory.children.sumOf { total(it, max) }
return children + mySize
}
fun part1(): Long {
return total(readDirectories(), 100000L)
}
fun part2(): Long {
val root = readDirectories()
val threshold = 30000000L - (70000000L - root.size)
return root.sizes().sorted().first { it >= threshold }
}
}
class Directory(
val name: String,
val parent: Directory? = null,
) {
val children = mutableListOf<Directory>()
val files = mutableListOf<File>()
val size: Long
get() = children.sumOf { it.size } + files.sumOf { it.size }
fun addDirectory(child: Directory) {
children.add(child)
}
fun addFile(file: File) {
files.add(file)
}
fun cd(name: String): Directory {
return children.first { it.name == name }
}
fun sizes(): List<Long> {
return children.map { it.sizes() }.flatten() + size
}
}
data class File(
val size: Long,
val name: String,
)
| 0 | Kotlin | 0 | 0 | 77ce9ea5b227b29bc6424d9a3bc486d7e08f7f58 | 2,280 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/be/swsb/aoc2021/day15/Day15.kt | Sch3lp | 433,542,959 | false | {"Kotlin": 90751} | package be.swsb.aoc2021.day15
import be.swsb.aoc2021.common.Point
import be.swsb.aoc2021.common.Point.Companion.at
object Day15 {
fun solve1(input: List<String>) : Int {
val caveWalls = input.flatMapIndexed { idx, line ->
line.mapIndexed { lineIndex, char -> CaveWall(Point.at(lineIndex, idx), "$char".toInt()) }
}
val scan = Scan(caveWalls)
return scan.findLeastRiskyPath().also { println("Least Risky Path: $it") }.summedRiskLevel
}
fun solve2(input: List<String>) : Int = 0
}
typealias RiskLevel = Int
data class CaveWall(val point: Point, val riskLevel: RiskLevel)
typealias PathBuilder = MutableList<CaveWall>
typealias Path = List<CaveWall>
val Path.summedRiskLevel: Int
get() = this.sumOf { wall -> wall.riskLevel }
data class Scan(val walls: List<CaveWall>) {
private val locations by lazy { walls.associateBy { it.point } }
private val adjacencyList: Map<CaveWall, List<CaveWall>> by lazy{ walls.associateWith { neighboursOf(it.point) } }
fun wallsAt(points: List<Point>): List<CaveWall> =
points.mapNotNull { point -> locations[point] }
fun neighboursOf(point: Point) : List<CaveWall> = wallsAt(point.orthogonalNeighbours())
fun findLeastRiskyPath(): Path {
val start = walls.first().also { println("start: $it") }
val end = walls.last().also { println("end: $it") }
val visited = walls.associateWith { false }.toMutableMap()
return depthFirstSearch(start, end, visited, path = mutableListOf(start), leastRiskyPath = mutableListOf(
CaveWall(at(99,99), Int.MAX_VALUE)
))
}
private fun depthFirstSearch(
from: CaveWall,
to: CaveWall,
visited: MutableMap<CaveWall, Boolean>,
path: PathBuilder = mutableListOf(),
leastRiskyPath: Path
): Path {
fun visit(cavewall: CaveWall) { visited[cavewall] = true }
fun backtrack(cavewall: CaveWall) { visited[cavewall] = false }
if (from == to) {
return if (path.summedRiskLevel < leastRiskyPath.summedRiskLevel) path else leastRiskyPath
}
var currentLeastRiskyPath = leastRiskyPath.toList()
visit(from)
neighboursOf(from.point).filter { it.riskLevel <= from.riskLevel }.forEach { caveWall ->
if (!visited.getValue(caveWall)) {
path += caveWall
currentLeastRiskyPath = depthFirstSearch(caveWall, to, visited, path, leastRiskyPath).toList()
path.removeLast()
}
}
backtrack(from)
return currentLeastRiskyPath
}
} | 0 | Kotlin | 0 | 0 | 7662b3861ca53214e3e3a77c1af7b7c049f81f44 | 2,623 | Advent-of-Code-2021 | MIT License |
src/main/kotlin/kr/co/programmers/P72412.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/374
class P72412 {
fun solution(info: Array<String>, query: Array<String>): IntArray {
val aggregate = mutableMapOf<String, MutableList<Int>>()
// 경우의 수를 집계한다.
for (i in info.indices) {
dfs(aggregate, "", 0, info[i].split(" "))
}
// 이진 탐색으로 숫자를 찾을 것이므로 점수를 오름차순 정렬
for (e in aggregate.entries) {
e.value.sort()
}
// 찾기
val answer = IntArray(query.size)
for (i in query.indices) {
val split = query[i].replace(" and ", "").split(" ")
answer[i] = search(aggregate, split[0], split[1].toInt())
}
return answer
}
private fun dfs(aggregate: MutableMap<String, MutableList<Int>>, key: String, depth: Int, info: List<String>) {
if (depth == 4) {
aggregate[key] = aggregate[key]?.run {
this += info[4].toInt()
this
} ?: mutableListOf(info[4].toInt())
return
}
dfs(aggregate, "$key-", depth + 1, info)
dfs(aggregate, "$key${info[depth]}", depth + 1, info)
}
private fun search(aggregate: MutableMap<String, MutableList<Int>>, key: String, score: Int): Int {
return aggregate[key]?.run {
var start = 0
var end = this.lastIndex
while (start <= end) {
val mid = (start + end) / 2
if (this[mid] < score) {
start = mid + 1
} else {
end = mid - 1
}
}
this.size - start
} ?: 0
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,762 | algorithm | MIT License |
src/Day04.kt | MisterTeatime | 560,956,854 | false | {"Kotlin": 37980} | fun main() {
fun part1(input: List<String>): Int {
return input
.map {line ->
line.split(",")
.map { range ->
IntRange(
range.takeWhile { it != '-' }.toInt()
,range.takeLastWhile { it != '-' }.toInt()
).toSet()
}
}
.map { line ->
val commonElements = line[0].intersect(line[1])
commonElements == line[0] || commonElements == line[1]
}
.count { it }
}
fun part2(input: List<String>): Int {
return input
.map {line ->
line.split(",")
.map { range ->
IntRange(
range.takeWhile { it != '-' }.toInt()
,range.takeLastWhile { it != '-' }.toInt()
).toSet()
}
}
.map { line ->
line[0].intersect(line[1])
}
.count { it.isNotEmpty() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8ba0c36992921e1623d9b2ed3585c8eb8d88718e | 1,399 | AoC2022 | Apache License 2.0 |
src/Day12.kt | Reivax47 | 572,984,467 | false | {"Kotlin": 32685} | fun main() {
fun trouveLesVoisins(monArbre: MutableList<Noeud>, leNoeud: Noeud, largeur: Int, hauteur: Int) {
val x = leNoeud.x
val y = leNoeud.y
val laLettre = leNoeud.letter
val decalX = arrayOf(0, 0, -1, 1)
val decalY = arrayOf(-1, 1, 0, 0)
val decalSens = arrayOf("U", "D", "L", "R")
for (i in 0..3) {
val newX = x + decalX[i]
val newY = y + decalY[i]
if (newX in 0..largeur && newY in 0..hauteur) {
val cible = monArbre.find { it.x == newX && it.y == newY }
if (cible != null && cible.letter < laLettre + 2) {
leNoeud.voisins.add(cible)
}
}
}
}
fun createArbre(input: List<String>): MutableList<Noeud> {
val largeur = input[0].length
val hauteur = input.size
val monArbre = mutableListOf<Noeud>()
for (h in 0 until hauteur) {
for (l in 0 until largeur) {
val lettre = input[h].substring(l, l + 1)[0].toChar()
val leNoeud = Noeud(lettre, l, h)
if (lettre == 'S') {
leNoeud.entree = true
leNoeud.letter = 'a'
} else if (lettre == 'E') {
leNoeud.sortie = true
leNoeud.letter = 'z'
}
monArbre.add(leNoeud)
}
}
monArbre.forEach { it ->
trouveLesVoisins(monArbre, it, largeur - 1, hauteur - 1)
}
return monArbre
}
fun Dijkstra(monArbre: MutableList<Noeud>, depart: Noeud?): Int {
val unVisited = mutableSetOf<Noeud>()
monArbre.forEach { feuille ->
feuille.visited = false
feuille.shortestDistance = 10000000
}
depart!!.shortestDistance = 0
unVisited.add(depart)
do {
val actuel = unVisited.sortedBy { it.shortestDistance }[0]
unVisited.remove(actuel)
actuel.visited = true
val distanceFromDebut = actuel.shortestDistance + 1
actuel.voisins.filter { !it.visited }.forEach { unVoisin ->
if (distanceFromDebut < unVoisin.shortestDistance) {
unVoisin.shortestDistance = distanceFromDebut
}
unVisited.add(unVoisin)
}
} while (unVisited.size > 0)
return monArbre.find { it.sortie }!!.shortestDistance
}
fun part1(input: List<String>): Int {
val monArbre = createArbre(input)
val cible = monArbre.find { it.entree }
return Dijkstra(monArbre, cible)
}
fun part2(input: List<String>): Int {
val monArbre = createArbre(input)
val lesA = monArbre.filter { it.letter == 'a' }
val lesResults = mutableListOf<Int>()
lesA.forEach { it ->
lesResults.add(Dijkstra(monArbre, it))
}
return lesResults.sorted()[0]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
class Noeud(var letter: Char, val x: Int, val y: Int) {
val voisins = mutableListOf<Noeud>()
var shortestDistance: Int = 10000000
var entree = false
var sortie = false
var visited = false
}
| 0 | Kotlin | 0 | 0 | 0affd02997046d72f15d493a148f99f58f3b2fb9 | 3,503 | AD2022-01 | Apache License 2.0 |
src/Day09.kt | KarinaCher | 572,657,240 | false | {"Kotlin": 21749} | fun main() {
fun nextPosition(direction: String, position: Pair<Int, Int>): Pair<Int, Int> = when (direction) {
"R" -> position.first + 1 to position.second
"L" -> position.first - 1 to position.second
"U" -> position.first to position.second + 1
"D" -> position.first to position.second - 1
else -> throw UnsupportedOperationException("Direction $direction not defined")
}
fun tailPosition(head: Pair<Int, Int>, tail: Pair<Int, Int>, direction: String): Pair<Int, Int> {
// should we move tail
if ((Math.abs(head.first - tail.first) <= 1) && (Math.abs(head.second - tail.second)) <= 1) {
return tail
}
var tailX = tail.first
var tailY = tail.second
// moved by X-axis, Y not changed
if (head.second == tail.second || arrayOf("R", "L").contains(direction)) {
tailX = if (head.first > tail.first) tailX + 1 else tailX - 1
if (head.second != tail.second) {
tailY = head.second
}
}
// moved by Y-axis, X not changed
if (head.first == tail.first || arrayOf("U", "D").contains(direction)) {
tailY = if (head.second > tail.second) tailY + 1 else tailY - 1
if (head.first != tail.first) {
tailX = head.first
}
}
return tailX to tailY
}
fun part1(input: List<String>): Int {
val visited = mutableSetOf<Pair<Int, Int>>()
var rope = arrayOf(0 to 0, 0 to 0)
visited.add(rope.last())
for (line in input) {
val split = line.split(" ")
val direction = split[0]
val steps = split[1].toInt()
for (step in 1..steps) {
rope[0] = nextPosition(direction, rope.first())
for (knotNum in 1 until rope.size) {
rope[knotNum] = tailPosition(rope[knotNum - 1], rope[knotNum], direction)
}
println(rope.joinToString(" "))
visited.add(rope.last())
}
}
return visited.size
}
fun part2(input: List<String>): Int {
var result = 0;
return result
}
val testInput = readInput("Day09_test")
val testInput2 = readInput("Day09_2_test")
check(part1(testInput) == 13)
check(part1(testInput2) == 9)
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 17d5fc87e1bcb2a65764067610778141110284b6 | 2,523 | KotlinAdvent | Apache License 2.0 |
src/Day03.kt | ghasemdev | 572,632,405 | false | {"Kotlin": 7010} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (line in input) {
val part1 = line.substring(0 until line.length / 2)
val part2 = line.substring(line.length / 2 until line.length)
val intersect = part1.toSet().intersect(part2.toSet()).first()
sum += if (intersect.isLowerCase()) {
intersect.code - 96
} else {
intersect.code - 38
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
var from = 0
var to = 3
repeat(input.size / 3) {
val lines = input.subList(from, to)
val intersect = lines[0].toSet().intersect(lines[1].toSet()).intersect(lines[2].toSet()).first()
sum += if (intersect.isLowerCase()) {
intersect.code - 96
} else {
intersect.code - 38
}
from += 3
to += 3
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7aa5e7824c0d2cf2dad94ed8832a6b9e4d36c446 | 1,314 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day02/Day02.kt | GrinDeN | 574,680,300 | false | {"Kotlin": 9920} | fun main() {
val part1Map = mapOf<String, Int>(
"A X" to 1 + 3,
"B X" to 1 + 0,
"C X" to 1 + 6,
"A Y" to 2 + 6,
"B Y" to 2 + 3,
"C Y" to 2 + 0,
"A Z" to 3 + 0,
"B Z" to 3 + 6,
"C Z" to 3 + 3
).withDefault { 0 }
fun part1(input: List<String>): Int {
return input.sumOf { part1Map.getValue(it) }
}
val part2Map = mapOf<String, Int>(
"A X" to 3 + 0,
"B X" to 1 + 0,
"C X" to 2 + 0,
"A Y" to 1 + 3,
"B Y" to 2 + 3,
"C Y" to 3 + 3,
"A Z" to 2 + 6,
"B Z" to 3 + 6,
"C Z" to 1 + 6
).withDefault { 0 }
fun part2(input: List<String>): Int {
return input.sumOf { part2Map.getValue(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day02/Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("day02/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f25886a7a3112c330f80ec2a3c25a2ff996d8cf8 | 1,063 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | carotkut94 | 572,816,808 | false | {"Kotlin": 7508} | fun main() {
val input = readInput("Day03")
val map = createMap()
println(part1(input, map))
println(part2(input, map))
}
fun part1(input:List<String>, map:Map<Char,Int>):Int{
return input
.map { it.chunked(it.length / 2) }
.sumOf { item -> map[item.map { it.toSet() }.reduce { left, right -> left intersect right}.first()]?:0 }
}
fun part2(input:List<String>, map:Map<Char,Int>):Int{
return input.chunked(3).sumOf { s ->
val s1 = s[0].toSet()
val s2 = s[1].toSet()
val s3 = s[2].toSet()
val c = (s1 intersect s2 intersect s3).single()
val p = map[c]
p?:0
}
}
fun createMap(): Map<Char, Int> {
return buildMap {
for (i in 1..26) {
putIfAbsent('a' + i - 1, i)
putIfAbsent('A' + i - 1, i + 26)
}
}
}
| 0 | Kotlin | 0 | 0 | ef3dee8be98abbe7e305e62bfe8c7d2eeff808ad | 842 | aoc-2022 | Apache License 2.0 |
src/Day09.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | import kotlin.math.abs
data class Pos(var x: Int, var y: Int) {
fun isFar(otherPos: Pos): Boolean {
return abs(this.x - otherPos.x) > 1 || abs(this.y - otherPos.y) > 1
}
}
fun stepInDirection(pos: Pos, direction: String) {
when (direction) {
"U" -> {
pos.y++
}
"D" -> {
pos.y--
}
"L" -> {
pos.x--
}
"R" -> {
pos.x++
}
}
}
// TODO use only vectors here
fun follow(followed: Pos, follower: Pos) {
if (follower.isFar(followed)) {
// same column
if (followed.x == follower.x) {
follower.y += (followed.y - follower.y) / 2
// if(currentHeadPos.y > follower.y) follower.y++
// else follower.y--
}
// same row
else if (followed.y == follower.y) {
follower.x += (followed.x - follower.x) / 2
// if(currentHeadPos.x > follower.x) follower.x++
// else follower.x--
}
// diagonal
else {
val vector = Pos(followed.x - follower.x, followed.y - follower.y)
if (abs(vector.x) > 1) vector.x /= 2
if (abs(vector.y) > 1) vector.y /= 2
follower.x += vector.x
follower.y += vector.y
}
}
}
class Day09Part1 {
private val visitedPositions = mutableSetOf("0;0")
private val currentHeadPos = Pos(0, 0)
private val currentTailPos = Pos(0, 0)
fun run(moves: List<String>): Int {
for (move in moves) {
val (direction, steps) = move.split(' ')
moveInDirection(direction, steps.toInt())
}
return visitedPositions.size
}
private fun moveInDirection(direction: String, steps: Int) {
for (i in 1..steps) {
stepInDirection(currentHeadPos, direction)
follow(currentHeadPos, currentTailPos)
visitedPositions.add("${currentTailPos.x};${currentTailPos.y}")
}
}
}
class Day09Part2 {
private val visitedPositions = mutableSetOf("0;0")
private val knots = List(10) { Pos(0, 0) }
fun run(moves: List<String>): Int {
for (move in moves) {
val (direction, steps) = move.split(' ')
moveInDirection(direction, steps.toInt())
}
return visitedPositions.size
}
private fun moveInDirection(direction: String, steps: Int) {
for (i in 1..steps) {
stepInDirection(knots[0], direction)
for(j in 0 .. knots.size - 2) {
follow(knots[j], knots[j + 1])
}
visitedPositions.add("${knots.last().x};${knots.last().y}")
}
}
}
fun main() {
val input = readInput("input09_1")
println(Day09Part1().run(input))
println(Day09Part2().run(input))
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 2,847 | advent-of-code | Apache License 2.0 |
src/Day25.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | fun main() {
fun String.toSNAFU(): List<Int> {
return this.map {
when (it) {
'=' -> -2
'-' -> -1
else -> it - '0'
}
}.reversed()
}
fun computeCarry(sum: Int): Pair<Int, Int> {
var cur = sum % 5
var newCarry = sum / 5
when (sum % 5) {
3 -> {
cur = -2
newCarry++
}
4 -> {
cur = -1
newCarry++
}
-3 -> {
cur = 2
newCarry--
}
-4 -> {
cur = 1
newCarry--
}
}
return cur to newCarry
}
fun add(a: List<Int>, b: List<Int>): List<Int> {
val result = mutableListOf<Int>()
var carry = 0
for (i in 0 until maxOf(a.size, b.size)) {
val sum = (a.getOrNull(i) ?: 0) + (b.getOrNull(i) ?: 0) + carry
val (cur, newCarry) = computeCarry(sum)
result.add(cur)
carry = newCarry
}
while (carry != 0) {
val (cur, newCarry) = computeCarry(carry)
result.add(cur)
carry = newCarry
}
return result
}
fun part1(input: List<String>): String {
var ans = listOf(0)
for (sna in input) {
ans = add(ans, sna.toSNAFU())
}
return ans.map {
when (it) {
-2 -> '='
-1 -> '-'
else -> '0' + it
}
}.reversed().joinToString("")
}
println(part1(readInput("data/Day25_test")))
println(part1(readInput("data/Day25")))
}
| 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 1,738 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day04.kt | georgiizorabov | 573,050,504 | false | {"Kotlin": 10501} | fun main() {
fun read(input: List<String>): List<Pair<String, String>> {
println(input)
return input.map { str ->
Pair(
str.split(",")[0],
str.split(",")[1]
)
}
}
fun pred(it: Pair<String, String>): Boolean {
val it1 = Pair(it.first.split('-'), it.second.split('-'))
return (it1.first[0].toInt() <= it1.second[0].toInt() && it1.first[1].toInt() >= it1.second[1].toInt()) || (it1.first[0].toInt() >= it1.second[0].toInt() && it1.first[1].toInt() <= it1.second[1].toInt())
}
fun pred1(it: Pair<String, String>): Boolean {
val it1 = Pair(it.first.split('-'), it.second.split('-'))
return (it1.first[0].toInt() >= it1.second[0].toInt() && it1.first[0].toInt() <= it1.second[1].toInt()) || (it1.second[0].toInt() >= it1.first[0].toInt() && it1.second[0].toInt() <= it1.first[1].toInt())
}
fun part1(input: List<String>): Int {
println(read(input).filter { pred(it) })
return read(input).filter { pred(it) }.size
}
fun part2(input: List<String>): Int {
return read(input).filter { pred1(it) }.size
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | bf84e55fe052c9c5f3121c245a7ae7c18a70c699 | 1,263 | aoc2022 | Apache License 2.0 |
2022/src/main/kotlin/com/github/akowal/aoc/Day07.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
class Day07 {
private val root = loadFileTree()
fun solvePart1(): Long {
val dirs = findAll(root) { it.size <= 100000 }
return dirs.sumOf { it.size }
}
fun solvePart2(): Long {
val spaceToFree = 30000000 - (70000000 - root.size)
val dirs = findAll(root) { it.size >= spaceToFree }
return dirs.minOf { it.size }
}
private fun findAll(dir: Dir, predicate: (Dir) -> Boolean): List<Dir> {
val result = mutableListOf<Dir>()
fun traverse(d: Dir) {
if (predicate(d)) {
result += d
}
d.dirs.values.forEach { traverse(it) }
}
traverse(dir)
return result
}
private fun loadFileTree(): Dir {
val root = Dir("/")
var pwd = root
val input = inputScanner("day07")
while (input.hasNextLine()) {
val s = input.nextLine()
when {
s.startsWith("$ cd ") -> {
pwd = when (val dst = s.substringAfter("$ cd ")) {
".." -> pwd.parent
"/" -> root
else -> pwd.getOrCreateDir(dst)
}
}
s == "$ ls" -> {
while (input.hasNextLine() && !input.hasNext("\\$")) {
val entry = input.nextLine()
if (!entry.startsWith("dir")) {
val name = entry.substringAfter(' ')
val size = entry.substringBefore(' ').toLong()
pwd.files += File(name, size)
}
}
}
}
}
return root
}
private data class File(
val name: String,
val size: Long,
)
private class Dir(
val name: String,
) {
lateinit var parent: Dir
val dirs = mutableMapOf<String, Dir>()
val files = mutableListOf<File>()
val size: Long by lazy { files.sumOf { it.size } + dirs.values.sumOf { it.size } }
fun getOrCreateDir(name: String): Dir {
return dirs.computeIfAbsent(name) { Dir(name).also { it.parent = this } }
}
}
}
fun main() {
val solution = Day07()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 2,415 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/Day05.kt | bacecek | 574,824,698 | false | null | data class Input(
val crates: MutableList<MutableList<String>>,
val commands: List<Command>
)
data class Command(
val howMuch: Int,
val from: Int,
val to: Int,
)
fun main() {
val inputRaw = loadInput("day05_input")
println("""
part1 = ${part1(parseInput(inputRaw))}
part2 = ${part2(parseInput(inputRaw))}
""".trimIndent())
}
fun part1(input: Input): String {
val crates = input.crates
input.commands.forEach { command ->
val from = crates[command.from - 1]
val to = crates[command.to - 1]
for (i in 0 until command.howMuch) {
to.add(from.removeLast())
}
}
return crates.map { it.last() }.joinToString(separator = "")
}
fun part2(input: Input): String {
val crates = input.crates
input.commands.forEach { command ->
val from = crates[command.from - 1]
val to = crates[command.to - 1]
val toAdd = mutableListOf<String>()
for (i in 0 until command.howMuch) {
toAdd.add(from.removeLast())
}
to.addAll(toAdd.reversed())
}
return crates.map { it.last() }.joinToString(separator = "")
}
fun parseInput(inputRaw: String): Input {
val inputLines = inputRaw.lines()
val commandsStartIndex = inputLines.indexOfFirst { it.startsWith("move") }
require(commandsStartIndex >= 4)
return Input(parseCrates(inputLines.take(commandsStartIndex - 2)),
parseCommands(inputLines.subList(commandsStartIndex, inputLines.size)))
}
fun parseCrates(lines: List<String>): MutableList<MutableList<String>> {
val reversed = lines.reversed()
val output = mutableListOf<MutableList<String>>()
val startOffset = 1
val betweenOffset = 4
val numberOfStacks = ((reversed[0].length - startOffset) / betweenOffset) + 1
for (i in 0 until numberOfStacks) {
output.add(mutableListOf())
}
for (i in reversed.indices) {
val line = reversed[i]
var indexInString = startOffset
var indexOfStack = 0
while (indexInString < line.length) {
val candidate = line[indexInString]
if (candidate.isLetter()) {
output[indexOfStack].add(candidate.toString())
}
indexInString += betweenOffset
indexOfStack++
}
}
return output
}
fun parseCommands(lines: List<String>): List<Command> {
return lines.map { line ->
val numbers = line.split(' ').filter { it.toIntOrNull() != null }
Command(
numbers[0].toInt(),
numbers[1].toInt(),
numbers[2].toInt(),
)
}
}
| 0 | Kotlin | 0 | 0 | c9a99b549d97d1e7a04a1c055492cf41653e78bb | 2,648 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | karlwalsh | 573,854,263 | false | {"Kotlin": 32685} | fun main() {
fun priorityOf(char: Char): Int {
val offset = when (char) {
in 'a'..'z' -> 96
in 'A'..'Z' -> 38
else -> throw IllegalArgumentException("Unknown char $char")
}
return char.code - offset
}
fun part1(input: List<String>): Int = input.asInputForPart1().sumOf { priorityOf(it.common()) }
fun part2(input: List<String>): Int = input.asInputForPart2().sumOf { priorityOf(it.common()) }
val input = readInput("Day03")
with(::part1) {
val exampleResult = this(example())
check(exampleResult == 157) { "Part 1 result was $exampleResult" }
println("Part 1: ${this(input)}")
}
with(::part2) {
val exampleResult = this(example())
check(exampleResult == 70) { "Part 2 result was $exampleResult" }
println("Part 2: ${this(input)}")
}
}
private fun List<String>.asInputForPart1(): List<Rucksack> = this.map { contents ->
val midPoint = contents.length / 2
val firstCompartment = contents.substring(0 until midPoint).toSet()
val secondCompartment = contents.substring(midPoint until contents.length).toSet()
Rucksack(firstCompartment, secondCompartment)
}
private fun List<String>.asInputForPart2(): List<Group> = this.asInputForPart1()
.windowed(3, 3, false)
.map { Group(it[0], it[1], it[2]) }
private data class Rucksack(val firstCompartment: Set<Char>, val secondCompartment: Set<Char>) {
fun common(): Char {
val intersect = firstCompartment.intersect(secondCompartment)
assert(intersect.size == 1) { "Assumed rucksack compartments have a single common item, but that didn't hold up: $intersect" }
return intersect.first()
}
fun all(): Set<Char> = firstCompartment.union(secondCompartment)
}
private data class Group(val a: Rucksack, val b: Rucksack, val c: Rucksack) {
fun common(): Char {
val intersect = a.all().intersect(b.all()).intersect(c.all())
assert(intersect.size == 1) { "Assumed rucksacks to have a single common item, but that didn't hold up: $intersect" }
return intersect.first()
}
}
private fun example() = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
""".trimIndent().lines() | 0 | Kotlin | 0 | 0 | f5ff9432f1908575cd23df192a7cb1afdd507cee | 2,406 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | ThijsBoehme | 572,628,902 | false | {"Kotlin": 16547} | fun main() {
fun valueOf(char: Char) =
if (char.isUpperCase()) char.code - 'A'.code + 27
else char.code - 'a'.code + 1
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val firstCompartment = rucksack.take(rucksack.length / 2)
val secondCompartment = rucksack.drop(rucksack.length / 2)
val intersect = firstCompartment.asIterable().toSet() intersect secondCompartment.asIterable().toSet()
check(intersect.size == 1)
val char = intersect.first()
valueOf(char)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { group ->
val intersect = group[0].asIterable().toSet() intersect
group[1].asIterable().toSet() intersect
group[2].asIterable().toSet()
check(intersect.size == 1)
val char = intersect.first()
valueOf(char)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 707e96ec77972145fd050f5c6de352cb92c55937 | 1,270 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day04.kt | kecolk | 572,819,860 | false | {"Kotlin": 22071} | data class ElfAssignment(val elf1: IntRange, val elf2: IntRange){
fun isContained(): Boolean =
(elf1.contains(elf2.first) && elf1.contains(elf2.last)) ||
(elf2.contains(elf1.first) && elf2.contains(elf1.last))
fun isOverlapping(): Boolean =
elf1.contains(elf2.first) ||
elf1.contains(elf2.last) ||
elf2.contains(elf1.first)
companion object{
fun fromString(input: String): ElfAssignment{
val (elf1, elf2) = input.split(",")
return ElfAssignment(elf1.toRange(), elf2.toRange())
}
}
}
fun String.toRange() = IntRange(
start = split("-").first().toInt(),
endInclusive = split("-").last().toInt()
)
fun main() {
fun part1(input: List<String>): Int = input
.map { ElfAssignment.fromString(it) }
.count { it.isContained() }
fun part2(input: List<String>): Int = input
.map { ElfAssignment.fromString(it) }
.count { it.isOverlapping() }
val testInput = readTextInput("Day04_test")
val input = readTextInput("Day04")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 72b3680a146d9d05be4ee209d5ba93ae46a5cb13 | 1,214 | kotlin_aoc_22 | Apache License 2.0 |
src/day02/Day02.kt | hamerlinski | 572,951,914 | false | {"Kotlin": 25910} | package day02
import readInput
import java.lang.Exception
fun main() {
fun part1() {
val input = readInput("Day02", "day02")
val inputIterator = input.iterator()
var solution = 0
inputIterator.forEach {
val myTacticWeapon = Tactic(it[2].toString())
val match = Match(it[0].toString(), myTacticWeapon.decision)
val points = ScoreCalculation(myTacticWeapon.decision, match.result())
solution += points.value
}
println(solution)
}
fun part2() {
val input = readInput("Day02", "day02")
val inputIterator = input.iterator()
var solution = 0
inputIterator.forEach {
val tactic = TrueTactic(it[2].toString())
val myWeapon = MyWeapon(it[0].toString(), tactic.decision)
val points = ScoreCalculation(myWeapon.result(), tactic.decision)
solution += points.value
}
println(solution)
}
part1()
part2()
}
class ScoreCalculation(shape: String, outcome: String) {
private val weaponPoints: Int = Awarding(shape).points
private val resultsPoints: Int = Awarding(outcome).points
val value: Int = weaponPoints.plus(resultsPoints)
}
class Awarding(value: String) {
private val pointsSystem: Map<String, Int> = mapOf(
"A" to 1, // rock > scissors A > C
"B" to 2, // paper > rock B > A
"C" to 3, // scissors > paper C > B
"lose" to 0,
"draw" to 3,
"win" to 6
)
val points = pointsSystem[value] ?: 0
}
class Tactic(value: String) {
private val approach: Map<String, String> = mapOf(
"X" to "A",
"Y" to "B",
"Z" to "C"
)
val decision: String = approach[value] ?: "A"
}
class TrueTactic(value: String) {
private val approach: Map<String, String> = mapOf(
"X" to "lose",
"Y" to "draw",
"Z" to "win"
)
val decision: String = approach[value] ?: "lose"
}
class Match(private val opponentWeapon: String, private val myWeapon: String) {
fun result(): String {
if (opponentWeapon == "A" && myWeapon == "A" || opponentWeapon == "B" && myWeapon == "B" || opponentWeapon == "C" && myWeapon == "C")
return "draw"
return if (opponentWeapon == "A" && myWeapon == "C" || opponentWeapon == "B" && myWeapon == "A" || opponentWeapon == "C" && myWeapon == "B")
"lose"
else "win"
}
}
class MyWeapon(private val opponentWeapon: String, private val desiredOutcome: String) {
fun result(): String {
if (opponentWeapon == "A" && desiredOutcome == "draw" || opponentWeapon == "B" && desiredOutcome == "lose" || opponentWeapon == "C" && desiredOutcome == "win")
return "A"
if (opponentWeapon == "B" && desiredOutcome == "draw" || opponentWeapon == "C" && desiredOutcome == "lose" || opponentWeapon == "A" && desiredOutcome == "win")
return "B"
if (opponentWeapon == "C" && desiredOutcome == "draw" || opponentWeapon == "A" && desiredOutcome == "lose" || opponentWeapon == "B" && desiredOutcome == "win")
return "C"
else {
throw Exception()
}
}
} | 0 | Kotlin | 0 | 0 | bbe47c5ae0577f72f8c220b49d4958ae625241b0 | 3,228 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/year2023/day18/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day18
import arrow.core.nonEmptyListOf
import utils.Direction
import utils.Point
import utils.ProblemPart
import utils.applyPickTheorem
import utils.move
import utils.readInputs
import utils.runAlgorithm
fun main() {
val (realInput, testInputs) = readInputs(2023, 18)
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(62),
algorithm = ::part1,
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(952408144115),
algorithm = ::part2,
),
)
}
private fun part1(input: List<String>): Long {
return parsePart1(input).fold(mutableListOf(Point())) { points, movement ->
generateSequence(points.last()) { it.move(movement.direction) }
.take(movement.steps + 1)
.drop(1)
.let(points::addAll)
points
}.applyPickTheorem()
}
private fun parsePart1(input: List<String>): List<Input> {
return input.asSequence()
.mapNotNull(parsingRegex1::matchEntire)
.map { match ->
Input(
steps = match.groupValues[2].toInt(),
direction = when (match.groupValues[1]) {
"R" -> Direction.Right
"L" -> Direction.Left
"U" -> Direction.Up
else -> Direction.Down
},
)
}
.toList()
}
private val parsingRegex1 = "([A-Z]) (\\d+) .*".toRegex()
private fun part2(input: List<String>): Long {
return parsePart2(input).fold(mutableListOf(Point())) { points, movement ->
generateSequence(points.last()) { it.move(movement.direction) }
.take(movement.steps + 1)
.drop(1)
.let(points::addAll)
points
}.applyPickTheorem()
}
private fun parsePart2(input: List<String>): List<Input> {
return input.asSequence()
.mapNotNull(parsingRegex2::matchEntire)
.map { match ->
Input(
steps = match.groupValues[1].toInt(16),
direction = when (match.groupValues[2]) {
"0" -> Direction.Right
"2" -> Direction.Left
"3" -> Direction.Up
else -> Direction.Down
},
)
}
.toList()
}
private val parsingRegex2 = ".* \\(#(\\p{XDigit}{5})(\\d)\\)".toRegex()
private data class Input(
val steps: Int,
val direction: Direction,
)
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 2,582 | Advent-of-Code | Apache License 2.0 |
src/day15/day15.kt | felldo | 572,762,654 | false | {"Kotlin": 76496} | import kotlin.math.abs
data class Sensor(var x: Long, var y: Long, var maxDistance: Long)
data class Beacon(var x: Long, var y: Long)
fun main() {
fun findMaxDistance(s: Sensor, b: Beacon) {
val xDist = abs(s.x - b.x)
val yDist = abs(s.y - b.y)
s.maxDistance = xDist + yDist
}
fun spotsCovered(s: Sensor, row: Long): Pair<Long, Long>? {
val yDist = abs(s.y - row)
if (yDist > s.maxDistance) {
return null
}
val xDist = s.maxDistance - yDist
return (Pair(s.x - xDist, s.x + xDist))
}
fun part1(input: List<String>, row: Long): Long {
val sensors = mutableListOf<Sensor>()
val beacons = mutableSetOf<Beacon>()
val regex = Regex("-*\\d+")
for (line in input) {
// Sensor at x=2, y=18: closest beacon is at x=-2, y=15
val nums = regex.findAll(line).map { it.value }.toList()
sensors.add(Sensor(nums[0].toLong(), nums[1].toLong(), 0))
val beacon = Beacon(nums[2].toLong(), nums[3].toLong())
beacons.add(beacon)
findMaxDistance(sensors.last(), beacon)
}
val ranges = mutableListOf<Pair<Long, Long>>()
for (s in sensors) {
val covered = spotsCovered(s, row)
if (covered != null) {
ranges.add(covered)
}
}
val newRanges = ranges.toMutableList()
var overlaps = true
while(overlaps) {
overlaps = false
for (i in ranges.indices) {
for (j in i + 1 until ranges.size) {
// 1 2 3 4
// a------b a-------b a-b a--------b
// c-------d c--------d c-------d c-d
val a = ranges[i].first
val b = ranges[i].second
val c = ranges[j].first
val d = ranges[j].second
if (a <= d && b >= c) {
val overLeft = Math.min(a, c)
val overRight = Math.max(b, d)
newRanges.remove(ranges[i])
newRanges.remove(ranges[j])
newRanges.add(Pair(overLeft, overRight))
overlaps = true
break
}
}
}
ranges.clear()
ranges.addAll(newRanges)
}
val beaconsOnRow = beacons.count { it.y == row }
return ranges.sumOf { it.second - it.first + 1 } - beaconsOnRow
}
fun part2(input: List<String>, maxCoordinate: Long): Long {
val sensors = mutableListOf<Sensor>()
val beacons = mutableSetOf<Beacon>()
val regex = Regex("-*\\d+")
for (line in input) {
// Sensor at x=2, y=18: closest beacon is at x=-2, y=15
val nums = regex.findAll(line).map { it.value }.toList()
sensors.add(Sensor(nums[0].toLong(), nums[1].toLong(), 0))
val beacon = Beacon(nums[2].toLong(), nums[3].toLong())
beacons.add(beacon)
findMaxDistance(sensors.last(), beacon)
}
for (row in 0 until maxCoordinate) {
val ranges = mutableListOf<Pair<Long, Long>>()
for (s in sensors) {
val covered = spotsCovered(s, row)
if (covered != null) {
ranges.add(covered)
}
}
val newRanges = ranges.toMutableList()
var overlaps = true
while (overlaps) {
overlaps = false
for (i in ranges.indices) {
for (j in i + 1 until ranges.size) {
// 1 2 3 4
// a------b a-------b a-b a--------b
// c-------d c--------d c-------d c-d
val a = ranges[i].first
val b = ranges[i].second
val c = ranges[j].first
val d = ranges[j].second
if (a <= d && b >= c) {
val overLeft = Math.min(a, c)
val overRight = Math.max(b, d)
newRanges.remove(ranges[i])
newRanges.remove(ranges[j])
newRanges.add(Pair(overLeft, overRight))
overlaps = true
break
}
}
}
ranges.clear()
ranges.addAll(newRanges)
}
if (ranges.size > 1) {
return if (ranges[0].first < ranges[1].first) {
(ranges[0].second + 1) * 4_000_000 + row
} else {
(ranges[1].second + 1) * 4_000_000 + row
}
}
}
return 0L
}
val input = readInput("Day15")
println(part1(input, 2_000_000L))
println(part2(input, 4_000_000))
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 5,270 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day12/Solution.kt | chipnesh | 572,700,723 | false | {"Kotlin": 48016} | package day12
import Coords
import findAll
import findFirst
import get
import getNeighbours
import readInput
import toCharMatrix
fun main() {
fun part1(input: List<String>): Int {
return HeightMap.ofInput(input).minStepsFromStart()
}
fun part2(input: List<String>): Int {
return HeightMap.ofInput(input).minStepsFromAnyA()
}
//val input = readInput("test")
val input = readInput("prod")
println(part1(input))
println(part2(input))
}
data class Step(val coords: Coords, val distance: Int = 0) {
fun moveTo(coords: Coords): Step {
return Step(coords, distance + 1)
}
}
data class HeightMap(
val map: List<List<Char>>
) {
val start = setOf(map.findFirst('S'))
val anyA = map.findAll('a').toSet()
val end = map.findFirst('E')
private fun distanceTo(destination: Set<Coords>): Int {
val steps = ArrayDeque(listOf(Step(end)))
val visited = mutableSetOf(end)
while (steps.isNotEmpty()) {
val current = steps.removeFirst()
val coords = current.coords
if (coords in destination) return current.distance
coords.getNeighbours(map)
.filterNot(visited::contains)
.filter { coords.canClimbTo(it) }
.onEach(visited::add)
.map(current::moveTo)
.forEach(steps::add)
}
error("oops")
}
fun minStepsFromStart() = distanceTo(start)
fun minStepsFromAnyA() = distanceTo(anyA)
private fun Coords.canClimbTo(other: Coords): Boolean {
val thisHeight = getHeight(this)
val otherHeight = getHeight(other)
return otherHeight >= thisHeight - 1
}
private fun getHeight(coords: Coords) =
when (val char = map[coords]) {
'S' -> 'a'
'E' -> 'z'
else -> char
}.code
companion object {
fun ofInput(input: List<String>): HeightMap {
return HeightMap(input.toCharMatrix())
}
}
}
| 0 | Kotlin | 0 | 1 | 2d0482102ccc3f0d8ec8e191adffcfe7475874f5 | 2,039 | AoC-2022 | Apache License 2.0 |
src/Day15.kt | Aldas25 | 572,846,570 | false | {"Kotlin": 106964} | import kotlin.math.abs
fun main() {
open class Point(val x: Int, val y: Int)
class Sensor(x: Int, y: Int, val beacon: Point) : Point(x, y)
fun dist(a: Point, b: Point): Int {
return abs(a.x - b.x) + abs(a.y - b.y)
}
fun canBeBeacon(pos: Point, sensors: List<Sensor>): Boolean {
for (sensor in sensors) {
if (sensor.beacon.x == pos.x && sensor.beacon.y == pos.y)
return true
if (dist(sensor, pos) <= dist(sensor, sensor.beacon))
return false
}
return true
}
fun part1(sensors: List<Sensor>, y: Int): Int {
var ans = 0
for (x in -10000000..10000000) {
if (!canBeBeacon(Point(x, y), sensors))
ans++
}
return ans
}
fun part2(sensors: List<Sensor>, maxCoord: Int): Long {
fun tuningFrequency(x: Int, y: Int): Long {
val xLong = x.toLong()
val yLong = y.toLong()
return xLong * 4000000L + yLong
}
fun updateY(x: Int, origY: Int): Int {
var y = origY
for (sensor in sensors) {
if (dist(sensor, Point(x, y)) <= dist(sensor, sensor.beacon)) {
// inside sensor's range
y = sensor.y + dist(sensor, sensor.beacon) + 1 - abs(sensor.x - x)
}
}
return y
}
var last: Point
for (x in 0..maxCoord) {
var y = 0
last = Point(x, y)
while (y <= maxCoord) {
y = updateY(x, y)
if (x == last.x && y == last.y)
return tuningFrequency(x, y)
last = Point(x, y)
}
}
return -1
}
fun parseSensor(line: String): Sensor {
val parts = line.split(
"Sensor at x=", ", y=", ": closest beacon is at x="
)
val sensorX = parts[1].toInt()
val sensorY = parts[2].toInt()
val beaconX = parts[3].toInt()
val beaconY = parts[4].toInt()
return Sensor(sensorX, sensorY, Point(beaconX, beaconY))
}
fun parseSensors(input: List<String>): List<Sensor> {
val sensors: MutableList<Sensor> = mutableListOf()
for (line in input)
sensors.add(parseSensor(line))
return sensors
}
val filename =
// "inputs/day15_sample"
"inputs/day15"
val lineY = // part1
// 10
2000000
val searchSpace = // part2
// 20
4000000
val input = readInput(filename)
val sensors1 = parseSensors(input)
val sensors2 = parseSensors(input)
println("Part 1: ${part1(sensors1, lineY)}")
println("Part 2: ${part2(sensors2, searchSpace)}")
} | 0 | Kotlin | 0 | 0 | 80785e323369b204c1057f49f5162b8017adb55a | 2,793 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/Day7_2.kt | vincent-mercier | 726,287,758 | false | {"Kotlin": 37963} | import java.io.File
import java.io.InputStream
private val orderedCards = "AKQT98765432J".reversed()
private class Hand2(val cards: String): Comparable<Hand2> {
enum class HandType(val value: Int) {
IMPOSSIBLE(-1),
HIGH_CARD(0),
ONE_PAIR(1),
TWO_PAIR(2),
THREE_OF_A_KIND(3),
FULL_HOUSE(4),
FOUR_OF_A_KIND(5),
FIVE_OF_A_KIND(6)
}
private val cardMap: Map<Char, Int> = cards.fold(mutableMapOf()) { acc, elem ->
acc[elem] = acc.getOrDefault(elem, 0) + 1
acc
}
fun type(): HandType {
val jCount = this.cardMap['J']
return when {
this.cardMap.size == 5 -> {
if (jCount == 1)
HandType.ONE_PAIR
else
HandType.HIGH_CARD
}
this.cardMap.size == 4 -> {
if (jCount == 2 || jCount == 1)
HandType.THREE_OF_A_KIND
else
HandType.ONE_PAIR
}
this.cardMap.size == 3 -> {
if (this.cardMap.values.any { it == 3 })
if (jCount == 1)
HandType.FOUR_OF_A_KIND
else if (jCount == 3)
HandType.FOUR_OF_A_KIND
else
HandType.THREE_OF_A_KIND
else
if (jCount == 1)
HandType.FULL_HOUSE
else if (jCount == 2)
HandType.FOUR_OF_A_KIND
else
HandType.TWO_PAIR
}
this.cardMap.size == 2 -> {
if (this.cardMap.values.any { it == 4 })
if (jCount == 1 || jCount == 4)
HandType.FIVE_OF_A_KIND
else
HandType.FOUR_OF_A_KIND
else
if (jCount == 2 || jCount == 3)
HandType.FIVE_OF_A_KIND
else
HandType.FULL_HOUSE
}
this.cardMap.size == 1 -> HandType.FIVE_OF_A_KIND
else -> HandType.IMPOSSIBLE
}
}
override fun compareTo(other: Hand2): Int {
val comparison = this.type().value.compareTo(other.type().value)
if (comparison == 0) {
for (index in this.cards.indices) {
if (this.cards[index] != other.cards[index]) {
return orderedCards.indexOf(this.cards[index]).compareTo(orderedCards.indexOf(other.cards[index]))
}
}
return 0
} else {
return comparison
}
}
}
fun main() {
val cardsRegex = "(?<handCards>[$orderedCards]+) (?<bid>\\d+)".toRegex()
val inputStream: InputStream = File("./src/main/resources/day7.txt").inputStream()
val inputText = inputStream.bufferedReader().readLines()
val input = inputText.asSequence()
.map { cardsRegex.find(it) }
.map { Hand2(it!!.groups["handCards"]!!.value) to it.groups["bid"]!!.value.toInt() }
.sortedBy { it.first }
println(
input.mapIndexed { index, pair ->
pair.second * (index + 1)
}
.sum()
)
}
| 0 | Kotlin | 0 | 0 | 53b5d0a0bb65a77deb5153c8a912d292c628e048 | 3,319 | advent-of-code-2023 | MIT License |
src/main/kotlin/days/y2023/day09/Day09.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day09
import util.InputReader
typealias PuzzleLine = String
typealias PuzzleInput = List<PuzzleLine>
class Day09(val input: PuzzleInput) {
val lines = input.map { line -> line.split(" ").map { it.toInt() } }
fun partOne() = lines.sumOf { findSequence(it) }
fun partTwo() = lines.sumOf { findSequence2(it) }
fun findSequence(input: List<Int>): Long {
val result = mutableListOf(input.toMutableList())
while (!result.last().isAllZeros()) {
val current = result.last()
val diffs = current.windowed(2).map { it[1] - it[0] }
result.add(diffs.toMutableList())
}
result.last().add(0)
for (y in result.size - 2 downTo 0) {
val add = result[y].last() + result[y + 1].last()
result[y].add(add)
}
return result[0].last().toLong()
}
// part 2 - Where's the tricky part?
// no fancy shenanigens, just copy paste
fun findSequence2(input: List<Int>): Long {
val result = mutableListOf(input.toMutableList())
while (!result.last().isAllZeros()) {
val current = result.last()
val diffs = current.windowed(2).map { it[1] - it[0] }
result.add(diffs.toMutableList())
}
result.last().add(0)
for (y in result.size - 2 downTo 0) {
val yF = result[y].first()
val y1F = result[y + 1].first()
val add = yF - y1F
result[y].add(0, add)
}
return result[0].first().toLong()
}
}
fun List<Int>.isAllZeros(): Boolean = this.all { it == 0 }
fun main() {
val year = 2023
val day = 9
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day)
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day)
fun partOne(input: PuzzleInput) = Day09(input).partOne()
fun partTwo(input: PuzzleInput) = Day09(input).partTwo()
println("Example 1: ${partOne(exampleInput)}")
println("Puzzle 1: ${partOne(puzzleInput)}")
// println("Example 2: ${partTwo(listOf(exampleInput.last()))}")
println("Example 2: ${partTwo(exampleInput)}")
println("Puzzle 2: ${partTwo(puzzleInput)}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 2,227 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day19.kt | michaelYuenAE | 573,094,416 | false | {"Kotlin": 74685} |
import kotlin.math.max
import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
println("start")
readInput("day19_input")
.mapIndexed { i, it ->
val blueprint = it.substringAfter(":")
.trim()
.split(".")
.take(4)
.map { s ->
s.trim().replace(Regex("\\D"), " ").split(" ").mapNotNull { i ->
i.toIntOrNull()
}
}
(i + 1) * search(blueprint, 24) to (if (i < 3) search(blueprint, 32) else 1)
}.fold(0 to 1) { acc, p ->
(acc.first + p.first) to (acc.second * p.second)
}.also(::println)
}.also {
println("time taken: $it ms")
}
}
fun search(
blueprint: List<List<Int>>,
timeLeft: Int,
ores: List<Int> = listOf(0, 0, 0, 0),
machines: List<Int> = listOf(1, 0, 0, 0),
floor: Int = 0
): Int {
if (timeLeft == 0) {
return ores.last()
}
// current geodes + current generation of geodes + if another geode machine was added every minute
val bestPossible = ores.last() + timeLeft * machines.last() + (timeLeft * (timeLeft - 1) / 2)
if (bestPossible < floor) {
return 0
}
// ores/blueprint/machine = [o, c, b, g]
// true if more ore robots are needed
val needed = machines.first() < maxOf(blueprint[1][0], blueprint[2][0], blueprint[3][0])
val ore = ores[0] >= blueprint[0][0] && needed
val clay = ores[0] >= blueprint[1][0]
val obsidian = ores[0] >= blueprint[2][0] && ores[1] >= blueprint[2][1]
val geode = ores[0] >= blueprint[3][0] && ores[2] >= blueprint[3][1]
val newOres = List(ores.size) {
ores[it] + machines[it]
}
var currentBest = floor
if (geode) {
val (o, c, b, g) = newOres
val (om, cm, bm, gm) = machines
val testOres = listOf(o - blueprint[3][0], c, b - blueprint[3][1], g)
val testMachines = listOf(om, cm, bm, gm + 1)
currentBest = max(
currentBest,
search(blueprint, timeLeft - 1, ores = testOres, machines = testMachines, floor = currentBest)
)
}
if (obsidian) {
val (o, c, b, g) = newOres
val (om, cm, bm, gm) = machines
val testOres = listOf(o - blueprint[2][0], c - blueprint[2][1], b, g)
val testMachines = listOf(om, cm, bm + 1, gm)
currentBest = max(
currentBest,
search(blueprint, timeLeft - 1, ores = testOres, machines = testMachines, floor = currentBest)
)
}
if (clay) {
val (o, c, b, g) = newOres
val (om, cm, bm, gm) = machines
val testOres = listOf(o - blueprint[1][0], c, b, g)
val testMachines = listOf(om, cm + 1, bm, gm)
currentBest = max(
currentBest,
search(blueprint, timeLeft - 1, ores = testOres, machines = testMachines, floor = currentBest)
)
}
if (ore) {
val (o, c, b, g) = newOres
val (om, cm, bm, gm) = machines
val testOres = listOf(o - blueprint[0][0], c, b, g)
val testMachines = listOf(om + 1, cm, bm, gm)
currentBest = max(
currentBest,
search(blueprint, timeLeft - 1, ores = testOres, machines = testMachines, floor = currentBest)
)
}
currentBest =
max(currentBest, search(blueprint, timeLeft - 1, ores = newOres, machines = machines, floor = currentBest))
return currentBest
} | 0 | Kotlin | 0 | 0 | ee521263dee60dd3462bea9302476c456bfebdf8 | 3,580 | advent22 | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day19/Day19.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day19
import eu.janvdb.aocutil.kotlin.point3d.Point3D
import eu.janvdb.aocutil.kotlin.point3d.Transformation
import eu.janvdb.aocutil.kotlin.point3d.Transformation.Companion.ALL_ROTATIONS
import eu.janvdb.aocutil.kotlin.readGroupedLines
const val FILENAME = "input19.txt"
fun main() {
val scanners = readGroupedLines(2021, FILENAME).map(Scanner::parse)
var combinedScanner = scanners[0]
val remainingScanners = scanners.toMutableList()
remainingScanners.remove(combinedScanner)
val scannerCoordinates = mutableListOf(Point3D(0, 0, 0))
while (remainingScanners.isNotEmpty()) {
val match = remainingScanners
.map { Pair(it, combinedScanner.combineWith(it)) }
.find { it.second != null } ?: throw RuntimeException("No result")
remainingScanners.remove(match.first)
combinedScanner = match.second!!.first
scannerCoordinates.add(match.second!!.second)
}
println("Part 1: ${combinedScanner.beacons.size}")
val maxDistance = scannerCoordinates.flatMap { scannerCoordinates.map(it::manhattanDistance) }.maxOrNull()
println("Part 2: $maxDistance")
}
class Scanner(val name: String, val beacons: Set<Point3D>) {
/**
* If a match is found with this rotation: returns the combined scanner and the relative position of the other scanner
*/
fun combineWith(other: Scanner): Pair<Scanner, Point3D>? {
val match = ALL_ROTATIONS.map { tryRotation(it, other) }
.find { it != null } ?: return null
return Pair(Scanner(name + "/" + other.name, beacons + match.first), match.second)
}
/**
* If a match is found with this rotation: returns the transformed point and the relative position of the other scanner
*/
private fun tryRotation(rotation: Transformation, other: Scanner): Pair<List<Point3D>, Point3D>? {
val transformedPoints = other.beacons.map { rotation * it }
val mostCommonDistance = beacons.asSequence()
.flatMap { mine -> transformedPoints.map { mine - it } }
.groupingBy { it }.eachCount()
.maxByOrNull { it.value }!!
if (mostCommonDistance.value < 12) return null
return Pair(transformedPoints.map { mostCommonDistance.key + it }, mostCommonDistance.key)
}
override fun toString() = "$name (${beacons.size})"
companion object {
fun parse(lines: List<String>): Scanner {
val name = lines[0].substring(4, lines[0].length - 4)
val coordinates = lines.asSequence().drop(1).map { Point3D.createCommaSeparated(it) }.toSet()
return Scanner(name, coordinates)
}
}
}
| 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,470 | advent-of-code | Apache License 2.0 |
src/main/kotlin/d18_Snailfish/Snailfish.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package d18_Snailfish
import util.Input
import util.Output
import kotlin.math.ceil
import kotlin.math.floor
fun main() {
Output.day(18, "Snailfish")
val startTime = Output.startTime()
val homework = Input.parseLines(filename = "/input/d18_homework.txt")
val sumMagnitude = homework
.map { SnailfishNumber.parse(it) }
.reduce { a, b -> a + b }
.magnitude()
Output.part(1, "Magnitude", sumMagnitude)
val largestSnailAddMagnitude = homework
.mapIndexed { i, left ->
homework.drop(i + 1).map { right ->
listOf(
SnailfishNumber.parse(left) to SnailfishNumber.parse(right),
SnailfishNumber.parse(right) to SnailfishNumber.parse(left)
)
}.flatten()
}.flatten()
.maxOf { (it.first + it.second).magnitude() }
Output.part(2, "Largest Magnitude from Snail Number Pairs", largestSnailAddMagnitude)
Output.executionTime(startTime)
}
sealed class SnailfishNumber {
var parent: SnailfishNumber? = null
abstract fun regularsInOrder(): List<RegularNumber>
abstract fun regularsAsPairs(depth: Int = 0): List<NumberPairs>
abstract fun split(): Boolean
abstract fun magnitude(): Int
private fun root(): SnailfishNumber =
parent?.root() ?: this
operator fun plus(other: SnailfishNumber) =
PairNumber(this, other).apply { reduced() }
fun reduced() {
do {
val reduced = explode() || split()
} while (reduced)
}
private fun explode(): Boolean {
root().regularsAsPairs().firstOrNull { it.depth == 4 }?.pair?.let { exploder ->
val regulars = root().regularsInOrder()
val leftChange = regulars.indexOfFirst { it === exploder.left } - 1
if (leftChange >= 0)
regulars[leftChange].value += (exploder.left as RegularNumber).value
val rightChange = regulars.indexOfFirst { it === exploder.right } + 1
if (rightChange < regulars.size)
regulars[rightChange].value += (exploder.right as RegularNumber).value
(exploder.parent as PairNumber).childHasExploded(exploder)
return true
} ?: return false
}
companion object {
fun parse(n: String): SnailfishNumber {
val list = mutableListOf<SnailfishNumber>()
n.forEach { c ->
when {
c.isDigit() -> list.add(RegularNumber(c.digitToInt()))
c == ']' -> {
val right = list.removeLast()
val left = list.removeLast()
list.add(PairNumber(left, right))
}
}
}
return list.removeFirst()
}
}
}
data class RegularNumber(
var value: Int
) : SnailfishNumber() {
override fun regularsInOrder(): List<RegularNumber> = listOf(this)
override fun regularsAsPairs(depth: Int): List<NumberPairs> = emptyList()
override fun split(): Boolean = false
override fun magnitude(): Int = value
fun splitToPair(splitParent: SnailfishNumber): PairNumber =
PairNumber(
RegularNumber(floor(value.toDouble() / 2.0).toInt()),
RegularNumber(ceil(value.toDouble() / 2.0).toInt())
).apply { this.parent = splitParent }
}
data class PairNumber(
var left: SnailfishNumber,
var right: SnailfishNumber
) : SnailfishNumber() {
init {
left.parent = this
right.parent = this
}
override fun regularsInOrder(): List<RegularNumber> =
this.left.regularsInOrder() + this.right.regularsInOrder()
override fun regularsAsPairs(depth: Int): List<NumberPairs> =
this.left.regularsAsPairs(depth + 1) +
listOf(NumberPairs(depth, this)) +
this.right.regularsAsPairs(depth + 1)
fun childHasExploded(child: PairNumber) {
val replacement = RegularNumber(0).apply { parent = this@PairNumber.parent }
when {
left === child -> left = replacement
else -> right = replacement
}
}
override fun split(): Boolean {
if (left is RegularNumber) {
val actualLeft = left as RegularNumber
if (actualLeft.value >= 10) {
left = actualLeft.splitToPair(this)
return true
}
}
val didSplit = left.split()
if (didSplit) return true
if (right is RegularNumber) {
val actualRight = right as RegularNumber
if (actualRight.value >= 10) {
right = actualRight.splitToPair(this)
return true
}
}
return right.split()
}
override fun magnitude(): Int = (left.magnitude() * 3) + (right.magnitude() * 2)
}
data class NumberPairs(
var depth: Int,
var pair: PairNumber
) | 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 4,961 | advent-of-code-2021 | MIT License |
src/day11/Day11.kt | EdwinChang24 | 572,839,052 | false | {"Kotlin": 20838} | package day11
import readInput
fun main() {
part1()
part2()
}
fun part1() = common(20) { this / 3 }
fun part2() = common(10_000) { this % it.reduce { acc, l -> acc * l } }
fun common(rounds: Int, keptManageable: Long.(MutableList<Long>) -> Long) {
val input = readInput(11)
val items = mutableListOf<MutableList<Long>>()
val operations = mutableListOf<(Long) -> Long>()
val tests = mutableListOf<Long>()
val ifTrue = mutableListOf<Int>()
val ifFalse = mutableListOf<Int>()
for (line in input) when {
line.startsWith(" S") -> items += line.removePrefix(" Starting items: ").split(", ").map { it.toLong() }
.toMutableList()
line.startsWith(" O") -> with(line.removePrefix(" Operation: new = old ").split(' ')) {
operations.add(
if (first() == "+") {
{ it + last().toInt() }
} else if (line.last().isDigit()) {
{ it * last().toInt() }
} else {
{ it * it }
}
)
}
line.startsWith(" T") -> tests += line.split(' ').last().toLong()
line.startsWith(" If t") -> ifTrue += line.split(' ').last().toInt()
line.startsWith(" If f") -> ifFalse += line.split(' ').last().toInt()
}
val totals = MutableList(items.size) { 0L }
repeat(rounds) {
repeat(items.size) { monkey ->
repeat(items[monkey].size) {
val worryLevel = operations[monkey](items[monkey].removeFirst()).keptManageable(tests)
val throwTo = if (worryLevel % tests[monkey] == 0L) ifTrue[monkey] else ifFalse[monkey]
items[throwTo] += worryLevel
totals[monkey]++
}
}
}
val (first, second) = totals.sortedDescending()
println(first * second)
}
| 0 | Kotlin | 0 | 0 | e9e187dff7f5aa342eb207dc2473610dd001add3 | 1,878 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | data class SandPosition(val x: Int, val y: Int) {
companion object {
fun of(string: String): SandPosition {
val (x, y) = string.split(',').map { it.toInt() }
return SandPosition(x, y)
}
}
}
fun main() {
val day = 14
val start = SandPosition(500, 0)
fun unorderedRange(start: Int, finish: Int): IntRange = if (start < finish) {
start..finish
} else {
finish..start
}
fun rangeOfSandPositions(position1: SandPosition, position2: SandPosition) = if (position1.x == position2.x) {
unorderedRange(position1.y, position2.y).map { SandPosition(position1.x, it) }
} else {
unorderedRange(position1.x, position2.x).map { SandPosition(it, position1.y) }
}
fun prepareInput(input: List<String>): MutableList<SandPosition> {
val segments = input.map { line -> line.split(" -> ").map { SandPosition.of(it) } }
val points = segments.flatMap { segment ->
segment.zipWithNext().flatMap { (position1, position2) ->
rangeOfSandPositions(position1, position2)
}
}.distinct().toMutableList()
return points
}
fun SandPosition.fallDown(points: List<SandPosition>): SandPosition? {
val newY = points.filter { it.x == this.x && it.y > this.y }
.minOfOrNull { it.y } ?: return null //infinite fall
return this.copy(
y = newY - 1
)
}
fun SandPosition.moveSides(points: List<SandPosition>): SandPosition? {
for (x in listOf(this.x - 1, this.x + 1)) {
val nextPossiblePosition = SandPosition(x, this.y + 1)
if (nextPossiblePosition !in points) {
return nextPossiblePosition
}
}
return null
}
fun part1(input: List<String>): Int {
val points = prepareInput(input)
var successfulFallAttempt = 0
loop@ while (true) {
var sandBlockPosition = start
while (true) {
sandBlockPosition = sandBlockPosition.fallDown(points) ?: break@loop
sandBlockPosition = sandBlockPosition.moveSides(points) ?: break
}
points.add(sandBlockPosition)
successfulFallAttempt++
}
return successfulFallAttempt
}
fun part2(input: List<String>): Int {
val points = prepareInput(input)
val maxY = points.maxOf { it.y } + 2
for (x in 500 - maxY - 1..500 + maxY + 1)
points.add(SandPosition(x, maxY))
var successfulFallAttempt = 0
loop@ while (true) {
var sandBlockPosition = start
while (true) {
sandBlockPosition = sandBlockPosition.fallDown(points) ?: break@loop
sandBlockPosition = sandBlockPosition.moveSides(points) ?: break
}
points.add(sandBlockPosition)
successfulFallAttempt++
if (sandBlockPosition == start)
break
}
return successfulFallAttempt
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 3,362 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | paul-griffith | 572,667,991 | false | {"Kotlin": 17620} | fun main() {
fun String.toRange(): IntRange {
val (first, last) = split('-')
return first.toInt()..last.toInt()
}
operator fun IntRange.contains(other: IntRange): Boolean {
return other.first >= this.first && other.last <= this.last
}
fun part1(input: Sequence<String>): Int {
// split to pairs
// pair of strings to ranges
// either range contains the other
// count
return input.count { line ->
val (pair1, pair2) = line.split(',')
val range1 = pair1.toRange()
val range2 = pair2.toRange()
range1 in range2 || range2 in range1
}
}
fun part2(input: Sequence<String>): Int {
return input.count { line ->
val (pair1, pair2) = line.split(',')
val range1 = pair1.toRange()
val range2 = pair2.toRange()
range1.intersect(range2).isNotEmpty()
}
}
val sample = sequenceOf(
"2-4,6-8",
"2-3,4-5",
"5-7,7-9",
"2-8,3-7",
"6-6,4-6",
"2-6,4-8",
)
println(part1(readInput("day04")))
println(part2(readInput("day04")))
}
| 0 | Kotlin | 0 | 0 | 100a50e280e383b784c3edcf65b74935a92fdfa6 | 1,192 | aoc-2022 | Apache License 2.0 |
src/Day11.kt | esteluk | 572,920,449 | false | {"Kotlin": 29185} | sealed class Operation {
data class Add(val value: Int): Operation() {
override fun operate(on: Int): Int {
return value + on
}
}
data class Multiply(val value: Int): Operation() {
override fun operate(on: Int): Int {
return value * on
}
}
object Squared: Operation() {
override fun operate(on: Int): Int {
return on * on
}
}
abstract fun operate(on: Int): Int
companion object {
fun parse(input: String): Operation {
val str = input.removePrefix(" Operation: new = ")
return if (str == "old * old") {
Squared
} else if (str.contains("*")) {
val value = str.split(" * ")[1].toInt()
Multiply(value)
} else {
val value = str.split(" + ")[1].toInt()
Add(value)
}
}
}
}
sealed class Test {
data class Divisible(override val value: Int): Test() {
override fun test(worryUnderTest: Int): Boolean {
return worryUnderTest % value == 0
}
}
abstract fun test(worryUnderTest: Int): Boolean
abstract val value: Int
companion object {
fun parse(input: String): Test? {
val str = input.removePrefix(" Test: ")
return if (str.startsWith("divisible by")) {
val value = str.split(" ").last().toInt()
Divisible(value)
} else {
null
}
}
}
}
data class Destinations(val success: Int, val failure: Int) {
companion object {
operator fun invoke(input: List<String>) : Destinations {
val trueDest = input[0].split(" ").last().toInt()
val falseDest = input[1].split(" ").last().toInt()
return Destinations(trueDest, falseDest)
}
}
}
data class Monkey(
var items: MutableList<Int>,
val operation: Operation,
val test: Test,
val destinations: Destinations,
var inspectionCount: Long = 0
) {
companion object {
operator fun invoke(input: List<String>): Monkey {
val items = input[1].substring(18).split(", ").map { it.toInt() }.toMutableList()
val operation = Operation.parse(input[2])
val test = Test.parse(input[3])!!
val destinations = Destinations(input.subList(4, 6))
return Monkey(items, operation, test, destinations)
}
}
}
fun main() {
fun part1(input: List<String>): Long {
val monkeys = input.chunked(7).map { Monkey(it) }
for (i in 0 until 20) {
for (monkey in monkeys) {
monkey.items = monkey.items.map { monkey.operation.operate(it) / 3 }.toMutableList()
monkey.inspectionCount += monkey.items.size
val iter = monkey.items.iterator()
while (iter.hasNext()) {
val item = iter.next()
val destination =
if (monkey.test.test(item)) monkey.destinations.success else monkey.destinations.failure
monkeys[destination].items.add(item)
iter.remove()
}
}
}
// println(monkeys)
val mostActive = monkeys.sortedByDescending { it.inspectionCount }
return mostActive[0].inspectionCount * mostActive[1].inspectionCount
}
fun part2(input: List<String>): Long {
val monkeys = input.chunked(7).map { Monkey(it) }
val modulo = monkeys.map { it.test.value } .fold(1) { acc, iter -> acc * iter }
for (i in 0 until 1000) {
for (monkey in monkeys) {
monkey.items.map { monkey.operation.operate(it) }.forEach {
val destination = if (monkey.test.test(it)) monkey.destinations.success else monkey.destinations.failure
monkeys[destination].items.add(it % modulo)
monkey.inspectionCount += 1
}
monkey.items = mutableListOf()
}
}
// println(monkeys)
val mostActive = monkeys.sortedByDescending { it.inspectionCount }
return mostActive[0].inspectionCount * mostActive[1].inspectionCount
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73 | 4,610 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch0/Problem9.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch0
import dev.bogwalk.util.maths.isCoPrime
import dev.bogwalk.util.maths.pythagoreanTriplet
import kotlin.math.ceil
import kotlin.math.sqrt
import kotlin.math.hypot
/**
* Problem 9: Special Pythagorean Triplet
*
* https://projecteuler.net/problem=9
*
* Goal: If there exists any Pythagorean triplet for which a + b + c = N, find the maximum
* product among all such triplets, otherwise return -1.
*
* Constraints: 1 <= N <= 3000
*
* Pythagorean Triplet: A set of 3 natural numbers, such that a < b < c && a^2 + b^2 = c^2.
*
* e.g.: N = 12
* triplets = {{3,4,5}}; as 3 + 4 + 5 == 12
* product = 3*4*5 = 60
*/
class SpecialPythagoreanTriplet {
fun maxTripletProduct(
n: Int,
solution: (Int) -> Triple<Int, Int, Int>?
): Int {
return solution(n)?.product() ?: -1
}
private fun Triple<Int, Int, Int>.product(): Int = first * second * third
/**
* Solution iterates through values of c and b with some limits:
*
* - c > [n]/3 and can be at most ([n]/2) - 1 (latter proved if c is replaced by its
* Pythagorean equation -> sqrt(a^2 + b^2) < a + b).
*
* - b cannot be <= a.
*
* - Triplet elements must either be all evens OR 2 odds with 1 even. Therefore, the sum of a
* triplet must be even as the sum of evens is an even number and the sum of 2 odds is
* an even number as well.
*
* - The product of the 2 non-hypotenuse sides (a, b) must be divisible by 12.
*
* SPEED (WORST) 2.03ms for N = 3000
*
* @return triple(a, b, c) if one exists, or null.
*/
fun maxTripletBruteBC(n: Int): Triple<Int, Int, Int>? {
if (n % 2 != 0) return null
var maxTriplet: Triple<Int, Int, Int>? = null
nextC@for (c in (n / 2 - 1) downTo (n / 3 + 1)) {
val diff = n - c
nextB@for (b in (c - 1) downTo (diff / 2)) {
val a = diff - b
if (b <= a) continue@nextC
if (a * b % 12 != 0) continue@nextB
if (hypot(a.toDouble(), b.toDouble()) == c.toDouble()) {
val current = Triple(a, b, c)
if (maxTriplet == null || current.product() > maxTriplet.product()) {
maxTriplet = current
}
break
}
}
}
return maxTriplet
}
/**
* Solution iterates through values of a only based on:
*
* - Set {3,4,5} being the smallest existing triplet, so a must be >= 3 and can be
* at most ([n]/3) - 1. Based on a < b and a < c, so 2a < b + c -> 3a < a + b + c.
*
* - Inserting c = [n] - a - b into the formula a^2 + b^2 = c^2 reduces to:
*
* 2ab + 2bn = n^2 - 2an
*
* b = n(n - 2a)/2(n - a)
*
* - Exhaustive search shows that the first maximum triplet found will be the only solution,
* so the loop can be broken early.
*
* - Triplet elements must either be all evens OR 2 odds with 1 even. Therefore, the sum of a
* triplet must be even as the sum of evens is an even number and the sum of 2 odds is
* an even number as well.
*
* - The product of the 2 non-hypotenuse sides (a, b) must be divisible by 12.
*
* SPEED (BETTER) 4.8e4ns for N = 3000
*
* @return triple(a, b, c) if one exists, or null.
*/
fun maxTripletBruteA(n: Int): Triple<Int, Int, Int>? {
if (n % 2 != 0) return null
var maxTriplet: Triple<Int, Int, Int>? = null
for (a in (n / 3 - 1) downTo 3) {
val b = n * (n - 2 * a) / (2 * (n - a))
if (a >= b || a * b % 12 != 0) continue
val c = n - a - b
if (hypot(a.toDouble(), b.toDouble()) == c.toDouble()) {
maxTriplet = Triple(a, b, c)
break
}
}
return maxTriplet
}
/**
* Solution optimised based on:
*
* - All Pythagorean triplets can be reduced to a primitive one by dividing out the
* gcd(a,b,c) = d, and inserting Euclid's formula equations for each side, such that:
*
* a + b + c = 2m(m + n) * d, with m > n > 0.
*
* - A triplet is primitive if only 1 of m or n is even and gcd(m,n) = 1. The latter
* occurs because gdc(a,b) = gcd(b,c) = gcd(c,a) = 1.
*
* SPEED (BEST): 3.5e4ns for N = 3000
*
* @return triple(a, b, c) if one exists, or null.
*/
fun maxTripletOptimised(num: Int): Triple<Int, Int, Int>? {
if (num % 2 != 0) return null
var maxTriplet: Triple<Int, Int, Int>? = null
val limit = num / 2
val mMax = ceil(sqrt(1.0 * limit)).toInt()
for (m in 2 until mMax) {
if (limit % m == 0) { // found even divisor m (> 1) of num/2
// find opposite parity divisor k (= m + n) of num/2m
var k = if (m % 2 == 1) m + 2 else m + 1
var kMax = limit / m
while (kMax % 2 == 0) {
kMax /= 2
}
while (k < 2 * m && k <= kMax) {
if (kMax % k == 0 && isCoPrime(k, m)) {
val current = pythagoreanTriplet(m, k - m, limit / (k * m))
if (maxTriplet == null || current.product() > maxTriplet.product()) {
maxTriplet = current
}
}
k += 2
}
}
}
return maxTriplet
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 5,608 | project-euler-kotlin | MIT License |
src/Day05.kt | rafael-ribeiro1 | 572,657,838 | false | {"Kotlin": 15675} | import java.util.*
fun main() {
fun part1(input: List<String>): String {
val stacks = input.getStacks()
input.getRearrangementProcedures().forEach {
for (i in 1..it.quantity) {
stacks[it.to].push(stacks[it.from].pop())
}
}
return stacks.message
}
fun part2(input: List<String>): String {
val stacks = input.getStacks()
input.getRearrangementProcedures().forEach {
val temp = Stack<Char>()
for (i in 1..it.quantity) {
temp.push(stacks[it.from].pop())
}
for (i in 1..it.quantity) {
stacks[it.to].push(temp.pop())
}
}
return stacks.message
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
fun List<String>.getStacks(): List<Stack<Char>> {
val stacks = mutableListOf<Stack<Char>>()
for (i in 1..(this[indexOf("") - 1].length / 4 + 1)) {
stacks.add(Stack())
}
this.subList(0, indexOf("") - 1)
.reversed()
.forEach {
for (i in 1..it.length step 4) {
if (it[i].isLetter()) {
stacks[i/4].push(it[i])
}
}
}
return stacks
}
val List<Stack<Char>>.message: String
get() = this.fold("") { msg, stack -> "$msg${stack.peek()}" }
fun List<String>.getRearrangementProcedures(): List<Procedure> {
return this.subList(indexOf("") + 1, size)
.map { Procedure.fromString(it) }
}
class Procedure(
val quantity: Int,
val from: Int,
val to: Int
) {
companion object {
fun fromString(procedure: String): Procedure {
return procedure.split(" ").let {
Procedure(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 5cae94a637567e8a1e911316e2adcc1b2a1ee4af | 2,071 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Problem14.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | /**
* Longest Collatz sequence
*
* The following iterative sequence is defined for the set of positive integers:
*
* n → n/2 (n is even)
* n → 3n + 1 (n is odd)
*
* Using the rule above and starting with 13, we generate the following sequence:
*
* 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
* It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been
* proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
*
* Which starting number, under one million, produces the longest chain?
*
* NOTE: Once the chain starts the terms are allowed to go above one million.
*
* https://projecteuler.net/problem=14
*/
fun main() {
println(longestCollatzSequence(1_000_000))
}
private fun longestCollatzSequence(max: Int): Int {
var longest = 0
var answer = 0
for (n in (max / 2) until max) {
val count = collatzSequenceSize(n)
if (count > longest) {
longest = count
answer = n
}
}
max.countLeadingZeroBits()
return answer
}
private val cache = mutableMapOf(1 to 1)
private fun collatzSequenceSize(n: Int): Int {
val cached = cache[n]
if (cached != null) {
return cached
}
val next = if (n % 2 == 0) {
collatzSequenceSize(n / 2) + 1
} else {
collatzSequenceSize((3 * n + 1) / 2) + 2
}
if (cache.size <= 1 shl 30) {
cache[n] = next
}
return next
}
| 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 1,506 | project-euler | MIT License |
src/main/kotlin/days/day21/Day21.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day21
import days.Day
import java.util.*
class Day21 : Day() {
override fun partOne(): Any {
return solve(64)
}
override fun partTwo(): Any {//131 input size
val x = (26501365L - 65) / 131
val values = arrayOf(solve(65), solve(65 + 131), solve(65 + 131 * 2))
val quadrat = quadrat(values)
return x * x * quadrat.first + x * quadrat.second + quadrat.third
}
fun quadrat(values: Array<Int>):Triple<Int,Int,Int> {
//Lagrange
// * a = y0/2 - y1 + y2/2
// * b = -3*y0/2 + 2*y1 - y2/2
// * c = y0
return Triple(
values[0] / 2 - values[1] + values[2] / 2,
-3 * (values[0] / 2) + 2 * values[1] - values[2] / 2,
values[0]
)
}
fun solve(steps: Int): Int {
val inputMap = mutableListOf<Coordinate>()
var startingPosition:Coordinate? = null
readInput().forEachIndexed { y, line ->
line.forEachIndexed { x, char ->
if (char != '#') {
inputMap.add(Coordinate(x, y))
}
if (char == 'S') {
startingPosition = Coordinate(x,y)
}
}
}
if (startingPosition == null) throw Exception("No start found")
val smallestX = inputMap.minOfOrNull { it.x }!!
val largestX = inputMap.maxOfOrNull { it.x }!! + 1
val smallestY = inputMap.minOfOrNull { it.y }!!
val largestY = inputMap.maxOfOrNull { it.y }!! + 1
val queue:Queue<Coordinate> = LinkedList()
queue.add(startingPosition)
val data = mutableListOf<Int>()
for (i in 0 until steps) {
val nextQueue: MutableSet<Coordinate> = mutableSetOf()
while (queue.isNotEmpty()) {
val current = queue.remove()
val neighbours = current.getNeighbours()
val neighboursFiltered = neighbours.toMutableList()
neighbours.forEach {
val mappedX = if (it.x >= largestX) {
it.x % (largestX - smallestX) + smallestX
} else if (it.x < smallestX) {
largestX - ((smallestX - it.x - 1) % (largestX - smallestX)) - 1
} else {
it.x
}
val mappedY = if (it.y >= largestY) {
it.y % (largestY - smallestY) + smallestY
} else if (it.y < smallestY) {
largestY - ((smallestY - it.y - 1) % (largestY - smallestY)) - 1
} else {
it.y
}
if (!inputMap.contains(Coordinate(mappedX, mappedY))) {
neighboursFiltered.remove(it)
}
}
nextQueue.addAll(neighboursFiltered)
}
queue.addAll(nextQueue)
data.add(nextQueue.size)
println("${i}: ${nextQueue.size}")
}
return queue.size
}
}
class Coordinate(val x: Int, val y: Int) {
fun getNeighbours(): List<Coordinate> {
return listOf(
Coordinate(x - 1, y),
Coordinate(x, y - 1),
Coordinate(x, y + 1),
Coordinate(x + 1, y),
)
}
override fun toString(): String {
return "($x, $y)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Coordinate
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
}
| 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 3,859 | advent-of-code_2023 | The Unlicense |
src/main/kotlin/com/sk/set4/452. Minimum Number of Arrows to Burst Balloons.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set4
private fun findMinArrowShots(points: Array<IntArray>): Int {
if (points.isEmpty()) return 0
val sortedPoints =
points.sortedWith(
Comparator { o1, o2 ->
if (o1[0] < o2[0]) -1
else if (o1[0] == o2[0]) 0
else 1
}
)
var count = 1
var i = sortedPoints[0][0]
var j = sortedPoints[0][1]
sortedPoints.forEach { println(it.toList()) }
for (k in 1..sortedPoints.lastIndex) {
val ballon = sortedPoints[k]
if (j < ballon[0]) {
count++
i = ballon[0]
j = ballon[1]
} else {
i = maxOf(i, ballon[0])
j = minOf(j, ballon[0])
}
}
return count
}
//###############################################################################
//
//###############################################################################
class Solution452 {
/*
Maintain overlapping regions with (start, end)
For every new element check whether does it overlap with other regions, update boundry of all of them.
Return no of regions at last.
We can sort the array first to improve time.
*/
fun findMinArrowShots(points: Array<IntArray>): Int {
points.sortBy { it[0] }
var result = 0
var regionX = points[0][0]
var regionY = points[0][1]
for (i in 1 until points.size) {
if (isOverlap(regionX, regionY, points[i][0], points[i][1])) {
regionX = maxOf(regionX, points[1][0])
regionY = minOf(regionY, points[i][1])
} else {
result++
regionX = points[i][0]
regionY = points[i][1]
}
}
return result + 1 // we update arrow count when found new region, for last region add 1 as there is not new region after last
}
private fun isOverlap(
regionX: Int,
regionY: Int,
x: Int,
y: Int
): Boolean { // check start only as array is sorted by start.
return x in regionX..regionY
}
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,137 | leetcode-kotlin | Apache License 2.0 |
src/chapter2/section5/ex8.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter2.section5
import edu.princeton.cs.algs4.In
/**
* 编写一段程序Frequency
* 从标准输入读取一列字符串并按照字符串出现频率由高到低的顺序打印出每个字符串及其出现的次数
*
* 解:读入字符串时,依次放入数组中,
* 打印字符串时,先将字符串排序,统计每个字符串的重复次数,将字符串和重复次数关联成一个新对象,
* 将新对象按重复次数倒序排序,打印字符串及出现次数
*/
class Frequency {
class Node(val item: String, var count: Int) : Comparable<Node> {
override fun compareTo(other: Node): Int {
val countCompare = count.compareTo(other.count)
if (countCompare != 0) return countCompare
return item.compareTo(other.item)
}
override fun toString(): String {
return "[${item}:${count}]"
}
}
var list = mutableListOf<String>()
fun input(item: String) {
list.add(item)
}
fun output(): List<Node> {
list.sort()
if (list.isEmpty()) return emptyList()
val nodeList = mutableListOf<Node>()
nodeList.add(Node(list[0], 1))
for (i in 1 until list.size) {
if (list[i] == list[i - 1]) {
nodeList.last().count++
} else {
nodeList.add(Node(list[i], 1))
}
}
nodeList.sortDescending()
return nodeList
}
}
fun main() {
val input = In("./data/tale.txt")
val frequency = Frequency()
while (!input.isEmpty) {
frequency.input(input.readString())
}
val result = frequency.output()
println("size=${result.size}")
println(result.joinToString(limit = 100))
}
| 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,766 | Algorithms-4th-Edition-in-Kotlin | MIT License |
app/src/main/java/org/watsi/uhp/utils/FuzzySearchUtil.kt | Meso-Health | 227,514,539 | false | null | package org.watsi.uhp.utils
import org.apache.commons.text.similarity.LevenshteinDistance
// This util is based on the answer in the following stackoverflow answer
// https://stackoverflow.com/questions/5859561/getting-the-closest-string-match
object FuzzySearchUtil {
private val distanceAlg = LevenshteinDistance()
// this compares the two strings together splitting them by words to check for full word transposition
// or partial string match (not beginning at the first word)
// could split on multiple delims / have a max # splits
fun wordByWordValue(query: String, choice: String): Int {
val queryWords = query.toLowerCase().split(" ")
val choiceWords = choice.toLowerCase().split(" ")
var wordsTotal = 0
outerLoop@ for (qWord in queryWords) {
var wordBest = choice.length
innerLoop@ for (cWord in choiceWords) {
val currDistance = distanceAlg.apply(qWord, cWord)
if (currDistance < wordBest) {
wordBest = currDistance
}
if (currDistance == 0) {
break@innerLoop
}
}
wordsTotal = wordsTotal + wordBest
}
return wordsTotal
}
// This compares the two strings together ignoring any delimiters that would indicate words
fun fullStringValue(query: String, choice: String): Int {
return distanceAlg.apply(query.toLowerCase(), choice.toLowerCase())
}
fun matchValue(query: String, choice: String, fullStringValue: Int, wordByWordValue: Int, substringValue: Int): Double {
// These two weight determine if you want to give preference to a string that matches
// the un-split choice vs. any one of the delimited words
val fullStringWeight = 0.5
val wordByWordWeight = 0.8
// This is penalizing long strings less for differences than short strings
val lengthWeight = -0.1
// This is giving preference to queries that are an exact substring of a choice
val substringWeight = 2.5
// These are set such that you don't have to have a good match for both full / words
// Whichever is a better score will be a larger portion of the final score
val minWeight = 0.8
val maxWeight = 0.2
return (Math.min(fullStringWeight * fullStringValue, wordByWordWeight * wordByWordValue) * minWeight
+ Math.max(fullStringWeight * fullStringValue, wordByWordWeight * wordByWordValue) * maxWeight
+ lengthWeight * Math.abs(query.length - choice.length)
+ substringValue * substringWeight)
}
fun topMatches(query: String, choices: List<String>?, limit: Int, threshold: Double = 6.0): List<String> {
if (choices == null || query.isBlank()) {
return emptyList()
}
val processedQuery = query.replace("\\s+".toRegex()," ")
val best = choices.map { choice ->
val fullStringValue = fullStringValue(processedQuery, choice)
val wordByWordValue = wordByWordValue(processedQuery, choice)
val substringValue = if (choice.contains(processedQuery, true)) -1 else 1
val value = matchValue(processedQuery, choice, fullStringValue, wordByWordValue, substringValue)
Pair(choice, value)
}
return best.filter { it.second < threshold }.sortedBy { it.second }.map{ it.first }.take(limit)
}
}
| 2 | Kotlin | 3 | 5 | 6e1da182073088f28230fe60a2e09d6f38aab957 | 3,502 | meso-clinic | Apache License 2.0 |
2021/src/main/kotlin/day12_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.mapItems
fun main() {
Day12Imp.run()
}
object Day12Imp : Solution<Map<String, List<String>>>() {
override val name = "day12"
override val parser = Parser.lines.mapItems {
val (start, end) = it.split('-', limit = 2)
start to end
}.map {
it.flatMap { (start, end) ->
listOf(start to end, end to start)
}
.groupBy({ (start, _) -> start }) { (_, end) -> end }
}
val String.isBig get() = toCharArray().all(Char::isUpperCase)
/**
* Perform a breadth-first search to count all the pathys
*/
private fun countPaths(input: Map<String, List<String>>, doubleVisitAlllowed: Boolean = false): Int {
data class Frame(val vertex: String, val visited: Set<String>, val doubleVisitUsed: Boolean)
val stack = ArrayDeque<Frame>()
var count = 0
stack.add(Frame("start", setOf("start"), !doubleVisitAlllowed))
while (stack.isNotEmpty()) {
val (vertex, visited, doubleUsed) = stack.removeFirst()
if (vertex == "end") {
count++
} else {
val vs = input[vertex]!!
for (v in vs) {
if (!v.isBig && v in visited) {
if (!doubleUsed && v != "start" && v != "end") {
// use our double visit for this vertex
stack.add(Frame(v, visited + v, true))
}
} else {
stack.add(Frame(v, visited + v, doubleUsed))
}
}
}
}
return count
}
override fun part1(input: Map<String, List<String>>): Int {
return countPaths(input)
}
override fun part2(input: Map<String, List<String>>): Int {
return countPaths(input, doubleVisitAlllowed = true)
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,722 | aoc_kotlin | MIT License |
src/main/kotlin/Day5.kt | vw-anton | 574,945,231 | false | {"Kotlin": 33295} | import java.util.Stack
fun main() {
val (stack_raw, instructions_raw) = readFile("input/5-test.txt")
.splitBy { it.isBlank() }
.toPair()
val stacks = parseStacks(stack_raw)
val instructions = parseInstructions(instructions_raw)
/*
part1(stacks, instructions)
var result = stacks.map { it.last() }.joinToString(separator = "") { it.toString() }
println("part 1: $result")
check(result == "BSDMQFLSP" || result == "CMZ")
*/
part2(stacks, instructions)
val result = stacks.map { it.last() }.joinToString(separator = "") { it.toString() }
println("part 2: $result")
assert(result == "PGSQBFLDP" || result == "MCD")
}
private fun part1(stacks: List<ArrayDeque<Char>>, instructions: List<Instruction>) {
instructions.forEach { op ->
repeat(op.count) {
if (stacks[op.src].isNotEmpty()) {
val crate = stacks[op.src].removeLast()
stacks[op.dest].addLast(crate)
}
}
}
}
private fun part2(stacks: List<ArrayDeque<Char>>, instructions: List<Instruction>) {
instructions.forEach { op ->
buildList {
repeat(op.count) {
if (stacks[op.src].isNotEmpty())
add(stacks[op.src].removeLast())
}
}
.reversed()
.forEach {
stacks[op.dest].addLast(it)
}
}
}
fun parseStacks(input: List<String>): List<ArrayDeque<Char>> {
val lists = input
.dropLast(1)
.reversed()
.map { line ->
var index = 1
buildList {
while (index <= line.length) {
add(line[index])
index += 4
}
}
}
return transpose(lists)
.map { line -> line.filter { it != ' ' } }
.map { item -> ArrayDeque(item) }
}
fun parseInstructions(input: List<String>) = input.map {
Instruction.fromList(it.split(" "))
}
data class Instruction(val count: Int, val src: Int, val dest: Int) {
companion object {
fun fromList(input: List<String>) = Instruction(
count = input[1].toInt(),
src = input[3].toInt() - 1,
dest = input[5].toInt() - 1
)
}
} | 0 | Kotlin | 0 | 0 | a823cb9e1677b6285bc47fcf44f523e1483a0143 | 2,284 | aoc2022 | The Unlicense |
src/Day02.kt | psabata | 573,777,105 | false | {"Kotlin": 19953} | import Result.*
import Symbol.*
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
fun main() {
fun part1(input: List<Round1>): Int {
return input.sumOf { it.evaluate() }
}
fun part2(input: List<Round2>): Int {
return input.sumOf { it.evaluate() }
}
val testInput1 = InputHelper("Day02_test.txt").readLines { parse1(it) }
val testInput2 = InputHelper("Day02_test.txt").readLines { parse2(it) }
check(part1(testInput1) == 15)
check(part2(testInput2) == 12)
val input1 = InputHelper("Day02.txt").readLines { parse1(it) }
val input2 = InputHelper("Day02.txt").readLines { parse2(it) }
println("Part 1: ${part1(input1)}")
println("Part 2: ${part2(input2)}")
}
private fun parse1(input: String) = Round1(input[0].toSymbol(), input[2].toSymbol())
private fun parse2(input: String) = Round2(input[0].toSymbol(), input[2].toResult())
class Round1(
private val opponent: Symbol,
private val you: Symbol,
) {
fun evaluate(): Int {
return you.value + when(opponent) {
you -> DRAW.value
you.beats() -> WIN.value
you.looses() -> LOOSE.value
else -> throw IllegalStateException()
}
}
}
class Round2(
private val opponent: Symbol,
private val result: Result,
) {
fun evaluate(): Int {
return result.value + when(result) {
DRAW -> opponent.value
WIN -> opponent.looses().value
LOOSE -> opponent.beats().value
}
}
}
enum class Symbol(val value: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3),
;
fun beats(): Symbol =
when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
fun looses(): Symbol =
this.beats().beats()
}
fun Char.toSymbol(): Symbol {
return when (this) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> throw IllegalArgumentException("Not a valid symbol: $this")
}
}
enum class Result(val value: Int) {
LOOSE(0),
DRAW(3),
WIN(6),
;
}
fun Char.toResult(): Result {
return when (this) {
'X' -> LOOSE
'Y' -> DRAW
'Z' -> WIN
else -> throw IllegalArgumentException("Not a valid result: $this")
}
}
| 0 | Kotlin | 0 | 0 | c0d2c21c5feb4ba2aeda4f421cb7b34ba3d97936 | 2,344 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | defvs | 572,381,346 | false | {"Kotlin": 16089} | class CPU {
var regX: Int = 1
var pc: Int = 0
enum class InstructionType(val duration: Int) {
ADDX(2),
NOOP(1),
}
class Instruction(val instruction: InstructionType, vararg val args: Int)
fun execute(instruction: Instruction) {
when (instruction.instruction) {
InstructionType.ADDX -> {
regX += instruction.args[0]
}
InstructionType.NOOP -> {}
}
pc += instruction.instruction.duration
}
}
fun main() {
fun getPc2X(input: List<String>): List<Pair<Int, Int>> {
val myCPU = CPU()
val instructions = input.map { line ->
line.split(" ").let {
val instructionType = CPU.InstructionType.valueOf(it[0].uppercase())
when (it.size) {
1 -> CPU.Instruction(instructionType)
2 -> CPU.Instruction(instructionType, it[1].toInt())
else -> throw Exception("Invalid argument count: \"$line\"")
}
}
}
return (myCPU.pc to myCPU.regX).let {
instructions.map { instruction ->
myCPU.execute(instruction)
myCPU.pc to myCPU.regX
} + it
}.sortedBy { it.first }
}
fun part1(input: List<String>): Int {
val pc2x = getPc2X(input)
fun findFor(pc: Int) = pc2x.findLast { it.first < pc }!!.let { pc * it.second }
val signalStrengths = listOf(20, 60, 100, 140, 180, 220).map { findFor(it) }
return signalStrengths.sum()
}
fun part2(input: List<String>): List<Boolean> {
// FIXME: topleft pixel never shows up
val display = MutableList(240) { false }
val pc2x = getPc2X(input)
fun findFor(pc: Int) = pc2x.findLast { it.first <= pc }!!
for (i in 1..240) {
val current = findFor(i)
val printingValues = listOf(-1, 0, 1).map { (it + i).mod(40) }
if (printingValues.contains(current.second.mod(40))) display[i] = true
}
return display
}
val testInput = readInput("Day10_test")
check(part1(testInput).also { println("Test 1 result was: $it") } == 13140)
val input = readInput("Day10")
println(part1(input))
println(
part2(input)
.map { if (it) '#' else '.' }
.chunked(40)
.joinToString(separator = "") { it.joinToString("") + "\n" }
)
} | 0 | Kotlin | 0 | 1 | caa75c608d88baf9eb2861eccfd398287a520a8a | 2,504 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day09.kt | JohannesPtaszyk | 573,129,811 | false | {"Kotlin": 20483} | fun main() {
class Rope(knotCount: Int) {
val knots: List<MutableList<Pair<Int, Int>>> = buildList {
repeat(knotCount) { add(mutableListOf(Pair(0, 0))) }
}
fun getTailPositions(): Int = knots.last().distinctBy { it }.count()
fun move(input: List<String>) {
input.forEach {
val (direction, moves) = it.split(" ")
repeat(moves.toInt()) {
val head = knots.first()
var (hx, hy) = head.last()
when (direction) {
"U" -> hy += 1
"D" -> hy -= 1
"R" -> hx += 1
"L" -> hx -= 1
else -> throw UnsupportedOperationException("$direction is not a valid move")
}
head.add(hx to hy)
knots.drop(1).forEachIndexed { index: Int, knot: MutableList<Pair<Int, Int>> ->
val (px, py) = knots[index].last()
var (kx, ky) = knot.last()
when {
//Up
kx == px && py - ky == 2 -> {
ky += 1
}
//Down
kx == px && ky - py == 2 -> {
ky -= 1
}
//Right
ky == py && px - kx == 2 -> {
kx += 1
}
//Left
ky == py && kx - px == 2 -> {
kx -= 1
}
//Top-right
(px - kx >= 1 && py - ky == 2) || (px - kx == 2 && py - ky >= 1) -> {
ky += 1
kx += 1
}
//Top-Left
(kx - px >= 1 && py - ky == 2) || (kx - px == 2 && py - ky >= 1) -> {
ky += 1
kx -= 1
}
//Bottom-right
(px - kx >= 1 && ky - py == 2) || (px - kx == 2 && ky - py >= 1) -> {
ky -= 1
kx += 1
}
//Bottom-left
(kx - px >= 1 && ky - py == 2) || (kx - px == 2 && ky - py >= 1) -> {
ky -= 1
kx -= 1
}
}
knot.add(kx to ky)
}
}
}
}
}
fun part1(input: List<String>): Int {
val rope = Rope(2)
rope.move(input)
return rope.getTailPositions()
}
fun part2(input: List<String>): Int {
val rope = Rope(10)
rope.move(input)
return rope.getTailPositions()
}
val testInput = readInput("Day09_test")
val input = readInput("Day09")
println("Part1 test: ${part1(testInput)}")
check(part1(testInput) == 88)
println("Part 1: ${part1(input)}")
println("Part2 test: ${part2(testInput)}")
check(part2(testInput) == 36)
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 1 | 6f6209cacaf93230bfb55df5d91cf92305e8cd26 | 3,515 | advent-of-code-2022 | Apache License 2.0 |
src/main/day20/day20.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day20
import readInput
const val encryptionKey = 811589153L
fun main() {
val input = readInput("main/day20/Day20_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Long {
val original = input.mapIndexed { index, s -> Num(originalPosition = index, number = s.toLong()) }.toMutableList()
val mixed = mix(original)
return summedCoordinates(mixed)
}
fun part2(input: List<String>): Long {
val original = input.mapIndexed { index, s ->
Num(originalPosition = index, number = s.toLong() * encryptionKey)
}.toMutableList()
val mixed = generateSequence(original) { mix(original, it).toMutableList() }.drop(10).first()
return summedCoordinates(mixed)
}
private fun mix(list: MutableList<Num>, original: MutableList<Num> = list, position: Int = 0): List<Num> {
if (position == list.size) return list
val index = list.indexOfFirst {
it == original.firstOrNull { o ->
o.originalPosition == position
}
}
val current = list[index]
var newIndex = (index + current.number) % (list.size - 1)
if (newIndex <= 0) newIndex += list.size - 1
list.removeAt(index)
list.add(newIndex.toInt(), current.move())
return mix(list = list, original = list, position = position + 1)
}
private fun summedCoordinates(mixed: List<Num>): Long {
val zero = mixed.indexOfFirst { it.number == 0L }
val a = mixed[(zero + 1000) % mixed.size].number
val b = mixed[(zero + 2000) % mixed.size].number
val c = mixed[(zero + 3000) % mixed.size].number
return a + b + c
}
data class Num(val originalPosition: Int, val currentPosition: Int = originalPosition, val number: Long, val moved: Int = 0) {
fun move() = copy(moved = moved + 1)
} | 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 1,779 | aoc-2022 | Apache License 2.0 |
src/year2022/22/Day22.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`22`
import kotlin.math.roundToInt
import kotlin.math.sqrt
import readInput
/**
* Point with x,y and side on cube
*/
data class Point(
val x: Int,
val y: Int,
) {
var side: Int = -1
fun heuristic(): Int = x + y
fun copyWithSide(
x: Int = this.x,
y: Int = this.y
): Point {
return copy(
x = x,
y = y
).also { it.side = side }
}
operator fun minus(other: Point): Point {
return copyWithSide(
x = x - other.x,
y = y - other.y
)
}
operator fun plus(other: Point): Point {
return copyWithSide(
x = x + other.x,
y = y + other.y
)
}
override fun toString(): String {
return "Point(x=$x, y=$y, side=$side)"
}
}
sealed class Cell {
abstract val point: Point
data class Empty(override val point: Point) : Cell()
data class Wall(override val point: Point) : Cell()
companion object {
fun from(
x: Int,
y: Int,
string: String
): Cell? {
return when (string) {
" " -> null
"." -> Empty(Point(x, y))
"#" -> Wall(Point(x, y))
else -> error("!! $string")
}
}
fun from(
cell: Cell,
side: Int,
): Cell {
return when (cell) {
is Empty -> cell.copy(cell.point.copyWithSide().also { it.side = side })
is Wall -> cell.copy(cell.point.copyWithSide().also { it.side = side })
}
}
}
}
/**
* Enum for direction for moving point on map
*/
enum class Direction {
RIGHT, LEFT, TOP, DOWN;
}
/**
* Type of rotation command
*/
enum class RotationType {
R, L
}
/**
* Command representing either Move or Rotation
*/
sealed class Command {
data class Move(val amount: Int) : Command() {
override fun toString(): String {
return this.amount.toString()
}
}
data class Rotation(val rotation: RotationType) : Command() {
override fun toString(): String {
return when (this.rotation) {
RotationType.R -> "R"
RotationType.L -> "L"
}
}
}
}
/**
* Calculate number of side on the cube
*/
fun Map<Point, Cell>.sideSize(): Int = sqrt(size / 6f).roundToInt()
fun List<Cell>.sideSize(): Int = sqrt(size / 6f).roundToInt()
/**
* Return map of Point to Cell
*/
fun parseInput(input: List<String>): Map<Point, Cell> {
val listOfListOfCells = input.mapIndexed { y, line ->
line.split("")
.filter { it.isNotEmpty() }
.mapIndexedNotNull { x, s ->
Cell.from(x, y, s)
}
}
.flatten()
val sideOfSquare = listOfListOfCells.sideSize()
val cellsWithSides = listOfListOfCells
.map { cell ->
val xSide = cell.point.x / sideOfSquare
val ySide = cell.point.y / sideOfSquare
Cell.from(cell, xSide + ySide * 6)
}
val groupedIndexes = cellsWithSides
.groupBy { it.point.side }
.keys
.sorted()
val resResMap = cellsWithSides.map { cell ->
val newSide = groupedIndexes.indexOf(cell.point.side) + 1
Cell.from(cell = cell, side = newSide)
}
return resResMap.associateBy { it.point }
}
/**
* Map line with commands to list of [Command]
*/
fun parseInputCommands(input: String): List<Command> {
val mutableList = mutableListOf<Command>()
var currentNumber = ""
input.forEach { char ->
when {
char.isDigit() -> currentNumber += char
char == 'R' -> {
mutableList.add(Command.Move(currentNumber.toInt()))
mutableList.add(Command.Rotation(RotationType.R))
currentNumber = ""
}
char == 'L' -> {
mutableList.add(Command.Move(currentNumber.toInt()))
mutableList.add(Command.Rotation(RotationType.L))
currentNumber = ""
}
}
}
if (currentNumber.isNotEmpty()) {
mutableList.add(Command.Move(currentNumber.toInt()))
}
return mutableList
}
/**
* Map [Direction] to new [RotationType] and provide new [Direction]
*/
fun Direction.applyRotation(rotation: RotationType): Direction {
return when (rotation) {
RotationType.R -> when (this) {
Direction.RIGHT -> Direction.DOWN
Direction.LEFT -> Direction.TOP
Direction.TOP -> Direction.RIGHT
Direction.DOWN -> Direction.LEFT
}
RotationType.L -> when (this) {
Direction.RIGHT -> Direction.TOP
Direction.LEFT -> Direction.DOWN
Direction.TOP -> Direction.LEFT
Direction.DOWN -> Direction.RIGHT
}
}
}
/**
* Create new point, moved in new direction
*/
fun Point.moveInDirection(
currentDirection: Direction,
): Point {
return when (currentDirection) {
Direction.RIGHT -> copyWithSide(x = x + 1)
Direction.LEFT -> copyWithSide(x = x - 1)
Direction.TOP -> copyWithSide(y = y - 1)
Direction.DOWN -> copyWithSide(y = y + 1)
}
}
private fun Point.applyCommand(
isTest: Boolean,
isCube: Boolean,
initialDirection: Direction,
command: Command.Move,
cells: Map<Point, Cell>
): Pair<Point, Direction> {
var resultPoint = this
var currentDirection: Direction = initialDirection
repeat(command.amount) {
val nextPoint = resultPoint.moveInDirection(currentDirection)
if (cells.containsKey(nextPoint)) {
when (cells[nextPoint]!!) {
is Cell.Empty -> resultPoint = cells[nextPoint]!!.point
is Cell.Wall -> return@repeat
}
} else {
val prevPoint = cells[resultPoint]!!.point
val (newPoint: Point, newDir) = if (isCube) {
if (isTest) {
findNextPointOnCubeTestData(
cells = cells,
initialPoint = prevPoint,
initialDirection = currentDirection
)
} else {
findNextPointOnCubeRealData(
cells = cells,
initialPoint = prevPoint,
initialDirection = currentDirection
)
}
} else {
findNextPointOnFlat(
currentDirection = currentDirection,
cells = cells,
resultPoint = resultPoint
) to currentDirection
}
when (cells[newPoint]!!) {
is Cell.Empty -> {
resultPoint = newPoint
currentDirection = newDir
}
is Cell.Wall -> return@repeat
}
}
}
return resultPoint to currentDirection
}
private fun findNextPointOnFlat(
currentDirection: Direction,
cells: Map<Point, Cell>,
resultPoint: Point
): Point {
val nextPoint = when (currentDirection) {
Direction.RIGHT -> cells.keys.filter { it.y == resultPoint.y }.minBy { it.x }
Direction.LEFT -> cells.keys.filter { it.y == resultPoint.y }.maxBy { it.x }
Direction.TOP -> cells.keys.filter { it.x == resultPoint.x }.maxBy { it.y }
Direction.DOWN -> cells.keys.filter { it.x == resultPoint.x }.minBy { it.y }
}
return nextPoint
}
private fun findNextPointOnCubeRealData(
cells: Map<Point, Cell>,
initialPoint: Point,
initialDirection: Direction
): Pair<Point, Direction> {
val nextPoint = when (initialDirection) {
Direction.RIGHT -> when (initialPoint.side) {
2 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 5,
newDir = Direction.LEFT
) { sizeSide, diffPoint ->
indexMinusY(sizeSide, diffPoint)
}
3 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 2,
newDir = Direction.TOP
) { _, diffPoint ->
switchXY(diffPoint)
}
5 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 2,
newDir = Direction.LEFT
) { sizeSide, diffPoint ->
indexMinusY(sizeSide, diffPoint)
}
6 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 5,
newDir = Direction.TOP
) { _, diffPoint ->
switchXY(diffPoint)
}
else -> error("Failed Init Direction: $initialDirection Point: $initialPoint")
}
Direction.LEFT -> when (initialPoint.side) {
1 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 4,
newDir = Direction.RIGHT
) { sizeSide, diffPoint ->
indexMinusY(sizeSide, diffPoint)
}
3 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 4,
newDir = Direction.DOWN
) { _, diffPoint ->
switchXY(diffPoint)
}
4 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 1,
newDir = Direction.RIGHT
) { sizeSide, diffPoint ->
indexMinusY(sizeSide, diffPoint)
}
6 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 1,
newDir = Direction.DOWN
) { sizeSide, diffPoint ->
switchXY(diffPoint)
}
else -> error("Failed Init Direction: $initialDirection Point: $initialPoint")
}
Direction.TOP -> when (initialPoint.side) {
1 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 6,
newDir = Direction.RIGHT
) { _, diffPoint ->
switchXY(diffPoint)
}
2 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 6,
newDir = Direction.TOP
) { sizeSide, diffPoint ->
indexMinusY(sizeSide, diffPoint)
}
4 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 3,
newDir = Direction.RIGHT
) { _, diffPoint ->
switchXY(diffPoint)
}
else -> error("Failed Init Direction: $initialDirection Point: $initialPoint")
}
Direction.DOWN -> when (initialPoint.side) {
6 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 2,
newDir = Direction.DOWN
) { sizeSide, diffPoint ->
indexMinusY(sizeSide, diffPoint)
}
2 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 3,
newDir = Direction.LEFT
) { _, diffPoint ->
switchXY(diffPoint)
}
5 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 6,
newDir = Direction.LEFT
) { _, diffPoint ->
switchXY(diffPoint)
}
else -> error("Failed Init Direction: $initialDirection Point: $initialPoint")
}
}
return nextPoint
}
private fun findNextPointOnCubeTestData(
cells: Map<Point, Cell>,
initialPoint: Point,
initialDirection: Direction
): Pair<Point, Direction> {
val nextPoint = when (initialDirection) {
Direction.RIGHT -> {
when (initialPoint.side) {
1 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 6,
newDir = Direction.LEFT
) { sizeSide, diffPoint ->
diffPoint.copyWithSide(
x = diffPoint.x,
y = diffPoint.y - sizeSide,
)
}
4 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 6,
newDir = Direction.DOWN
) { sizeSide, diffPoint ->
val index = sizeSide - 1
diffPoint.copyWithSide(
x = index - diffPoint.y,
y = index - diffPoint.x,
)
}
6 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 1,
newDir = Direction.LEFT
) { sizeSide, diffPoint ->
indexMinusY(sizeSide, diffPoint)
}
else -> error("Failed Init Direction: $initialDirection Point: $initialPoint")
}
}
Direction.LEFT -> error("! $initialDirection $initialPoint")
Direction.TOP -> {
when (initialPoint.side) {
3 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 1,
newDir = Direction.RIGHT
) { _, diffPoint ->
switchXY(diffPoint)
}
else -> error("Failed Init Direction: $initialDirection Point: $initialPoint")
}
}
Direction.DOWN -> {
when (initialPoint.side) {
5 -> calculateNewPointAndDirection(
cells = cells,
initialPoint = initialPoint,
newSide = 2,
newDir = Direction.TOP
) { sizeSide, diffPoint ->
val index = sizeSide - 1
diffPoint.copyWithSide(
x = index - diffPoint.x,
y = diffPoint.y,
)
}
else -> error("Failed Init Direction: $initialDirection Point: $initialPoint")
}
}
}
return nextPoint
}
/**
*
*/
private fun indexMinusY(
sizeSide: Int,
diffPoint: Point
): Point {
val index = sizeSide - 1
return diffPoint.copyWithSide(
x = diffPoint.x,
y = index - diffPoint.y,
)
}
/**
* Helper method to create new point with switched X and Y
*/
private fun switchXY(diffPoint: Point) = diffPoint.copyWithSide(
x = diffPoint.y,
y = diffPoint.x,
)
private fun calculateNewPointAndDirection(
cells: Map<Point, Cell>,
initialPoint: Point,
newSide: Int,
newDir: Direction,
transpose: (sideSize: Int, diffPoint: Point) -> Point
): Pair<Point, Direction> {
val sizeSide = cells.sideSize()
val currentSideTopLeftPoint = cells.keys
.filter { it.side == initialPoint.side }
.minBy { it.heuristic() }
val diffPoint = initialPoint - currentSideTopLeftPoint
val newSideTopLeftPoint = cells.keys
.filter { it.side == newSide }
.minBy { it.heuristic() }
val resDifPoint = transpose(sizeSide, diffPoint)
val resultPoint = newSideTopLeftPoint + resDifPoint
return resultPoint to newDir
}
fun walkOverPoints(
isTest: Boolean,
isCube: Boolean,
initialPoint: Point,
commands: List<Command>,
cells: Map<Point, Cell>
): Pair<Point, Direction> {
var currentPoint = initialPoint
var currentDirection = Direction.RIGHT
commands.forEach {
when (it) {
is Command.Move -> {
val (nextPoint, nextDirection) = currentPoint.applyCommand(
isTest = isTest,
isCube = isCube,
initialDirection = currentDirection,
command = it,
cells = cells
)
currentPoint = nextPoint
currentDirection = nextDirection
}
is Command.Rotation -> {
currentDirection = currentDirection.applyRotation(it.rotation)
}
}
}
return currentPoint to currentDirection
}
fun main() {
fun solve(
input: List<String>,
isCube: Boolean,
isTest: Boolean
): Int {
/**
* Parse input
*/
val map = parseInput(input.dropLast(2))
val commands = parseInputCommands(input.last())
/**
* Find top left point
*/
val minY = map.keys.minBy { it.y }
val initialPoint = map.keys.filter { it.y == minY.y }.minBy { it.x }
val (finalPoint, finalDirection) = walkOverPoints(
isTest = isTest,
isCube = isCube,
initialPoint = initialPoint,
commands = commands,
cells = map
)
/**
* Calculate final answer
*/
val pointNumber = finalPoint.y.inc() * 1000 + finalPoint.x.inc() * 4
val dirNumber = when (finalDirection) {
Direction.RIGHT -> 0
Direction.DOWN -> 1
Direction.LEFT -> 2
Direction.TOP -> 3
}
return pointNumber + dirNumber
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day22_test")
val part1Test = solve(input = testInput, isCube = false, isTest = true)
val part2Test = solve(input = testInput, isCube = true, isTest = true)
check(part1Test == 6032)
check(part2Test == 5031)
val input = readInput("Day22")
val part1 = solve(input = input, isCube = false, isTest = false)
check(part1 == 43466)
println(part1)
val part2 = solve(input = input, isCube = true, isTest = false)
check(part2 == 162155)
println(part2)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 19,008 | KotlinAdventOfCode | Apache License 2.0 |
src/year2021/Day18.kt | drademacher | 725,945,859 | false | {"Kotlin": 76037} | package year2021
import readLines
fun main() {
fun input() = parseInput(readLines("2021", "day18"))
fun testInput() = parseInput(readLines("2021", "day18_test"))
check(part1(testInput()) == 4140)
println("Part 1:" + part1(input()))
check(part2(testInput()) == 3993)
println("Part 2:" + part2(input()))
}
private fun parseInput(lines: List<String>): List<Snailfish> =
lines
.map { Snailfish.fromString(it) }
private fun part1(input: List<Snailfish>): Int {
var acc = input.first()
for (snailfish in input.drop(1)) {
acc = Snailfish.add(acc, snailfish)
acc = acc.reduced()
}
return acc.magnitude
}
private fun part2(input: List<Snailfish>): Int {
return input
.flatMap { fst -> input.map { snd -> Pair(fst.getCopy(), snd.getCopy()) } }
.map { Snailfish.add(it.first, it.second) }
.map(Snailfish::reduced)
.map(Snailfish::magnitude)
.maxOf { it }
}
sealed class Snailfish() {
class Number(var number: Int) : Snailfish()
class Pair(var left: Snailfish, var right: Snailfish) : Snailfish()
fun getCopy(): Snailfish {
return when (this) {
is Number -> Number(number)
is Pair -> Pair(left.getCopy(), right.getCopy())
}
}
val isNumberPair: Boolean
get() = this is Pair && left is Number && right is Number
val containsNumberPair: Boolean
get() = this.isNumberPair || (this is Pair && (right.containsNumberPair || left.containsNumberPair))
fun getInorderTraversal(): List<Number> {
return when (this) {
is Number -> listOf(this)
is Pair -> left.getInorderTraversal() + right.getInorderTraversal()
}
}
fun reduced(): Snailfish {
var hasExploded = true
var hasSplit = true
while (hasExploded || hasSplit) {
hasExploded = this.explode()
if (!hasExploded) {
hasSplit = this.split()
}
}
return this
}
fun explode(): Boolean {
return when (this) {
is Number -> false
is Pair -> {
val current = this.findNumberPairToExplode() ?: return false
val inorder = getInorderTraversal()
val offset = inorder.indexOf(current.left)
val leftSibling = inorder.getOrNull(offset - 1)
val rightSibling = inorder.getOrNull(offset + 2)
leftSibling?.also { it.number += (current.left as Number).number }
rightSibling?.also { it.number += (current.right as Number).number }
val parent = current.getParent(this)!!
if (parent.left == current) {
parent.left = Number(0)
} else {
parent.right = Number(0)
}
return true
}
}
}
fun findNumberPairToExplode(currentDepth: Int = 0): Pair? {
if (currentDepth >= 4 && isNumberPair) {
return this as Pair
}
return when (this) {
is Number -> null
is Pair -> {
left.findNumberPairToExplode(currentDepth + 1) ?: right.findNumberPairToExplode(currentDepth + 1)
}
}
}
fun getParent(tree: Snailfish): Pair? {
if (tree is Pair && (tree.left == this || tree.right == this)) {
return tree
}
return when (tree) {
is Number -> null
is Pair -> {
getParent(tree.left) ?: getParent(tree.right)
}
}
}
fun split(parent: Snailfish? = null): Boolean {
return when (this) {
is Number -> {
if (number >= 10) {
val split = Pair(Number(number / 2), Number((number + 1) / 2))
if ((parent as Pair).left == this) {
parent.left = split
} else {
parent.right = split
}
true
} else {
false
}
}
is Pair -> {
left.split(this) || right.split(this)
}
}
}
val magnitude: Int
get() =
when (this) {
is Number -> number
is Pair -> 3 * left.magnitude + 2 * right.magnitude
}
override fun toString(): String {
return when (this) {
is Number -> number.toString()
is Pair -> "[$left,$right]"
}
}
companion object {
fun add(
a: Snailfish,
b: Snailfish,
): Pair {
return Pair(a, b)
}
fun fromString(string: String): Snailfish {
if (string.toIntOrNull() != null) {
return Number(string.toInt())
}
var level = 0
var split = -1
for (index in string.indices) {
when (string[index]) {
'[' -> {
level += 1
}
']' -> {
level -= 1
}
',' -> {
if (level == 1) {
split = index
break
}
}
}
}
if (split == -1) {
throw IllegalStateException("$string should have a splitting comma")
}
return Pair(
fromString(string.substring(1 until split)),
fromString(string.substring(split + 1..string.length - 2)),
)
}
}
}
| 0 | Kotlin | 0 | 0 | 4c4cbf677d97cfe96264b922af6ae332b9044ba8 | 5,824 | advent_of_code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DistinctCharactersEqual.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
/**
* 2531. Make Number of Distinct Characters Equal
* @see <a href="https://leetcode.com/problems/make-number-of-distinct-characters-equal/">Source</a>
*/
fun interface DistinctCharactersEqual {
fun isItPossible(word1: String, word2: String): Boolean
}
class DistinctCharactersEqualMap : DistinctCharactersEqual {
override fun isItPossible(word1: String, word2: String): Boolean {
val mp1: MutableMap<Char, Int> = HashMap()
val mp2: MutableMap<Char, Int> = HashMap()
// store freq of chars in word1 in mp1
for (w1 in word1.toCharArray()) {
mp1[w1] = mp1.getOrDefault(w1, 0) + 1
}
// store freq of chars in word2 in mp2
for (w2 in word2.toCharArray()) {
mp2[w2] = mp2.getOrDefault(w2, 0) + 1
}
var c1 = 'a'
while (c1 <= 'z') {
var c2 = 'a'
while (c2 <= 'z') {
if (!mp1.containsKey(c1) || !mp2.containsKey(c2)) {
c2++
// if any of the char is not present then skip
continue
}
insertAndRemove(mp1, c2, c1) // insert c2 to word1 and remove c1 from word1
insertAndRemove(mp2, c1, c2) // insert c1 to word2 and remove c2 from word2
if (mp1.size == mp2.size) return true // if size of both maps are equal then possible return true
// reset back the maps
insertAndRemove(mp1, c1, c2) // insert c1 back to word1 and remove c2 from word1
insertAndRemove(mp2, c2, c1) // insert c2 back to word2 and remove c1 from word2
c2++
}
c1++
}
return false
}
private fun insertAndRemove(
mp: MutableMap<Char, Int>,
toInsert: Char,
toRemove: Char,
) {
// made this helper fxn for easy removal from hashmap
mp[toInsert] = mp.getOrDefault(toInsert, 0) + 1 // increment freq for char to be inserted
mp[toRemove] = mp.getOrDefault(toRemove, 0) - 1 // decrement freq for char to be removed
// if freq of that char reaches zero, then remove the key from hashmap
if (mp[toRemove] == 0) mp.remove(toRemove)
}
}
class DistinctCharactersEqualArray : DistinctCharactersEqual {
override fun isItPossible(word1: String, word2: String): Boolean {
val map1 = IntArray(ALPHABET_LETTERS_COUNT)
val map2 = IntArray(ALPHABET_LETTERS_COUNT)
// store frequency of characters
for (element in word1) map1[element - 'a']++
for (element in word2) map2[element - 'a']++
var count1 = 0
var count2 = 0
// count no of distinct characters in each string
for (i in 0 until ALPHABET_LETTERS_COUNT) {
if (map1[i] > 0) count1++
if (map2[i] > 0) count2++
}
// as explained in step 3
if (count1 == count2 && word1.length == word2.length) return true
for (i in 0 until ALPHABET_LETTERS_COUNT) {
for (j in 0 until ALPHABET_LETTERS_COUNT) {
if (map1[i] == 0 || map2[j] == 0) continue
var uniqueCharInMap1 = count1
var uniqueCharInMap2 = count2
// changing char count for map1
if (map1[j] == 0) uniqueCharInMap1++
map1[j]++
if (map1[i] == 1) uniqueCharInMap1--
map1[i]--
// changing char count for map2
if (map2[i] == 0) uniqueCharInMap2++
map2[i]++
if (map2[j] == 1) uniqueCharInMap2--
map2[j]--
// if count of unique chars are same, return true
if (uniqueCharInMap1 == uniqueCharInMap2) return true
map1[j]--
map1[i]++
map2[i]--
map2[j]++
}
}
return false
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,652 | kotlab | Apache License 2.0 |
src/main/kotlin/aoc2023/Day16.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.*
private data class Beam(val loc: Coordinates, val heading: Direction) {
fun move(dir: Direction) = copy(loc=loc.move(dir), heading=dir)
}
private class Day16(input: List<String>): ArrayAsSurface(input) {
fun rotate90_1(dir: Direction) = when(dir) {
E -> N
N -> E
S -> W
W -> S
}
fun rotate90_2(dir: Direction) = when(dir) {
E -> S
S -> E
N -> W
W -> N
}
fun nextBeams(current: Beam, seen: Set<Beam>): List<Beam> {
val dir = current.heading
val next = when (checkedAt(current.loc, 'X')) {
'.' -> listOf(current.move(dir))
'/' -> listOf(current.move(rotate90_1(dir)))
'\\' -> listOf(current.move(rotate90_2(dir)))
'|' -> when(dir) {
N, S -> listOf(current.move(dir))
E, W -> listOf(current.move(N), current.move(S))
}
'-' -> when(dir) {
N, S -> listOf(current.move(E), current.move(W))
E, W -> listOf(current.move(dir))
}
else -> emptyList()
}
return next.filter { it !in seen && inBounds(it.loc)}
}
fun allBeams(start: Beam): MutableSet<Beam> {
var currentBeams = listOf(start)
val seen = mutableSetOf(start)
while (currentBeams.isNotEmpty()) {
val nextBeams = currentBeams.flatMap { nextBeams(it, seen) }
seen.addAll(nextBeams)
currentBeams = nextBeams
}
return seen
}
private fun symbolFor(beams: List<Beam>): Char {
return when(beams.size) {
0 -> '.'
1 -> when(beams[0].heading) {
N -> '^'
S -> 'v'
E -> '>'
W -> '<'
}
else -> '0' + beams.size
}
}
fun starts() = (0..<getWidth()).flatMap { listOf(Beam(Coordinates(it,0),S),Beam(Coordinates(it,getHeight() - 1),N)) } +
(0..getHeight()).flatMap { listOf(Beam(Coordinates(0,it),E),Beam(Coordinates(getWidth() -1,it),W)) }
fun printBeams(beams: Set<Beam>) {
rows().forEach {row ->
println(row.map { loc ->
val at = at(loc)
when(at) {
'.' -> symbolFor(beams.filter { it.loc == loc })
else -> at
}
}.joinToString(""))
}
}
fun printEnergised(beams: Set<Beam>) {
val coordinates = beams.map { it.loc }
.filter { inBounds(it) }.toSet()
println(coordinates.size)
rows().forEach {row ->
println(row.map { loc ->
if (loc in coordinates) '#' else '.'
}.joinToString(""))
}
}
}
fun main() {
val testInput = """.|...\....
|.-.\.....
.....|-...
........|.
..........
.........\
..../.\\..
.-.-/..|..
.|....-|.\
..//.|....""".trimIndent().split("\n")
fun part1(input: List<String>): Int {
val start = Beam(Coordinates(0, 0), E)
val problem = Day16(input)
val beams = problem
.allBeams(start)
// problem.printBeams(beams)
// println()
// problem.printEnergised(beams)
return beams
.distinctBy { it.loc }
.count()
}
fun part2(input: List<String>): Int {
val problem = Day16(input)
return problem.starts().map { start ->
val beams = problem
.allBeams(start)
beams
.distinctBy { it.loc }
.count() }.max()
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 46)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 16)
val input = puzzleInput.toList()
println(part1(input))
val start = System.currentTimeMillis()
println(part2(input))
println("Time: ${System.currentTimeMillis() - start}")
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 4,074 | aoc-2022-kotlin | Apache License 2.0 |
src/Day18.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
val coordsList = getCoordsList(input)
return getSidesCount(coordsList)
}
fun part2(input: List<String>): Int {
val coordsList = getCoordsList(input)
val minList: Array<Int> = Array(3) { Int.MAX_VALUE }
val maxList: Array<Int> = Array(3) { Int.MIN_VALUE }
coordsList.forEach { coords ->
coords.forEachIndexed { index, i ->
minList[index] = min(minList[index], i)
maxList[index] = max(maxList[index], i)
}
}
val sizes: Array<Int> = Array(3) { maxList[it] - minList[it] + 2 }
val space: Array<Array<Array<CubeType>>> = Array(sizes[0]) {
Array(sizes[1]) {
Array(sizes[2]) { CubeType.EMPTY }
}
}
coordsList.forEach {
space[it[0] - minList[0] + 1][it[1] - minList[1] + 1][it[2] - minList[2] + 1] = CubeType.BLOCK
}
var processedList: MutableList<Array<Int>> = mutableListOf()
processedList.add(Array(3) { 0 })
space[0][0][0] = CubeType.EXTERNAL
while (processedList.size > 0) {
val newList: MutableList<Array<Int>> = mutableListOf()
processedList.forEach { current ->
NEAREST_CUBES.forEach { delta ->
val coords: Array<Int> = Array(3) { current[it] + delta[it] }
if (coords[0] in 0 until sizes[0]
&& coords[1] in 0 until sizes[1]
&& coords[2] in 0 until sizes[2]
&& space[coords[0]][coords[1]][coords[2]] == CubeType.EMPTY
) {
newList.add(coords)
space[coords[0]][coords[1]][coords[2]] = CubeType.EXTERNAL
}
}
}
processedList = newList
}
val innerCubesList: MutableList<List<Int>> = mutableListOf()
space.forEachIndexed { index0, arrayOfArrays ->
arrayOfArrays.forEachIndexed { index1, array ->
array.forEachIndexed { index2, cubeType ->
if (cubeType == CubeType.EMPTY)
innerCubesList.add(
listOf(
index0 + minList[0] - 1,
index1 + minList[1] - 1,
index2 + minList[2] - 1
)
)
}
}
}
return getSidesCount(coordsList) - getSidesCount(innerCubesList)
}
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
private fun getCoordsList(input: List<String>): List<List<Int>> {
return input.map {
it.split(',').map(String::toInt)
}
}
private fun getSidesCount(coordsList: List<List<Int>>): Int {
val sides: Array<MutableSet<List<Int>>> = Array(3) { mutableSetOf() }
coordsList.forEach {
it.forEachIndexed { index, i ->
if (sides[index].contains(it))
sides[index].remove(it)
else
sides[index].add(it)
val secondCoords = ArrayList(it)
secondCoords[index] = i + 1
if (sides[index].contains(secondCoords))
sides[index].remove(secondCoords)
else
sides[index].add(secondCoords)
}
}
return sides.sumOf { it.size }
}
private enum class CubeType { EMPTY, EXTERNAL, BLOCK }
private val NEAREST_CUBES: List<Array<Int>> = listOf(
arrayOf(1, 0, 0),
arrayOf(-1, 0, 0),
arrayOf(0, 1, 0),
arrayOf(0, -1, 0),
arrayOf(0, 0, 1),
arrayOf(0, 0, -1)
) | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 3,929 | AdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | hoppjan | 433,705,171 | false | {"Kotlin": 29015, "Shell": 338} | import kotlin.math.absoluteValue
import kotlin.math.roundToInt
fun main() {
fun part1(input: IntArray) =
input.sumOf { crabPosition ->
crabPosition distanceTo input.cheapestPointByDistance()
}
fun part2(input: IntArray) =
input.cheapestPointByFuelCosts()
.possibleMeetingPointRange(ACCOUNTING_FOR_ERRORS)
.mostEfficientFuelUseOf { possibleMeetingPosition ->
input.sumOf { crabPosition ->
(crabPosition distanceTo possibleMeetingPosition)
.fuelNeeded()
}
}
// test if implementation meets criteria from the description
val testInput = IntInputReader2.read("Day07_test")
// testing part 1
val testSolution1 = 37
val testOutput1 = part1(testInput)
printTestResult(1, testOutput1, testSolution1)
check(testOutput1 == testSolution1)
// testing part 2
val testSolution2 = 168
val testOutput2 = part2(testInput)
printTestResult(2, testOutput2, testSolution2)
check(testOutput2 == testSolution2)
// the actual
val input = IntInputReader2.read("Day07")
printResult(1, part1(input).also { check(it == 347_449) })
printResult(2, part2(input).also { check(it == 98_039_527) })
}
infix fun Int.distanceTo(location: Int) = (this - location).absoluteValue
fun IntArray.cheapestPointByDistance() = sortedArray()[size / 2]
fun IntArray.cheapestPointByFuelCosts() = average().roundToInt()
// Accounting for errors is necessary because cheapestPointByFuelCosts rounds a Double.
// I think...? I do not want to think about it anymore, but the tests/checks pass :)
private const val ACCOUNTING_FOR_ERRORS = 1
fun Int.possibleMeetingPointRange(errorFromPoint: Int) = minus(errorFromPoint)..plus(errorFromPoint)
fun IntRange.mostEfficientFuelUseOf(fuelUseCalculation: (Int) -> Int) = minOf(fuelUseCalculation)
/**
* Part 2 fuel cost.
* Optimized way to get the sum of [Int] and all numbers below it.
*/
fun Int.fuelNeeded() = this * (this + 1) / 2
| 0 | Kotlin | 0 | 0 | 04f10e8add373884083af2a6de91e9776f9f17b8 | 2,062 | advent-of-code-2021 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.