path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/java/challenges/educative_grokking_coding_interview/top_k_elements/_3/ClosestPoints.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.top_k_elements._3 import challenges.util.PrintHyphens import java.util.* /** Given a list of points on a plane, where the plane is a 2-D array with (x, y) coordinates, find the k closest points to the origin (0, 0). https://www.educative.io/courses/grokking-coding-interview-patterns-java/JEzp359Rjn9 */ internal object ClosestPoints { private fun kClosest(points: Array<Point>, k: Int): List<Point> { val maxHeap: PriorityQueue<Point> = PriorityQueue<Point>(java.util.Comparator<Point> { p1: Point, p2: Point -> p2.distFromOrigin() - p1.distFromOrigin() }) // put first 'k' points in the max heap for (i in 0 until k) maxHeap.add(points[i]) // go through the remaining points of the input array, if a Location is closer to the origin than the top Location // of the max-heap, remove the top Location from heap and add the Location from the input array for (i in k until points.size) { if (points[i].distFromOrigin() < maxHeap.peek().distFromOrigin()) { maxHeap.poll() maxHeap.add(points[i]) } } // the heap has 'k' points closest to the origin, return them in a list return ArrayList(maxHeap) } @JvmStatic fun main(args: Array<String>) { val pointsOne: Array<Point> = arrayOf<Point>( Point(1, 3), Point(3, 4), Point(2, -1) ) val pointsTwo: Array<Point> = arrayOf<Point>( Point(1, 3), Point(2, 4), Point(2, -1), Point(-2, 2), Point(5, 3), Point(3, -2) ) val pointsThree: Array<Point> = arrayOf<Point>( Point(1, 3), Point(5, 3), Point(3, -2), Point(-2, 2) ) val pointsFour: Array<Point> = arrayOf<Point>( Point(2, -1), Point(-2, 2), Point(1, 3), Point(2, 4) ) val pointsFive: Array<Point> = arrayOf<Point>( Point(1, 3), Point(2, 4), Point(2, -1), Point(-2, 2), Point(5, 3), Point(3, -2), Point(5, 3), Point(3, -2) ) val points: Array<Array<Point>> = arrayOf(pointsOne, pointsTwo, pointsThree, pointsFour, pointsFive) val kList = intArrayOf(2, 3, 1, 4, 5) for (i in points.indices) { print((i + 1).toString() + ".\tSet of points: ") for (p in points[i]) print("[" + p.x.toString() + " , " + p.y.toString() + "] ") println( """ K: ${kList[i]}""" ) val result: List<Point> = kClosest(points[i], kList[i]) print("\tHere are the k = " + kList[i] + " points closest to the origin(0, 0): ") for (p in result) print("[" + p.x.toString() + " , " + p.y.toString() + "] ") println("\n") println(PrintHyphens.repeat("-", 100)) } } } class Point(var x: Int, var y: Int) { fun distFromOrigin(): Int { // ignoring sqrt return x * x + y * y } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,983
CodingChallenges
Apache License 2.0
src/day06/Day06.kt
lpleo
572,702,403
false
{"Kotlin": 30960}
package day06 import readInput fun main() { fun part1(input: List<String>): Int { val string = input[0] for (i in 0..string.length) { val reduce = string.substring(i, i + 4).map { character -> string.substring(i, i + 4).count { internalChar -> internalChar == character } == 1 }.reduce { a, b -> a && b } if (reduce) return i + 4; } return 0 } fun part2(input: List<String>): Int { val string = input[0] for (i in 0..string.length) { val reduce = string.substring(i, i + 14).map { character -> string.substring(i, i + 14).count { internalChar -> internalChar == character } == 1 }.reduce { a, b -> a && b } if (reduce) return i + 14; } return 0 } println(part1(listOf("mjqjpqmgbljsphdztnvjfqwrcgsmlb"))) check(part1(listOf("mjqjpqmgbljsphdztnvjfqwrcgsmlb")) == 7) println(part1(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz"))) check(part1(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz")) == 5) println(part1(listOf("nppdvjthqldpwncqszvftbrmjlhg"))) check(part1(listOf("nppdvjthqldpwncqszvftbrmjlhg")) == 6) check(part1(listOf("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg")) == 10) check(part1(listOf("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw")) == 11) val input = readInput("files/Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
115aba36c004bf1a759b695445451d8569178269
1,378
advent-of-code-2022
Apache License 2.0
2022/Day16/problems.kt
moozzyk
317,429,068
false
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
import java.io.File import kotlin.math.* data class Valve(val label: String, val flow: Int, val tunnels: Set<String>) class Solution(val valveMap: Map<String, Valve>) { val paths = cachePaths(valveMap) var closedValves = mutableMapOf<String, Valve>() var memo = mutableMapOf<Triple<String, Pair<String, Int>, Pair<String, Int>>, Int>() fun openValves(withHelp: Boolean, timeLimit: Int): Int { closedValves = valveMap.filter { it.value.flow > 0 }.toMutableMap() memo = mutableMapOf<Triple<String, Pair<String, Int>, Pair<String, Int>>, Int>() return openValves( valveMap["AA"]!!, 1, valveMap["AA"]!!, if (withHelp) 1 else Int.MAX_VALUE, timeLimit ) } fun openValves( valve1: Valve, minute1: Int, valve2: Valve, minute2: Int, timeLimit: Int, ): Int { if (minute1 > timeLimit) { return 0 } var flow = (timeLimit - minute1 + 1) * valve1.flow var maxDescFlow = if (!closedValves.isEmpty()) { 0 } else { openValves(valve2, minute2, valve2, Int.MAX_VALUE, timeLimit) } for (nextValve in closedValves.values.toList()) { closedValves.remove(nextValve.label) val nextEta = 1 + minute1 + paths[Pair(valve1.label, nextValve.label)]!! val descFlow = if (nextEta < minute2) { openValves(nextValve, nextEta, valve2, minute2, timeLimit) } else { openValves(valve2, minute2, nextValve, nextEta, timeLimit) } maxDescFlow = max(maxDescFlow, descFlow) closedValves.put(nextValve.label, nextValve) } return flow + maxDescFlow } fun cachePaths(valveMap: Map<String, Valve>): MutableMap<Pair<String, String>, Int> { var paths = mutableMapOf<Pair<String, String>, Int>() for (from in valveMap.filter { it.value.flow > 0 || it.key == "AA" }.map { it.key }) { for (to in valveMap.filter { it.value.flow > 0 }.map { it.key }) { if (from != to) { paths.put(Pair(from, to), pathCost(from, to, valveMap)) } } } return paths } fun pathCost(from: String, to: String, valveMap: Map<String, Valve>): Int { var visited = mutableSetOf<String>() var q = ArrayDeque<Pair<String, Int>>() q.addLast(Pair<String, Int>(from, 0)) while (!q.isEmpty()) { val (valve, steps) = q.removeFirst() if (valve == to) { return steps } for (nextValve in valveMap[valve]!!.tunnels) { if (!visited.contains(nextValve)) { visited.add(nextValve) q.addLast(Pair(nextValve, steps + 1)) } } } throw Exception("Cannot find path from ${from} to ${to}") } } fun main(args: Array<String>) { val lines = File(args[0]).readLines() val regex = """ ([A-Z]{2}) .*=(\d+).*(valve|valves) (.*)""".toRegex() val valveMap = lines .map { regex.find(it)!!.destructured.let { (label: String, flow: String, _: String, tunnels: String) -> Valve(label, flow.toInt(), tunnels.split(", ").toSet()) } } .associateBy({ it.label }, { it }) println(problem1(valveMap)) println(problem2(valveMap)) } fun problem1(valveMap: Map<String, Valve>): Int { return Solution(valveMap).openValves(false, 30) } fun problem2(valveMap: Map<String, Valve>): Int { println("This is ridiculously slooow") return Solution(valveMap).openValves(true, 26) }
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
4,020
AdventOfCode
MIT License
src/Day10.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
enum class Command(val cycles: Int) { addx(2), noop(1) } class Instruction(var cmd: Command, var arg: Int? = null) { } class Computer(private val instructions: List<Instruction>, var x: Int = 1) { private var cc = 0 private var ip = 0 val screen = Screen(40, 6) private var cycle = 0 fun tick() { if (cc == instructions[ip].cmd.cycles) { when (instructions[ip].cmd) { Command.addx -> x += instructions[ip].arg!! else -> null } ip++ cc = 0 } screen.draw(cycle++, x) cc++ } } class Screen(private val width: Int, height: Int) { private val size = width * height private val display = MutableList(size) { ' ' } fun draw(cycle: Int, x: Int) { val idx = cycle % size val row = cycle / width if ((idx-1..idx+1).contains(x + row * width)) { display[cycle] = '#' } else { display[cycle] = ' ' } } fun print() { display.chunked(width).forEach { println(it.joinToString("")) } } } fun main() { fun parse(input: List<String>): List<Instruction> = input.map { line -> line.split(" ").let { Instruction(Command.valueOf(it[0]), it.getOrNull(1)?.toInt()) } } fun part1(input: List<String>): Int { val computer = Computer(parse(input)) var acc = 0 val samples = listOf(20, 60, 100, 140, 180, 220) (1..220).forEach { computer.tick() if (samples.contains(it)) acc += it * computer.x } return acc } fun part2(input: List<String>) { val computer = Computer(parse(input)) (1..240).forEach { computer.tick() } computer.screen.print() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
2,090
advent-of-code-2022
Apache License 2.0
src/Day09.kt
CrazyBene
573,111,401
false
{"Kotlin": 50149}
import kotlin.math.abs import kotlin.math.sign fun main() { fun List<String>.toMoveInstructions(): List<Pair<Int, Int>> { return this.flatMap { val (char, times) = it.split(" ") val move = when (char.first()) { 'U' -> 0 to 1 'R' -> 1 to 0 'D' -> 0 to -1 'L' -> -1 to 0 else -> error("Can not convert ${char.first()} to move direction.") } List(times.toInt()) { move } } } fun Pair<Int, Int>.isTouching(otherPosition: Pair<Int, Int>): Boolean { return abs(this.first - otherPosition.first) <= 1 && abs(this.second - otherPosition.second) <= 1 } fun getFollowMoveInstruction(headPosition: Pair<Int, Int>, tailPosition: Pair<Int, Int>): Pair<Int, Int> { if (headPosition.isTouching(tailPosition)) return 0 to 0 val distanceX = headPosition.first - tailPosition.first val distanceY = headPosition.second - tailPosition.second return distanceX.sign to distanceY.sign } operator fun Pair<Int, Int>.plus(moveInstruction: Pair<Int, Int>): Pair<Int, Int> { return this.first + moveInstruction.first to this.second + moveInstruction.second } fun part1(input: List<String>): Int { val moveInstructions = input.toMoveInstructions() var headPosition = 0 to 0 var tailPosition = 0 to 0 val positionsVisitedByTail = mutableSetOf<Pair<Int, Int>>() positionsVisitedByTail.add(tailPosition) moveInstructions.forEach { headPosition += it tailPosition += getFollowMoveInstruction(headPosition, tailPosition) positionsVisitedByTail.add(tailPosition) } return positionsVisitedByTail.size } fun part2(input: List<String>): Int { val moveInstructions = input.toMoveInstructions() val numberOfRopeSegments = 10 val ropeSegmentsPositions = Array(numberOfRopeSegments) { 0 to 0 } val positionsVisitedByTail = mutableSetOf<Pair<Int, Int>>() positionsVisitedByTail.add(ropeSegmentsPositions.last()) moveInstructions.forEach { for (i in ropeSegmentsPositions.indices) { if (i == 0) ropeSegmentsPositions[0] = ropeSegmentsPositions[0] + it else ropeSegmentsPositions[i] = ropeSegmentsPositions[i] + getFollowMoveInstruction( ropeSegmentsPositions[i - 1], ropeSegmentsPositions[i] ) } positionsVisitedByTail.add(ropeSegmentsPositions.last()) } return positionsVisitedByTail.size } val testInput = readInput("Day09Test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println("Question 1 - Answer: ${part1(input)}") println("Question 2 - Answer: ${part2(input)}") }
0
Kotlin
0
0
dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26
3,009
AdventOfCode2022
Apache License 2.0
src/Day09.kt
RandomUserIK
572,624,698
false
{"Kotlin": 21278}
import kotlin.math.abs private fun List<String>.toDirections(): List<Direction> = joinToString("") { val direction = it.substringBefore(" ") val steps = it.substringAfter(" ").toInt() direction.repeat(steps) }.map { when (it) { 'U' -> Direction.U 'D' -> Direction.D 'L' -> Direction.L 'R' -> Direction.R else -> error("Invalid direction entry provided: [$it].") } } private infix fun Point.touches(tail: Point): Boolean = abs(this.row - tail.row) <= 1 && abs(this.col - tail.col) <= 1 private infix fun Point.chase(head: Point): Point = (head - this).let { diff -> this + Point(row = diff.row.coerceIn(-1, 1), col = diff.col.coerceIn(-1, 1)) } private enum class Direction( val dRow: Int, val dCol: Int, ) { U(-1, 0), D(1, 0), L(0, -1), R(0, 1) } private data class Point( val row: Int = 0, val col: Int = 0, ) { fun move(direction: Direction): Point = copy(row = row + direction.dRow, col = col + direction.dCol) operator fun plus(other: Point) = Point( row = row + other.row, col = col + other.col, ) operator fun minus(other: Point) = Point( row = row - other.row, col = col - other.col, ) } fun main() { fun part1(input: List<String>): Int { val directions = input.toDirections() var head = Point() var tail = Point() val pointsVisited = mutableSetOf(Point()) // we ought to include the starting point directions.forEach { direction -> head = head.move(direction) if (!(head touches tail)) { tail = tail chase head } pointsVisited.add(tail) } return pointsVisited.size } fun part2(input: List<String>): Int { val directions = input.toDirections() val pointsVisited = mutableSetOf(Point()) val knots = Array(10) { Point() } directions.forEach { direction -> knots[0] = knots.first().move(direction) (0 until knots.lastIndex).forEach { headIdx -> if (!(knots[headIdx] touches knots[headIdx + 1])) { knots[headIdx + 1] = knots[headIdx + 1] chase knots[headIdx] } } pointsVisited += knots.last() } return pointsVisited.size } val input = readInput("inputs/day09_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f22f10da922832d78dd444b5c9cc08fadc566b4b
2,169
advent-of-code-2022
Apache License 2.0
src/Day01.kt
ManueruEd
573,678,383
false
{"Kotlin": 10647}
fun main() { fun part1(input: List<String>): Int { val a = input.map { it.toIntOrNull() } .fold(mutableListOf()) { acc: MutableList<ArrayList<Int>>, s: Int? -> if (s == null) { acc.add(arrayListOf()) acc } else { if (acc.lastOrNull() == null) { acc.add(arrayListOf()) } acc.last().add(s) acc } } return a.maxOf { it.sum() } } fun part2(input: List<String>): Int { val a = input.map { it.toIntOrNull() } .fold(mutableListOf()) { acc: MutableList<ArrayList<Int>>, s: Int? -> if (s == null) { acc.add(arrayListOf()) acc } else { if (acc.lastOrNull() == null) { acc.add(arrayListOf()) } acc.last().add(s) acc } } return a.map { it.sum() }.sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
09f3357e059e31fda3dd2dfda5ce603c31614d77
1,502
AdventOfCode2022
Apache License 2.0
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day14.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day14 : Day("2851", "10002813279337") { private val template = input.split("\n\n")[0] private val rules = input .split("\n\n")[1] .lines() .map { it.replace(" -> ", "") } .associate { (it[0] to it[1]) to it[2] } override fun solvePartOne(): Any { return getAnswerAfterSteps(10) } override fun solvePartTwo(): Any { return getAnswerAfterSteps(40) } private fun getAnswerAfterSteps(steps: Int): Long { var counts = Array(26) { LongArray(26) } for (i in 0 until template.length - 1) { counts[template[i] - 'A'][template[i + 1] - 'A']++ } for (i in 0 until steps) { val newCounts = Array(26) { LongArray(26) } for ((pair, insertion) in rules) { val pairLeftIndex = pair.first - 'A' val pairRightIndex = pair.second - 'A' val insertionIndex = insertion - 'A' newCounts[pairLeftIndex][insertionIndex] += counts[pairLeftIndex][pairRightIndex] newCounts[insertionIndex][pairRightIndex] += counts[pairLeftIndex][pairRightIndex] } counts = newCounts } val characters = 'A'..'Z' val occurrences = characters .map { ch1 -> var count = characters.sumOf { ch2 -> counts[ch1 - 'A'][ch2 - 'A'] + counts[ch2 - 'A'][ch1 - 'A'] } if (template[0] == ch1) { count++ } if (template.last() == ch1) { count++ } count / 2 } .filter { it > 0 } return occurrences.maxOf { it } - occurrences.minOf { it } } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
1,797
advent-of-code-2021
MIT License
src/Day11.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
import Monkey11.Op fun main() { fun parseMonkeys(input: List<String>): List<Monkey11> { val digits = Regex("\\d+") return buildList { input.chunked(7) { val (f, op, s) = it[2].split(':')[1] .trim() .replace("new = ", "") .split(' ') .filter(String::isNotBlank) add( Monkey11( ArrayDeque(digits.findAll(it[1]).map { it.value.toLong() }.toList()), Op(f, op, s), digits.find(it[3])!!.value.toLong(), digits.find(it[4])!!.value.toInt(), digits.find(it[5])!!.value.toInt(), ) ) } } .also { all -> all.forEach { it.monkeys = all } } } fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) repeat(20) { for (monkey in monkeys) { monkey { (it.toDouble() / 3).toLong() } } } return monkeys.map(Monkey11::processedItems).sorted().takeLast(2).map(Int::toLong).reduce(Long::times) } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input) repeat(10000) { monkeys.forEach(Monkey11::invoke) } return monkeys.map(Monkey11::processedItems).sorted().takeLast(2).map(Int::toLong).reduce(Long::times) } val testInput = readInput("Day11_test") val testPart1 = part1(testInput) check(testPart1 == 10605L) { "Actual result: $testPart1" } val input = readInput("Day11") println(part1(input)) val testPart2 = part2(testInput) check(testPart2 == 2713310158L) { "Actual result: $testPart2" } println(part2(input)) } class Monkey11( val items: ArrayDeque<Long>, val operation: Op, val divisor: Long, val trueMonkey: Int, val falseMonkey: Int, ) { lateinit var monkeys: List<Monkey11> var processedItems = 0 val lcm: Long by lazy { monkeys.map(Monkey11::divisor).reduce(::lcm) } class Op(private val f: String, private val op: String, private val s: String) { operator fun invoke(input: Long): Long { val firstArg = if (f == "old") input else f.toLong() val secondArg = if (s == "old") input else s.toLong() return when (op) { "*" -> firstArg * secondArg "+" -> firstArg + secondArg else -> error("Unsupported op $op") } } } inline operator fun invoke(modifier: (Long) -> Long = { it }) { while (items.isNotEmpty()) { val item = items.removeFirst() val result = modifier(operation(item)) val testResult = result % divisor == 0L (if (testResult) monkeys[trueMonkey] else monkeys[falseMonkey]).items.add(result % lcm) processedItems++ } } } tailrec fun gcd(a: Long, b: Long): Long { return if (b == 0L) a else gcd(b, a % b) } fun lcm(a: Long, b: Long): Long { return a / gcd(a, b) * b }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
3,169
aoc-2022
Apache License 2.0
src/Day04.kt
mr3y-the-programmer
572,001,640
false
{"Kotlin": 8306}
@Suppress("USELESS_CAST") fun main() { fun part1(input: List<String>): Int { return input.sumOf { pair -> val (firstRange, secondRange) = pair.toIntRanges() if (firstRange containsAll secondRange || secondRange containsAll firstRange) 1 else 0 as Int } } fun part2(input: List<String>): Int { return input.sumOf { pair -> val (firstRange, secondRange) = pair.toIntRanges() if (firstRange containsAll secondRange || secondRange containsAll firstRange || firstRange overlapsWith secondRange) 1 else 0 as Int } } check(part1(readInput("Day04_sample")) == 2) println(part1(readInput("Day04_input"))) check(part2(readInput("Day04_sample")) == 4) println(part2(readInput("Day04_input"))) } fun String.toIntRanges(): List<IntRange> { return split(',') .map { range -> val start = range.takeWhile { it != '-' } IntRange(start = start.toInt(), endInclusive = range.drop(start.length + 1).toInt()) } } infix fun IntRange.containsAll(other: IntRange) = this.first <= other.first && this.last >= other.last infix fun IntRange.overlapsWith(other: IntRange) = this.last >= other.first && other.last >= this.first
0
Kotlin
0
0
96d1567f38e324aca0cb692be3dae720728a383d
1,372
advent-of-code-2022
Apache License 2.0
src/day04/Day04.kt
pnavais
727,416,570
false
{"Kotlin": 17859}
package day04 import readInput import java.util.Stack import kotlin.math.pow private fun getMatches(s: String): Int { val (n, w) = s.split(":")[1].split("|").map { i -> i.trim().split("\\s+".toRegex()).map(String::toInt) } val winning = w.toSet() return n.map { i -> i to winning.contains(i) }.count { p -> p.second } } fun part1(input: List<String>): Int { return input.sumOf { s -> val matches = getMatches(s) if (matches > 0) { 2.0.pow(matches.minus(1)).toInt() } else { 0 } } } fun part2(input: List<String>): Int { val connectionMap = input.associate { s -> val cardId = s.split(":")[0].split("\\s+".toRegex())[1].toInt() val matches = getMatches(s) val connections = mutableListOf<Int>() for (i in cardId + 1 until cardId + 1 + matches) { connections.add(i) } cardId to connections } var totalSratchCards = 0 val stack = Stack<Int>() connectionMap.keys.forEach { stack.push(it); } while (stack.isNotEmpty()) { val currentCardId = stack.pop() totalSratchCards++ connectionMap[currentCardId]?.forEach { stack.push(it) } } return totalSratchCards } fun main() { val testInput = readInput("input/day04") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
f5b1f7ac50d5c0c896d00af83e94a423e984a6b1
1,372
advent-of-code-2k3
Apache License 2.0
src/day08/Day08.kt
easchner
572,762,654
false
{"Kotlin": 104604}
package day08 import readInputString import java.lang.Integer.max fun main() { fun part1(input: List<String>): Int { val trees = mutableListOf<MutableList<Int>>() var totalVisible = 0 for (line in input) { trees.add(mutableListOf()) for (i in line) { trees.last().add(i.digitToInt()) } } for (r in trees.indices) { var tallest = -1 for (c in trees[r].indices) { var visible = false val height = trees[r][c] // Test to the left if (height > tallest) { tallest = height visible = true } // Test to the right var shade: Int? = trees[r].subList(c + 1, trees[r].size).maxOrNull() if (shade == null) shade = -1 if (shade < height) { visible = true } // Test above shade = trees.mapIndexed { i, row -> if (i < r) row[c] else -1 }.maxOrNull() if (shade == null) shade = -1 if (shade < height) { visible = true } // Test below shade = trees.mapIndexed { i, row -> if (i > r) row[c] else -1 }.maxOrNull() if (shade == null) shade = -1 if (shade < height) { visible = true } if (visible) totalVisible++ } } return totalVisible } fun part2(input: List<String>): Int { val trees = mutableListOf<MutableList<Int>>() var bestView = 0 for (line in input) { trees.add(mutableListOf()) for (i in line) { trees.last().add(i.digitToInt()) } } for (r in trees.indices) { for (c in trees[r].indices) { val height = trees[r][c] // Left var left = 0 for (x in c - 1 downTo 0) { if (trees[r][x] < height) { left++ } else { left++ break } } // Right var right = 0 for (x in c + 1 until trees[r].size) { if (trees[r][x] < height) { right++ } else { right++ break } } // Up var up = 0 for (x in r - 1 downTo 0) { if (trees[x][c] < height) { up++ } else { up++ break } } // Down var down = 0 for (x in r + 1 until trees.size) { if (trees[x][c] < height) { down++ } else { down++ break } } val scenic = left * right * up * down bestView = max(bestView, scenic) } } return bestView } val testInput = readInputString("day08/test") val input = readInputString("day08/input") check(part1(testInput) == 21) println(part1(input)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
0
5966e1a1f385c77958de383f61209ff67ffaf6bf
3,668
Advent-Of-Code-2022
Apache License 2.0
src/net/sheltem/aoc/y2022/Day16.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2022 suspend fun main() { Day16().run() } class Day16 : Day<Int>(1651, 1707) { override suspend fun part1(input: List<String>): Int { val valves = input.map(Valve.Companion::from) val valvesMap = valves.associateBy { it.name } val paths = valves.associate { it.name to it.neighbours.associateWith { 1 }.toMutableMap() }.toMutableMap() return paths.floydWarshall(valvesMap).dfs(valvesMap, 0, "AA", emptySet(), 0, 30) } override suspend fun part2(input: List<String>): Int { val valves = input.map(Valve.Companion::from) val valvesMap = valves.associateBy { it.name } val paths = valves.associate { it.name to it.neighbours.associateWith { 1 }.toMutableMap() }.toMutableMap() return paths.floydWarshall(valvesMap).dfs(valvesMap, 0, "AA", emptySet(), 0, 26, true) } } private fun Map<String, MutableMap<String, Int>>.dfs( valvesMap: Map<String, Valve>, currentScore: Int, currentValve: String, visited: Set<String>, time: Int, maxTime: Int, partTwo: Boolean = false ): Int { var score = currentScore for ((name, dist) in this[currentValve]!!) { if (!visited.contains(name) && time + dist + 1 < maxTime) { score = score.coerceAtLeast( this.dfs( valvesMap, currentScore = currentScore + (maxTime - time - dist - 1) * valvesMap[name]?.flowRate!!, currentValve = name, visited = visited + name, time = time + dist + 1, maxTime = maxTime, partTwo ) ) } } if (partTwo) { score = score.coerceAtLeast( this.dfs( valvesMap, currentScore = currentScore, currentValve = "AA", visited = visited, time = 0, maxTime = maxTime ) ) } return score } private fun MutableMap<String, MutableMap<String, Int>>.floydWarshall(valveMap: Map<String, Valve>): MutableMap<String, MutableMap<String, Int>> { for (outerKey in this.keys) { for (middleKey in this.keys) { for (innerKey in this.keys) { val middleToOuter = this[middleKey]?.get(outerKey) ?: 9999 val outerToInner = this[outerKey]?.get(innerKey) ?: 9999 val middleToInner = this[middleKey]?.get(innerKey) ?: 9999 if (middleToOuter + outerToInner < middleToInner) { this[middleKey]?.set(innerKey, middleToOuter + outerToInner) } } } } this.values.forEach { it.keys.map { key -> if (valveMap[key]?.flowRate == 0) key else "" } .forEach { toRemove -> if (toRemove != "") it.remove(toRemove) } } this.values.forEach { it.remove("AA") } return this } private data class Valve(val name: String, val flowRate: Int, val neighbours: List<String>) { companion object { fun from(line: String): Valve { val (name, rate) = line.split("; ")[0].split(" ").let { it[1] to it[4].split("=")[1].toInt() } val neighbours = line.split(", ").toMutableList() neighbours[0] = neighbours[0].takeLast(2) return Valve(name, rate, neighbours) } } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
3,433
aoc
Apache License 2.0
src/test/kotlin/Day06.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe /* --- Day 6: Custom Customs --- See https://adventofcode.com/2020/day/6 */ fun List<Set<Char>>.countYes(): Int = sumBy { it.size } fun List<List<Set<Char>>>.anyPerGroup(): List<Set<Char>> = map { group -> group.reduce { result, current -> result.union(current) } } fun List<List<Set<Char>>>.allPerGroup(): List<Set<Char>> = map { group -> group.reduce { result, current -> result.intersect(current) } } fun parseAnswers(answers: String): List<List<Set<Char>>> = answers.split("""\n\s*\n""".toRegex()) .map { groupString -> groupString.trim().split("\n") .map { it.toCharArray().toSet() } .filter { it.isNotEmpty() } } class Day06_Part1 : FunSpec({ val answersString = """ abc a b c ab ac a a a a b """.trimIndent() context("parse answers") { val answers = parseAnswers(answersString) test("numer of groups") { answers.size shouldBe 5 } test("number of persons in group") { answers.map { it.size } shouldBe listOf(1, 3, 2, 4, 1) } test("yes answers per person with random samples") { answers[0][0] shouldBe setOf('a', 'b', 'c') answers[2][1] shouldBe setOf('a', 'c') answers[4] shouldBe listOf(setOf('b')) } } context("yes answers of group are a union of answers of persons") { test("union of answers per group") { parseAnswers(answersString).anyPerGroup() shouldBe listOf( setOf('a', 'b', 'c'), setOf('a', 'b', 'c'), setOf('a', 'b', 'c'), setOf('a'), setOf('b'), ) } test("sum yes answers") { parseAnswers(answersString).anyPerGroup().countYes() shouldBe 11 } } }) class Day06_Part1_Exercise: FunSpec({ val input = readResource("day06Input.txt")!! val count = parseAnswers(input).anyPerGroup().countYes() test("solution") { count shouldBe 6542 } }) class Day06_Part2 : FunSpec({ val answers = """ abc a b c ab ac a a a a b """.trimIndent() context("yes answers of group are a now an intersection of answers of persons") { test("intersection of answers per group") { parseAnswers(answers).allPerGroup() shouldBe listOf( setOf('a', 'b', 'c'), setOf(), setOf('a'), setOf('a'), setOf('b'), ) } test("sum yes answers") { parseAnswers(answers).allPerGroup().countYes() shouldBe 6 } } }) class Day06_Part2_Exercise: FunSpec({ val input = readResource("day06Input.txt")!! val count = parseAnswers(input).allPerGroup().countYes() test("solution") { count shouldBe 3299 } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
3,249
advent_of_code_2020
Apache License 2.0
src/Day04.kt
punx120
573,421,386
false
{"Kotlin": 30825}
fun main() { fun getRange(s : String) : Pair<Int, Int> { val parts = s.split("-") return Pair(parts[0].toInt(), parts[1].toInt()) } fun part1(input: List<String>): Int { var count = 0 for (line in input) { val split = line.split(',') val (r1, r2) = getRange(split[0]) val (l1, l2) = getRange(split[1]) if ((r1 <= l1 && l2 <= r2) || (l1 <= r1 && r2 <= l2)) { ++count } } return count } fun part2(input: List<String>): Int { var count = 0 for (line in input) { val split = line.split(',') val (r1, r2) = getRange(split[0]) val (l1, l2) = getRange(split[1]) if (l1 in r1..r2 || l2 in r1 .. r2 || r1 in l1..l2 || r2 in l1..l2) { ++count } } return count } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
eda0e2d6455dd8daa58ffc7292fc41d7411e1693
1,181
aoc-2022
Apache License 2.0
src/main/kotlin/year2022/Day21.kt
simpor
572,200,851
false
{"Kotlin": 80923}
import AoCUtils.test import java.lang.Exception enum class Operation { PLUS, MINUS, TIMES, DIVIDE } fun main() { open class Monkey data class MonkeyValue(val name: String, val value: Long) : Monkey() data class MonkeyOperation(val name: String, val first: String, val second: String, val operation: Operation) : Monkey() fun getValueFor(name: String, monkeyMap: Map<String, Monkey>): Long { val monkey = monkeyMap[name] return when (monkey) { is MonkeyValue -> monkey.value is MonkeyOperation -> when (monkey.operation) { Operation.PLUS -> getValueFor(monkey.first, monkeyMap) + getValueFor(monkey.second, monkeyMap) Operation.MINUS -> getValueFor(monkey.first, monkeyMap) - getValueFor(monkey.second, monkeyMap) Operation.TIMES -> getValueFor(monkey.first, monkeyMap) * getValueFor(monkey.second, monkeyMap) Operation.DIVIDE -> getValueFor(monkey.first, monkeyMap) / getValueFor(monkey.second, monkeyMap) } else -> throw Exception("nope") } } fun parse(input: String): Map<String, Monkey> { val monkeys = input.lines().map { line -> val split1 = line.split(":") val name = split1[0].trim() val num = split1[1].trim().toLongOrNull() if (num != null) { MonkeyValue(name, num) } else { val split2 = split1[1].trim().split(" ") MonkeyOperation( name, split2[0], split2[2], when (split2[1]) { "+" -> Operation.PLUS "-" -> Operation.MINUS "*" -> Operation.TIMES "/" -> Operation.DIVIDE else -> throw Exception("nope") } ) } } val monkeyMap = monkeys.map { when (it) { is MonkeyValue -> Pair(it.name, it) is MonkeyOperation -> Pair(it.name, it) else -> throw Exception("nope") } }.toMap() return monkeyMap } fun part1(input: String, debug: Boolean = false): Long { val monkeyMap = parse(input) val result = getValueFor("root", monkeyMap) return result } fun part2(input: String, debug: Boolean = false): Long { val monkeyMap = parse(input) val human = "humn" return 0L } val testInput = "root: pppw + sjmn\n" + "dbpl: 5\n" + "cczh: sllz + lgvd\n" + "zczc: 2\n" + "ptdq: humn - dvpt\n" + "dvpt: 3\n" + "lfqf: 4\n" + "humn: 5\n" + "ljgn: 2\n" + "sjmn: drzm * dbpl\n" + "sllz: 4\n" + "pppw: cczh / lfqf\n" + "lgvd: ljgn * ptdq\n" + "drzm: hmdt - zczc\n" + "hmdt: 32" val input = AoCUtils.readText("year2022/day21.txt") part1(testInput, false) test Pair(152L, "test 1 part 1") part1(input, false) test Pair(118565889858886L, "part 1") part2(testInput, false) test Pair(301L, "test 2 part 2") part2(input) test Pair(0L, "part 2") }
0
Kotlin
0
0
631cbd22ca7bdfc8a5218c306402c19efd65330b
3,333
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc2023/Day21.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import PointL import readInput import to2dCharArray object Day21 { private class GardenMap(private val map: Array<CharArray>) { private val maxX = map.size - 1 private val maxY = map.first().size - 1 private val validGrid = PointL(0, 0) to PointL(maxX, maxY) private val start = map.withIndex() .flatMap { (x, column) -> column.withIndex().map { (y, char) -> PointL(x, y) to char } } .first { it.second == 'S' }.first tailrec fun getReachablePointsForParity( remainingSteps: Int, currentPoints: Set<PointL> = setOf(start), pointsReachedWithSameParitySoFar: MutableSet<PointL> = currentPoints.toMutableSet(), parity: Parity = Parity.EVEN ): Set<PointL> { val reachable = currentPoints.flatMap { it.getNeighbours(validGrid = validGrid).filter { p -> map[p.x.toInt()][p.y.toInt()] != '#' } }.toSet() return if (remainingSteps == 0 || reachable.all { it in pointsReachedWithSameParitySoFar }) { pointsReachedWithSameParitySoFar } else { if ((remainingSteps % 2 == 1 && parity == Parity.EVEN) || (remainingSteps % 2 == 0 && parity == Parity.ODD)) { // we're at an "odd" position, so all points reachable from here can be reached with an even amount of steps pointsReachedWithSameParitySoFar.addAll(reachable) } getReachablePointsForParity( remainingSteps - 1, reachable, pointsReachedWithSameParitySoFar ) } } fun part2(maxSteps: Int): Int { val distances = visit(setOf(start), mutableMapOf(), 0) val maxDistance = distances.maxOf { it.value } val maxDistancePoints = distances.filter { it.value == maxDistance }.map { it.key } val maxDistanceAtTheEdges = maxDistancePoints.all { (it.x == 0L || it.x.toInt() == maxX) && (it.y == 0L || it.y.toInt() == maxY) } val top = PointL(start.x, maxY.toLong()) val bottom = PointL(start.x, 0L) val left = PointL(0, start.y) val right = PointL(maxX.toLong(), start.y) val sameDistanceToAllSides = listOf(left, right, top, bottom).mapNotNull { distances[it] } val totalEmptyTiles = map.sumOf { it.count { c -> c != '#' } } val stepsInNeighbourGridsUntilOriginalGridIsFilled = maxDistance - sameDistanceToAllSides.first() if (maxDistanceAtTheEdges) { println("max distance at the edges: $maxDistance") println("distance to all sides: ${sameDistanceToAllSides.first()}") println("visited in original grid: ${distances.size}") println("total empty tiles in original grid: $totalEmptyTiles") println("unreachable tiles: ${totalEmptyTiles - distances.size}") println("stepsInNeighbourGridsUntilOriginalGridIsFilled: $stepsInNeighbourGridsUntilOriginalGridIsFilled") println("nextMiddleReached: ${stepsInNeighbourGridsUntilOriginalGridIsFilled > sameDistanceToAllSides.first()}") val pointsReachedInTopGrid = getReachablePointsForParity( stepsInNeighbourGridsUntilOriginalGridIsFilled, currentPoints = setOf(bottom), parity = Parity.from(stepsInNeighbourGridsUntilOriginalGridIsFilled) ).size val pointsReachedInBottomGrid = getReachablePointsForParity( stepsInNeighbourGridsUntilOriginalGridIsFilled, currentPoints = setOf(top), parity = Parity.from(stepsInNeighbourGridsUntilOriginalGridIsFilled) ).size val pointsReachedInLeftGrid = getReachablePointsForParity( stepsInNeighbourGridsUntilOriginalGridIsFilled, currentPoints = setOf(right), parity = Parity.from(stepsInNeighbourGridsUntilOriginalGridIsFilled) ).size val pointsReachedInRightGrid = getReachablePointsForParity( stepsInNeighbourGridsUntilOriginalGridIsFilled, currentPoints = setOf(left), parity = Parity.from(stepsInNeighbourGridsUntilOriginalGridIsFilled) ).size println("top: $pointsReachedInTopGrid, bottom: $pointsReachedInBottomGrid, left: $pointsReachedInLeftGrid, right: $pointsReachedInRightGrid") println("total: ${distances.size + pointsReachedInBottomGrid + pointsReachedInLeftGrid + pointsReachedInRightGrid + pointsReachedInTopGrid} in $maxDistance steps") // double the step count val nextFilledSteps = maxDistance * 2 val bottomLeft = PointL(0, maxY) val bottomRight = PointL(maxX, maxY) val topLeft = PointL(0, 0) val topRight = PointL(maxX, 0) val stepsLeftWhenStartingFromCorners = nextFilledSteps - maxDistance val pointsReachedFromBottomLeft = getReachablePointsForParity( stepsLeftWhenStartingFromCorners, currentPoints = setOf(bottomLeft), parity = Parity.from(stepsLeftWhenStartingFromCorners) ).size val pointsReachedFromBottomRight = getReachablePointsForParity( stepsLeftWhenStartingFromCorners, currentPoints = setOf(bottomRight), parity = Parity.from(stepsLeftWhenStartingFromCorners) ).size val pointsReachedFromTopLeft = getReachablePointsForParity( stepsLeftWhenStartingFromCorners, currentPoints = setOf(topLeft), parity = Parity.from(stepsLeftWhenStartingFromCorners) ).size val pointsReachedFromTopRight = getReachablePointsForParity( stepsLeftWhenStartingFromCorners, currentPoints = setOf(topRight), parity = Parity.from(stepsLeftWhenStartingFromCorners) ).size val reached = distances.size * (4 + 1) + pointsReachedInBottomGrid + pointsReachedInLeftGrid + pointsReachedInRightGrid + pointsReachedInTopGrid + pointsReachedFromBottomLeft + pointsReachedFromBottomRight + pointsReachedFromTopLeft + pointsReachedFromTopRight println("total after $nextFilledSteps steps: $reached") val stepsForSmallDiamond = distances[top]!! val remainingSteps = maxSteps - stepsForSmallDiamond println(remainingSteps) val configurations: Map<Pair<Parity, PointL>, IntArray> = mapOf( (Parity.EVEN to start) to IntArray(130), (Parity.ODD to start) to IntArray(130), (Parity.EVEN to top) to IntArray(130), (Parity.ODD to top) to IntArray(130), (Parity.EVEN to bottom) to IntArray(130), (Parity.ODD to bottom) to IntArray(130), (Parity.EVEN to left) to IntArray(130), (Parity.ODD to left) to IntArray(130), (Parity.EVEN to right) to IntArray(130), (Parity.ODD to right) to IntArray(130), (Parity.EVEN to topLeft) to IntArray(130), (Parity.ODD to topLeft) to IntArray(130), (Parity.EVEN to topRight) to IntArray(130), (Parity.ODD to topRight) to IntArray(130), (Parity.EVEN to bottomLeft) to IntArray(130), (Parity.ODD to bottomLeft) to IntArray(130), (Parity.EVEN to bottomRight) to IntArray(130), (Parity.ODD to bottomRight) to IntArray(130), ) configurations.forEach { entry -> for (steps in 0..129) { entry.value[steps] = getReachablePointsForParity( steps, currentPoints = setOf(topLeft), parity = entry.key.first ).size } } var steps = 0 var tileReached = 0L for (step in 1..maxSteps) { } steps += 130 tileReached += configurations[Parity.EVEN to start]!![130] + configurations[Parity.ODD to top]!![65] + configurations[Parity.ODD to bottom]!![65] + configurations[Parity.ODD to left]!![65] + configurations[Parity.ODD to right]!![65] steps += 65 tileReached += configurations[Parity.ODD to top]!![65] + configurations[Parity.ODD to bottom]!![65] + configurations[Parity.ODD to left]!![65] + configurations[Parity.ODD to right]!![65] steps += 65 } return 0 } private enum class Parity { EVEN, ODD; companion object { fun from(input: Int) = if (input % 2 == 0) EVEN else ODD } } tailrec fun visit(current: Set<PointL>, alreadySeen: MutableMap<PointL, Int>, steps: Int): Map<PointL, Int> { val newPoints = current.flatMap { it.getNeighbours(validGrid = validGrid) } .filter { p -> map[p.x.toInt()][p.y.toInt()] != '#' && p !in alreadySeen.keys }.toSet() return if (newPoints.isEmpty()) { alreadySeen } else { newPoints.forEach { alreadySeen[it] = steps } visit(newPoints, alreadySeen, steps + 1) } } } fun part1(input: List<String>, steps: Int): Int { val map = GardenMap(input.to2dCharArray()) return map.getReachablePointsForParity(steps).size } fun part2(input: List<String>, steps: Int): Int { val map = GardenMap(input.to2dCharArray()) return map.part2(steps) / 2 } } fun main() { val testInput = readInput("Day21_test", 2023) check(Day21.part1(testInput, steps = 6) == 16) /* check(Day21.part2(testInput, steps = 10) == 50) check(Day21.part2(testInput, steps = 50) == 1594) check(Day21.part2(testInput, steps = 100) == 6536) check(Day21.part2(testInput, steps = 500) == 167004) check(Day21.part2(testInput, steps = 1000) == 668697) check(Day21.part2(testInput, steps = 5000) == 16733044) */ val input = readInput("Day21", 2023) println(Day21.part1(input, steps = 64)) println(Day21.part2(input, steps = 26501365)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
11,293
adventOfCode
Apache License 2.0
src/Day11.kt
sungi55
574,867,031
false
{"Kotlin": 23985}
fun main() { val day = "Day11" fun getMonkey(index: Int, lines: List<String>, decreaseWorryStrategy: (Long) -> Long): Monkey { val (sign, increaseBy) = lines[index + 2] .substringAfter("old ") .split(" ") .let { it.first() to if (it.last() == "old") null else it.last().toLong() } return Monkey( items = lines[index + 1] .substringAfter(": ") .split(", ") .map { it.toLong() } .toMutableList(), worryLevel = Monkey.WorryLevel( divisibleValue = lines[index + 3].substringAfterLast(" ").toLong(), increaseBy = increaseBy, increaseSign = sign, decreaseBy = decreaseWorryStrategy ), moveFirst = lines[index + 4].substringAfterLast(" ").toInt(), moveSecond = lines[index + 5].substringAfterLast(" ").toInt() ) } fun getMonkeys(lines: List<String>, decreaseWorryStrategy: (Long) -> Long = { 0L }) = mutableMapOf<Int, Monkey>().apply { for (input in lines.indices step 7) { val monkeyPoint = lines[input].dropLast(1).substringAfterLast(" ").toInt() this[monkeyPoint] = getMonkey(input, lines, decreaseWorryStrategy) } } fun getMonkeysBusiness(lines: List<String>, rounds: Int, decreaseWorryStrategy: (Long) -> Long) = getMonkeys(lines, decreaseWorryStrategy).apply { repeat(rounds) { values.forEach { monkey -> monkey.items.indices.onEach { monkey.inspectAndThrow()?.let { (monkeyPoint, pack) -> this[monkeyPoint]?.catchPack(pack) } } } } }.withMostBusiness() fun part1(lines: List<String>): Long = getMonkeysBusiness(lines, 20) { it.div(3) } fun part2(lines: List<String>): Long { val decreaseWorryStrategy = getMonkeys(lines).values.map { it.worryLevel.divisibleValue }.reduce(Long::times) return getMonkeysBusiness(lines, 10000) { it % decreaseWorryStrategy } } val testInput = readInput(name = "${day}_test") val input = readInput(name = day) check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158) println(part1(input)) println(part2(input)) } private data class Monkey( val items: MutableList<Long>, val worryLevel: WorryLevel, val moveFirst: Int, val moveSecond: Int, var packInspected: Int = 0, ) { data class WorryLevel( val divisibleValue: Long, val increaseSign: String, val increaseBy: Long?, val decreaseBy: (Long) -> Long ) fun catchPack(pack: Long): Monkey = apply { items.add(pack) } fun inspectAndThrow(): Pair<Int, Long>? = startInspection().completeInspection().throwPack() private fun startInspection(): Monkey = apply { items.firstOrNull()?.also { pack -> items.removeFirst() items.add(0, worryLevel.applySignWith(pack)) packInspected++ } } private fun WorryLevel.applySignWith(pack: Long) = when (increaseSign) { "+" -> (increaseBy ?: pack) + pack "-" -> (increaseBy ?: pack) - pack "*" -> (increaseBy ?: pack) * pack else -> (increaseBy ?: pack) / pack } private fun completeInspection() = apply { items.firstOrNull()?.also { pack -> items.removeFirst() items.add(0, worryLevel.decreaseBy(pack)) } } private fun throwPack(): Pair<Int, Long>? = when { items.isEmpty() -> null items.first().passWorryLevel() -> moveFirst to items.first() else -> moveSecond to items.first() }.also { items.removeFirstOrNull() } private fun Long.passWorryLevel() = this % worryLevel.divisibleValue == 0L } private fun Map<Int, Monkey>.withMostBusiness() = values .sortedByDescending { it.packInspected } .take(2) .map { it.packInspected } .let { it[0].toLong() * it[1] }
0
Kotlin
0
0
2a9276b52ed42e0c80e85844c75c1e5e70b383ee
4,238
aoc-2022
Apache License 2.0
src/day14/a/day14a.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day14.a import readInputLines import shouldBe import vec2 import util.IntVector import java.lang.Integer.max import java.lang.Integer.min import kotlin.math.abs typealias Grid = HashMap<IntVector, Char> fun main() { val grid = read() val entry = vec2(500,0) val bottom = grid.keys.map { it[1] }.reduce(Integer::max) fun step(): Boolean { var p = entry time@while (true) { for (d in listOf(0, -1, 1)) { val q = p + vec2(d, 1) if (q[1] > bottom) return true if (!grid.containsKey(q)) { p = q continue@time } } break@time } grid[p] = '.' return false } var n = 0 while (!step()) n++ shouldBe(1003, n) } fun show(grid: Grid) { val bb0 = grid.keys.reduce{ a,b -> vec2(min(a[0],b[0]), min(a[1],b[1])) } val bb1 = grid.keys.reduce{ a,b -> vec2(max(a[0],b[0]), max(a[1],b[1])) } println() for (y in bb0[1]..bb1[1]) { for (x in bb0[0]..bb1[0]) print(grid[vec2(x, y)] ?: ' ') println() } } fun read(): Grid { val r = readInputLines(14).map { s -> s.split(" -> ").map { IntVector.parse(it) } } val g = Grid() r.forEach { rock -> val it = rock.iterator() var a = it.next() while(it.hasNext()) { val b = it.next() val d = (b-a).map { if (it == 0) 0 else it / abs(it) } var c = a g[c] = '#' while (c != b) { c += d g[c] = '#' } a = b } } return g }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
1,679
advent-of-code-2022
Apache License 2.0
src/Day14/Solution.kt
cweinberger
572,873,688
false
{"Kotlin": 42814}
package Day14 import readInput import toInt import java.util.Scanner import kotlin.math.abs import kotlin.math.sign object Solution { fun parseLine(line: String) : List<Pair<Int, Int>> { return line .split(" -> ") .map { it.split(',') .map { it.toInt() } } .map { Pair(it.first(), it.last()) } } fun getRange(instructions: List<List<Pair<Int, Int>>>): Pair<Pair<Int, Int>, Pair<Int, Int>> { val minX = instructions.flatten().minOf { it.first } val maxX = instructions.flatten().maxOf { it.first } val minY = instructions.flatten().minOf { it.second } val maxY = instructions.flatten().maxOf { it.second } return Pair(Pair(minX, maxX), Pair(minY, maxY)) } fun normalizeInstructions(instructions: List<List<Pair<Int, Int>>>): List<List<Pair<Int, Int>>> { val xRange = getRange(instructions).first val xDiff = -xRange.first return instructions.map { path -> path.map { point -> Pair( point.first + xDiff, point.second ) } } } fun createMap(instructions: List<List<Pair<Int, Int>>>, char: Char): Array<Array<Char>> { val dimensions = getRange(instructions) return Array(dimensions.second.second + 1) { Array(dimensions.first.second + 1) { char } } } fun printMap(map: Array<Array<Char>>) { println("+++ Printing Map of size ${map.first().size} x ${map.size} +++") map.forEach { row -> println(String(row.toCharArray())) } } fun drawPoint(x: Int, y: Int, char: Char, on: Array<Array<Char>>) { on[y][x] = char } fun drawLine( from: Pair<Int, Int>, to: Pair<Int, Int>, char: Char, on: Array<Array<Char>> ) { val diffX = from.first - to.first val diffY = from.second - to.second if (diffX != 0) { for (x in 0 .. abs(diffX)) { val signedX = from.first - x * diffX/abs(diffX) drawPoint(x = signedX, y = from.second, char = char, on = on) } } else if (diffY != 0) { for (y in 0 .. abs(diffY)) { val signedY = from.second - y * diffY/abs(diffY) drawPoint(x = from.first, y = signedY, char = char, on = on) } } } fun drawPath( path: List<Pair<Int, Int>>, char: Char, on: Array<Array<Char>> ) { var from = path.first() path.takeLast(path.size-1).forEach { to -> drawLine(from, to, char, on) from = to } } fun drawPaths( paths: List<List<Pair<Int, Int>>>, char: Char, on: Array<Array<Char>> ) { paths.forEach { path -> drawPath(path, char, on) } } fun emitSand(source: Pair<Int, Int>, on: Array<Array<Char>>) : Pair<Int, Int> { var sandPosition = source for(y in source.second until (on.size - 1)) { val belowLeft = on[y+1].getOrNull(sandPosition.first-1) val belowCenter = on[y+1].getOrNull(sandPosition.first) val belowRight = on[y+1].getOrNull(sandPosition.first+1) if (belowCenter == '.' || belowCenter == null) { sandPosition = Pair(sandPosition.first, y+1) } else if (belowLeft == '.' || belowLeft == null) { sandPosition = Pair(sandPosition.first-1, y+1) } else if (belowRight == '.' || belowRight == null) { sandPosition = Pair(sandPosition.first+1, y+1) } else { break } } return sandPosition } fun part1(input: List<String>) : Int { // parse instructions val instructions = input.map { parseLine(it) } // normalize val normalizedInstructions = normalizeInstructions(instructions) // create map val map = createMap(normalizedInstructions, '.') drawPaths(normalizedInstructions, '#', map) // draw sand source val normalizedXDiff = normalizedInstructions.first().first().first - instructions.first().first().first val sandSource = Pair(500+normalizedXDiff, 0) drawPoint(sandSource.first, sandSource.second, '+', map) printMap(map) // emit sand var counter = 0 while(true) { val emittedSandPosition = emitSand(sandSource, map) if(emittedSandPosition.first < 0 || emittedSandPosition.first > map.first().size) { break } counter++ drawPoint(emittedSandPosition.first, emittedSandPosition.second, 'o', map) } printMap(map) return counter } fun part2(input: List<String>) : Int { // parse instructions val instructions = input.map { parseLine(it) } // add bottom line val range = getRange(instructions) val yMax = range.second.second val newInstruction = listOf( Pair(range.first.first - (yMax), yMax + 2), Pair(range.first.second + (yMax), yMax + 2) ) val updatedInstructions = instructions.toMutableList() updatedInstructions.add(newInstruction) // normalize val normalizedInstructions = normalizeInstructions(updatedInstructions) // create map val map = createMap(normalizedInstructions, '.') drawPaths(normalizedInstructions, '#', map) // draw sand source val normalizedXDiff = normalizedInstructions.first().first().first - instructions.first().first().first val sandSource = Pair(500+normalizedXDiff, 0) drawPoint(sandSource.first, sandSource.second, '+', map) printMap(map) // emit sand var counter = 0 while(true) { val emittedSandPosition = emitSand(sandSource, map) counter++ drawPoint(emittedSandPosition.first, emittedSandPosition.second, 'o', map) if(emittedSandPosition.first == sandSource.first && emittedSandPosition.second == sandSource.second) { break } } printMap(map) return counter } } fun main() { val testInput = readInput("Day14/TestInput") val input = readInput("Day14/Input") println("\n=== Part 1 - Test Input ===") println(Solution.part1(testInput)) println("\n=== Part 1 - Final Input ===") println(Solution.part1(input)) println("\n=== Part 2 - Test Input ===") println(Solution.part2(testInput)) println("\n=== Part 2 - Final Input ===") println(Solution.part2(input)) }
0
Kotlin
0
0
883785d661d4886d8c9e43b7706e6a70935fb4f1
6,848
aoc-2022
Apache License 2.0
src/main/kotlin/com/sherepenko/leetcode/solutions/LongestPalindromicSubstring.kt
asherepenko
264,648,984
false
null
package com.sherepenko.leetcode.solutions import com.sherepenko.leetcode.Solution import kotlin.math.max class LongestPalindromicSubstring( private val str: String ) : Solution { companion object { fun longestPalindrome(str: String): String? { if (str.length <= 1) { return str } val dp = Array(str.length) { IntArray(str.length) } var maxLength = 0 var start = 0 var end = 0 for (j in str.indices) { dp[j][j] = 1 for (i in 0 until j) { if (str[i] == str[j] && (j - i <= 2 || dp[i + 1][j - 1] == 1)) { dp[i][j] = 1 if (j - i + 1 > maxLength) { maxLength = j - i + 1 start = i end = j } } } } dp.forEach { println(" ${it.joinToString(separator = " ")}") } return str.substring(start..end) } fun longestPalindromeII(str: String): String? { if (str.length <= 1) { return str } var start = 0 var end = 0 for (i in str.indices) { val length = max( str.expand(i, i), str.expand(i, i + 1) ) if (length > end - start) { start = i - (length - 1) / 2 end = i + length / 2 } } return str.substring(start..end) } private fun String.expand(start: Int, end: Int): Int { var i = start var j = end while (i >= 0 && j < length && this[i] == this[j]) { i-- j++ } return j - i - 1 } } override fun resolve() { val result = longestPalindrome(str) println( "Longest Palindromic Substring: \n" + " Input: $str; \n" + " Result: $result \n" ) } }
0
Kotlin
0
0
49e676f13bf58f16ba093f73a52d49f2d6d5ee1c
2,259
leetcode
The Unlicense
day11/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.lang.Double.NEGATIVE_INFINITY fun main() { val powerLevelGrid = fillPowerLevelGrid(3214) println("Part I: the solution is ${solvePartI(powerLevelGrid)}.") println("Part II: the solution is ${solvePartII(powerLevelGrid)}.") } fun solvePartI(powerLevelGrid: Array<IntArray>): String { val size = 3 var maxTotalPower = -10000 var maxCoordinate = "" for (topLeftX in 1..(301 - size)) { for (topLeftY in 1..(301 - size)) { var totalPower = 0 for (x in topLeftX..(topLeftX + size - 1)) { for (y in topLeftY..(topLeftY + size - 1)) { totalPower += powerLevelGrid[x - 1][y - 1] } } if (totalPower > maxTotalPower) { maxTotalPower = totalPower maxCoordinate = "$topLeftX,$topLeftY" } } } return maxCoordinate } fun solvePartII(powerLevelGrid: Array<IntArray>): String { var maxTotalPower = NEGATIVE_INFINITY.toInt() var maxCoordinateAndSize = "" for (size in 1..300) { for (topLeftX in 1..(301 - size)) { for (topLeftY in 1..(301 - size)) { var totalPower = 0 for (x in topLeftX..(topLeftX + size - 1)) { for (y in topLeftY..(topLeftY + size - 1)) { totalPower += powerLevelGrid[x - 1][y - 1] } } if (totalPower > maxTotalPower) { maxTotalPower = totalPower maxCoordinateAndSize = "$topLeftX,$topLeftY,$size" } } } } return maxCoordinateAndSize } fun fillPowerLevelGrid(gridSerialNumber: Int): Array<IntArray> { val result = Array(300) { IntArray(300) } for (x in 1..300) { for (y in 1..300) { result[x - 1][y - 1] = calculatePowerLevel(x, y, gridSerialNumber) } } return result } fun calculatePowerLevel(x: Int, y: Int, gridSerialNumber: Int): Int { val rackId = x + 10 var result = rackId * y result += gridSerialNumber result *= rackId result = getHundredsDigit(result) result -= 5 return result } fun getHundredsDigit(input: Int): Int { return (input / 100) % 10 }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
2,306
AdventOfCode2018
MIT License
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day13.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2022 import java.util.ArrayDeque as Deque class Day13(private val input: List<String>) { fun solvePart1(): Int { return input.asSequence() .filter { it.isNotEmpty() } .map { line -> parseArray(Deque(line.toList())) } .windowed(2, 2) .mapIndexed { index, list -> index + 1 to list } .filter { (_, list) -> list[0] < list[1] } .sumOf { (index, _) -> index } } fun solvePart2(): Int { val divider1 = PacketList(PacketList(PacketInteger(2))) val divider2 = PacketList(PacketList(PacketInteger(6))) val sorted = input.asSequence() .filter { it.isNotEmpty() } .map { line -> parseArray(Deque(line.toList())) } .plus(divider1) .plus(divider2) .sorted() return (sorted.indexOf(divider1) + 1) * (sorted.indexOf(divider2) + 1) } private fun parseArray(deque: Deque<Char>): PacketList { deque.removeFirst() val result = mutableListOf<PacketValue>() while (true) { if (deque.peekFirst() == '[') { result.add(parseArray(deque)) } when (val c = deque.removeFirst()) { ']' -> break ',' -> {} else -> { val value = if (deque.peekFirst().isDigit()) { c.digitToInt() * 10 + deque.removeFirst().digitToInt() } else { c.digitToInt() } result += PacketInteger(value) } } } return PacketList(result) } private sealed interface PacketValue : Comparable<PacketValue> private class PacketList(val items: List<PacketValue>) : PacketValue, Comparable<PacketValue> { constructor(item: PacketValue) : this(listOf(item)) override fun compareTo(other: PacketValue): Int { if (other !is PacketList) { return this.compareTo(PacketList(other)) } for (i in this.items.indices) { if (i >= other.items.size) { return 1 } val a = this.items[i] val b = other.items[i] val result = a.compareTo(b) if (result != 0) { return result } } return if (this.items.size < other.items.size) { -1 } else { 0 } } override fun toString(): String = items.joinToString(",", "[", "]") } private class PacketInteger(val value: Int) : PacketValue { override fun compareTo(other: PacketValue): Int { return if (other is PacketInteger) { this.value.compareTo(other.value) } else { -other.compareTo(PacketList(this)) } } override fun toString(): String = value.toString() } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
3,082
advent-of-code
Apache License 2.0
src/main/kotlin/com/uber/tagir/advent2018/day03/day03.kt
groz
159,977,575
false
null
package com.uber.tagir.advent2018.day03 import com.uber.tagir.advent2018.utils.resourceAsString fun main(args: Array<String>) { with(Day03()) { overlaps() single() } } data class Claim(val id: Int, val left: Int, val top: Int, val width: Int, val height: Int) fun parseClaim(s: String): Claim { // using toRegex doesn't support extracting groups by name in JDK 9+ val p = """#(?<id>\d+) @ (?<left>\d+),(?<top>\d+): (?<width>\d+)x(?<height>\d+)""".toPattern() val m = p.matcher(s) m.find() fun extract(name: String) = m.group(name).toInt() return Claim( id = extract("id"), left = extract("left"), top = extract("top"), width = extract("width"), height = extract("height") ) } class Day03 { private val input = resourceAsString("input.txt").lines() private val claims = input.map(::parseClaim) private val field = buildField(claims) private fun buildField(claims: Collection<Claim>): List<Array<MutableSet<Claim>>> { val width: Int = claims.map { it.left + it.width }.max()!! val height: Int = claims.map { it.top + it.height }.max()!! val field = (0 until height).map { Array(width) { mutableSetOf<Claim>() } } for (c in claims) { for (row in c.top until (c.top + c.height)) { for (col in c.left until (c.left + c.width)) { field[row][col].add(c) } } } return field } fun overlaps() { val nOverlaps = field.map { row -> row.count { it.size > 1 } }.sum() println(nOverlaps) } fun single() { val duplicates = field.flatMap { row -> row.filter { it.size > 1 } }.flatten() println(claims - duplicates) } }
0
Kotlin
0
0
19b5a5b86c9a3d2803192b8c6786a25151b5144f
1,819
advent2018
MIT License
src/main/kotlin/Day15.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset fun main() { fun hash(startValue: Int, instruction: String): Int { return instruction.fold(startValue) { acc, c -> ((acc + c.code) * 17) % 256 } } fun part1(input: List<String>): Int { val instructions = input.first.split(",") return instructions.sumOf { hash(0, it) } } fun arrangeInBoxes(input: List<String>): Map<Int, MutableList<Pair<String, Int>>> { val boxes = (0..255).associateWith { mutableListOf<Pair<String, Int>>() } val instructions = input.first.split(",") instructions.forEach { val label = it.substringBefore('=', it.substringBefore('-')) val remove = it.contains('-') val boxNumber = hash(0, label) if (remove) { val lensIndex = boxes[boxNumber]!!.indexOfFirst { lens -> lens.first == label } if (lensIndex >= 0) boxes[boxNumber]!!.removeAt(lensIndex) } else { val lensIndex = boxes[boxNumber]!!.indexOfFirst { lens -> lens.first == label } val lensPower = it.substringAfter("=").toInt() if (lensIndex < 0) { boxes[boxNumber]!!.add(label to lensPower) } else { boxes[boxNumber]!![lensIndex] = label to lensPower } } } return boxes } fun calculatePower(boxes: Map<Int, MutableList<Pair<String, Int>>>): Int { return boxes.entries.sumOf { it.value.foldIndexed(0 as Int) { index, acc, pair -> acc + (it.key + 1) * (index + 1) * pair.second } } } fun part2(input: List<String>): Int { val boxes = arrangeInBoxes(input) return calculatePower(boxes) } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day15-input.txt") val result1 = part1(input) "Result1: $result1".println() val result2 = part2(input) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
2,224
aoc-2023-in-kotlin
Apache License 2.0
src/problems/day2/daytwo.kt
klnusbaum
733,782,662
false
{"Kotlin": 43060}
package problems.day2 import java.io.File private const val gamesFile = "input/day2/games.txt" fun main() { part1() part2() } private data class Round(val red: Int, val green: Int, val blue: Int) private data class Game(val id: Int, val rounds: List<Round>) { fun allRedUnder(max: Int) = rounds.all { it.red <= max } fun allGreenUnder(max: Int) = rounds.all { it.green <= max } fun allBlueUnder(max: Int) = rounds.all { it.blue <= max } fun power() = maxRed() * maxGreen() * maxBlue() private fun maxRed() = rounds.maxOf { it.red } private fun maxGreen() = rounds.maxOf { it.green } private fun maxBlue() = rounds.maxOf { it.blue } } private fun part1() { val idSum = File(gamesFile).bufferedReader().useLines { sumIDs(it) } println("ID sum is $idSum") } private fun sumIDs(lines: Sequence<String>) = lines.map { it.toGame() } .filter { it.allRedUnder(12) and it.allGreenUnder(13) and it.allBlueUnder(14) } .map { it.id } .sum() private fun String.toGame(): Game = Game( this.substringBefore(":").toGameID(), this.substringAfter(":").toRounds(), ) private fun String.toGameID(): Int = this.trim().removePrefix("Game ").toInt() private fun String.toRounds(): List<Round> = this.trim().split(";").map { it.toRound() } private fun String.toRound(): Round { var red = 0 var green = 0 var blue = 0 this.split(",").map { it.trim() }.forEach { val amount = it.substringBefore(" ").toInt() when (it.substringAfter(" ")) { "red" -> red = amount "blue" -> blue = amount "green" -> green = amount } } return Round(red, green, blue) } private fun part2() { val powerSum = File(gamesFile).bufferedReader().useLines { sumPower(it) } println("Power sum is $powerSum") } private fun sumPower(lines: Sequence<String>) = lines.map { it.toGame().power() }.sum()
0
Kotlin
0
0
d30db2441acfc5b12b52b4d56f6dee9247a6f3ed
1,946
aoc2023
MIT License
src/main/kotlin/com/dmc/advent2022/Day03.kt
dorienmc
576,916,728
false
{"Kotlin": 86239}
//--- Day 3: Rucksack Reorganization --- package com.dmc.advent2022 class Day03 : Day<Int> { override val index = 3 override fun part1(input: List<String>): Int { return input.sumOf { it.overlap().priority() } } override fun part2(input: List<String>): Int { return input.chunked(3).sumOf { it.overlap().priority() } } } fun String.overlap() : Char { return listOf( this.substring(0, this.length/2), this.substring(this.length/2)). overlap() } fun List<String>.overlap() : Char { return map { it.toSet() } .reduce { left, right -> left.intersect(right) } .first() } fun Char.priority() : Int = when (this) { '0' -> 0 in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> throw IllegalArgumentException("Letter not in range: $this") } fun main() { val day = Day03() // test if implementation meets criteria from the description, like: val testInput = readInput(day.index, true) check(day.part1(testInput) == 157) val input = readInput(day.index) day.part1(input).println() day.part2(input).println() }
0
Kotlin
0
0
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
1,173
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/com/sk/topicWise/dp/322. Coin Change.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.dp /** * f(n) : Function to return minimum no of coins required to make n, return -1 otherwise. * f(n) = min{ 1 + f(n - arr[i]) } * where 0 <= i < size and arr[i] <= n */ class Solution322 { // dp, bottom-up fun coinChange(coins: IntArray, amount: Int): Int { if (amount == 0) return 0 val dp = IntArray(amount + 1) { -1 } for (i in 1..amount) { var minCoins = Int.MAX_VALUE for (j in coins.indices) { if (i == coins[j]) { minCoins = 1 break } if (i - coins[j] < 0) continue if (dp[i - coins[j]] == -1) continue minCoins = minOf(minCoins, dp[i - coins[j]] + 1) } if (minCoins != Int.MAX_VALUE) { dp[i] = minCoins } } return dp[amount] } } fun main() { val s = Solution322() s.coinChange(intArrayOf(1, 2, 5), 11) } // todo: Fix below soltions later private class SolutionCoinChange { // Solution-1, simple recursive fun coinChange1(arr: IntArray, n: Int): Int { if (n == 0) return 0 var res = Int.MAX_VALUE for (e in arr) { if (e <= n) { val r = coinChange1(arr, n - e) if (r != -1 && r + 1 < res) { res = r + 1 } } } if (res == Int.MAX_VALUE) res = -1 return res } // Solution-2, DP, top-down fun coinChange2(arr: IntArray, n: Int): Int { val dp = IntArray(n + 1) { 0 } return topdown(arr, n, dp) } private fun topdown(arr: IntArray, n: Int, dp: IntArray): Int { if (n == 0) return 0 if (dp[n] != 0) return dp[n] var res = Int.MAX_VALUE for (e in arr) { if (e <= n) { val r = topdown(arr, n - e, dp) if (r != -1 && r + 1 < res) { res = r + 1 } } } if (res == Int.MAX_VALUE) res = -1 dp[n] = res return res } // Solution-3, dp, bottom-up fun coinChange3(coins: IntArray, amount: Int): Int { if (amount == 0) return 0 val dp = IntArray(amount + 1) var sum = 0 while (++sum <= amount) { var min = -1 for (coin in coins) { if (sum >= coin && dp[sum - coin] != -1) { val temp = dp[sum - coin] + 1 min = if (min < 0) temp else if (temp < min) temp else min } } dp[sum] = min } return dp[amount] } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
2,714
leetcode-kotlin
Apache License 2.0
src/Day03.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
fun Char.priority(): Int = if (code > 96) code - 96 else code - 64 + 26 fun main() { fun part1(input: List<String>): Int { var result = 0 for (line in input) { val firstCompartment = IntArray(53) for (i in 0 until line.length / 2) { firstCompartment[line[i].priority()] = 1 } for (i in line.length / 2 until line.length) { if (firstCompartment[line[i].priority()] == 1) { result += line[i].priority() break } } } return result } fun part2(input: List<String>): Int { var result = 0 lateinit var items: IntArray for ((index, line) in input.withIndex()) { if (index % 3 == 0) items = IntArray(53) val expected = index % 3 for (i in line.indices) { val current = items[line[i].priority()] if (current == expected) { if (expected == 2) { result += line[i].priority() break } else { items[line[i].priority()] = expected + 1 } } } } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
1,551
advent-of-code-2022
Apache License 2.0
dynamic_programming/UniquePathsII/kotlin/Solution.kt
YaroslavHavrylovych
78,222,218
false
{"Java": 284373, "Kotlin": 35978, "Shell": 2994}
/** * A robot is located at the top-left corner of a m x n grid * (marked 'Start' in the diagram below). * The robot can only move either down or right at any point in time. * The robot is trying to reach the bottom-right corner of the grid * (marked 'Finish' in the diagram below). * Now consider if some obstacles are added to the grids. * How many unique paths would there be? * An obstacle and space is marked as 1 and 0 respectively in the grid. * <br> * https://leetcode.com/problems/unique-paths-ii/ */ typealias Matrix = Array<IntArray> class Solution { fun uniquePathsWithObstacles(ip: Matrix): Int { if(ip.size == 0 || ip[0].size == 0) return 0 val cache = Array(ip.size) { IntArray(ip[0].size) } cache[0][0] = if(ip[0][0] == 1) 0 else 1 for(i in 1..ip.indices.last) cache[i][0] = if(ip[i][0] == 1) 0 else cache[i-1][0] for(j in 1..ip[0].indices.last) cache[0][j] = if(ip[0][j] == 1) 0 else cache[0][j-1] for(i in 1..ip.indices.last) { for(j in 1..ip[0].indices.last) { cache[i][j] = if(ip[i][j] == 1) 0 else cache[i-1][j] + cache[i][j-1] } } return cache[cache.indices.last][cache[0].indices.last] } } fun main() { println("Unique Paths II: test is not implemented") }
0
Java
0
2
cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd
1,313
codility
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem516/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem516 /** * LeetCode page: [516. Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/); */ class Solution { /* Complexity: * Time O(N^2) and Space O(N^2) where N is the length of s; */ fun longestPalindromeSubseq(s: String): Int { // subResults[i][j] ::= longestPalindromeSubseq(s.slice(i until i+j)) val subResults = subResultHolder(s.length).apply { updateBaseCases(this) updateRemainingCases(s, this) } return originalProblem(subResults) } private fun subResultHolder(inputLength: Int): Array<IntArray> { return Array(inputLength) { start -> val maxSubStringLength = inputLength - start IntArray(maxSubStringLength + 1) } } private fun updateBaseCases(subResultHolder: Array<IntArray>) { for (start in subResultHolder.indices) { subResultHolder[start][0] = 0 subResultHolder[start][1] = 1 } } private fun updateRemainingCases(inputString: String, subResultHolder: Array<IntArray>) { val inputLength = inputString.length for (length in 2..inputLength) { val maxSubStringStart = inputLength - length for (start in 0..maxSubStringStart) { val isStartEndSameChar = inputString[start] == inputString[start + length - 1] val subResult = if (isStartEndSameChar) { 2 + subResultHolder[start + 1][length - 2] } else { maxOf(subResultHolder[start][length - 1], subResultHolder[start + 1][length - 1]) } subResultHolder[start][length] = subResult } } } private fun originalProblem(subResultHolder: Array<IntArray>): Int { return subResultHolder[0].last() } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,915
hj-leetcode-kotlin
Apache License 2.0
kotlin/src/main/kotlin/adventofcode/day7/Day7_2.kt
thelastnode
160,586,229
false
null
package adventofcode.day7 import java.io.File import java.util.* object Day7_2 { data class Input(val step: String, val dependency: String) private val LINE_REGEX = Regex("Step (\\w+) must be finished before step (\\w+) can begin") fun parse(line: String): Input { val match = LINE_REGEX.find(line) val (_, dependency, step) = match!!.groupValues return Input(step = step, dependency = dependency) } data class Event(val completedStep: String, val time: Int) : Comparable<Event> { override fun compareTo(other: Event): Int = time.compareTo(other.time) } fun process(inputs: List<Input>): String { var time = 0 var availableWorkers = 5 val steps = inputs.flatMap { listOf(it.dependency, it.step) }.distinct().toMutableSet() val stepTime = steps.map { Pair(it, it[0].minus('A') + 60 + 1) }.toMap() val dependenciesByStep = inputs .groupBy { it.step } .mapValues { it.value.map { input -> input.dependency }.toMutableSet() } .toMutableMap() val ordering = mutableListOf<String>() val eventQueue = PriorityQueue<Event>() fun removeFromDependencies(step: String) { dependenciesByStep.forEach { (_, dependencies) -> dependencies.remove(step) } } fun handleEventCompletion(event: Event) { time = event.time availableWorkers += 1 removeFromDependencies(event.completedStep) ordering.add(event.completedStep) } fun fillWorkers() { val nextSteps = steps.filter { step -> (step !in dependenciesByStep) || dependenciesByStep[step]!!.isEmpty() } .sorted() val stepsToAssign = nextSteps.take(Math.min(availableWorkers, nextSteps.size)) steps.removeAll(stepsToAssign) val newEvents = stepsToAssign.map { step -> Event(completedStep = step, time = time + stepTime[step]!!) } availableWorkers -= newEvents.size eventQueue.addAll(newEvents) } do { if (eventQueue.isNotEmpty()) { val event = eventQueue.poll() handleEventCompletion(event) } fillWorkers() } while (eventQueue.isNotEmpty()) println(ordering.joinToString("")) return time.toString() } } fun main(args: Array<String>) { val lines = File("./day7-input").readText().split("\n") val inputs = lines.map { Day7_2.parse(it) } println(Day7_2.process(inputs)) }
0
Kotlin
0
0
8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa
2,593
adventofcode
MIT License
2019/08 - Space Image Format/kotlin/src/app.kt
Adriel-M
225,250,242
false
null
import java.io.File import java.nio.file.Path fun main() { val digits = extractDigits("../input") println("===== Part 1 =====") println(runPart1(digits)) println("===== Part 2 =====") println(runPart2(digits)) } fun runPart1(digits: List<Int>): Int { val layers = partitionDigits(digits, 25 * 6) val layerDigitCounts = layers.map { generateCountsForPartition(it) } val layerWithFewestZero = layerDigitCounts.minBy { it[0] ?: -1 } ?: return 0 val onesCount = layerWithFewestZero[1] ?: 0 val twosCount = layerWithFewestZero[2] ?: 2 return onesCount * twosCount } fun runPart2(digits: List<Int>): String { val layers = partitionDigits(digits, 25 * 6) val image = (layers[0].indices).map { getColorForIndex(layers, it) } val imageFormatted = partitionDigits(image, 25) for (layer in imageFormatted) { println(layer) } return image.joinToString(separator="") } fun getColorForIndex(layers: List<List<Int>>, index: Int): Int { for (i in layers.indices) { if (layers[i][index] < 2) { return layers[i][index] } } return 2 } fun extractDigits(path: String): List<Int> { val text = File(path).readText().trimEnd() return text.map { Character.getNumericValue(it) } } fun partitionDigits(digits: List<Int>, separateCount: Int): List<List<Int>> { val partitions: MutableList<MutableList<Int>> = mutableListOf(mutableListOf()) digits.forEach { if (partitions.last().size == separateCount) { partitions.add(mutableListOf()) } partitions.last().add(it) } return partitions } fun generateCountsForPartition(partition: List<Int>): Map<Int, Int> { return partition.groupingBy { it }.eachCount() }
0
Kotlin
0
0
ceb1f27013835f13d99dd44b1cd8d073eade8d67
1,779
advent-of-code
MIT License
kotlin/src/katas/kotlin/eightQueen/EightQueen15.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.eightQueen import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.junit.Test import java.util.* class EightQueen15 { @Test fun `find queen positions on board`() { (0..8).forEach { boardSize -> val solutions = queenPositions(boardSize).toList() val iterativeSolutions = queenPositionsIterative(boardSize).toList() println(solutions) println(iterativeSolutions) println(solutions.size) solutions.zip(iterativeSolutions.toList()).forEach { println(it.first.toPrettyString()) println("=================") assertThat(it.first, equalTo(it.second)) } } } private fun EightQueen15.Solution.toPrettyString(): String { return 0.until(boardSize).map { row -> 0.until(boardSize).map { column -> if (queens.contains(Queen(column, row))) "Q" else "-" }.joinToString("") }.joinToString("\n") } private data class Queen(val column: Int, val row: Int) { override fun toString() = "($column,$row)" } private data class Solution(val boardSize: Int, val queens: List<Queen> = emptyList()) { val complete: Boolean get() = boardSize == queens.size fun nextSteps(): Sequence<Solution> { val column = (queens.map { it.column }.maxOrNull() ?: -1) + 1 return 0.until(boardSize).asSequence() .map { row -> Queen(column, row) } .filter { isValidStep(it) } .map { Solution(boardSize, queens + it) } } private fun isValidStep(queen: Queen): Boolean { return queens.none { it.row == queen.row || it.column == queen.column } && queens.none { Math.abs(it.row - queen.row) == Math.abs(it.column - queen.column) } } } private fun queenPositions(boardSize: Int): Sequence<Solution> { fun queenPositions(solution: Solution): Sequence<Solution> { if (solution.complete) return sequenceOf(solution) else return solution.nextSteps().flatMap(::queenPositions) } return queenPositions(Solution(boardSize)) } private fun queenPositionsIterative(boardSize: Int): Sequence<Solution> { val queue = LinkedList<Solution>() queue.add(Solution(boardSize)) val iterator = object: Iterator<Solution> { override fun hasNext(): Boolean { while (queue.isNotEmpty() && !queue.first.complete) { queue.addAll(0, queue.remove().nextSteps().toList()) } return queue.isNotEmpty() } override fun next() = queue.remove() } return object: Sequence<Solution> { override fun iterator() = iterator } } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,941
katas
The Unlicense
src/main/kotlin/aoc2023/day10/day10Solver.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 94973}
package aoc2023.day10 import lib.* suspend fun main() { setupChallenge().solveChallenge() } fun setupChallenge(): Challenge<Array<Array<Char>>> { return setup { day(10) year(2023) //input("example.txt") parser { it.readLines() .get2DArrayOfColumns() } partOne { val start = it.getCoordinatesOf('S')!! val loop = buildLoop(it, start) (loop.size / 2 + loop.size % 2).toString() } partTwo { val start = it.getCoordinatesOf('S')!! val loop = buildLoop(it, start).toList() val xMax = loop.maxOf { it.x() } val innerPoints = mutableSetOf<Pair<Int, Int>>() val startIndex = loop.indexOfFirst { it.x() == xMax } var direction = loop[startIndex].cardinalDirectionTo(loop[(startIndex + 1) % loop.size]) val inside = relativeDirectionTo(direction, CardinalDirection.West) loop.indices .map { (it + startIndex) % loop.size } .forEach { val current = loop[it] val candidates = mutableSetOf(current.adjacent(direction.turn(inside))) direction = current.cardinalDirectionTo(loop[(it + 1) % loop.size]) candidates.add(current.adjacent(direction.turn(inside))) innerPoints.addAll(candidates.filter { it !in loop }) } val toExpand = innerPoints.toMutableSet() while(toExpand.isNotEmpty()) { val current = toExpand.first() toExpand.remove(current) val candidates = current.getNeighbours(true).filter { it !in loop && it !in innerPoints } candidates.forEach { toExpand.add(it) innerPoints.add(it) } } innerPoints.size.toString() } } } fun Array<Array<Char>>.getCoordinatesOf(c: Char): Pair<Int, Int>? { this.indices.forEach { i -> val column = this[i] column.indices.forEach { j -> if (column[j] == c) { return i to j } } } return null } fun Char.getConnections(): List<CardinalDirection> { return when (this) { '|' -> listOf(CardinalDirection.North, CardinalDirection.South) '-' -> listOf(CardinalDirection.East, CardinalDirection.West) 'L' -> listOf(CardinalDirection.North, CardinalDirection.East) 'J' -> listOf(CardinalDirection.North, CardinalDirection.West) '7' -> listOf(CardinalDirection.South, CardinalDirection.West) 'F' -> listOf(CardinalDirection.South, CardinalDirection.East) else -> listOf() } } fun buildLoop(map: Array<Array<Char>>, start: Pair<Int, Int>): Set<Pair<Int, Int>> { var currentDirection = CardinalDirection.values().first { dir -> val neighbour = start.adjacent(dir) map.isValidCoord(neighbour.x(), neighbour.y()) && map[neighbour.x()][neighbour.y()].getConnections().contains(dir.opposite()) } var current = start.adjacent(currentDirection) val loop = mutableSetOf(start, current) var i = 0 do { currentDirection = map[current.x()][current.y()].getConnections().first { it != currentDirection.opposite() } current = current.adjacent(currentDirection) loop.add(current) i++ } while (current != start) return loop }
0
Kotlin
0
0
a77584ee012d5b1b0d28501ae42d7b10d28bf070
3,532
AoC-2023-DDJ
MIT License
src/main/kotlin/com/ginsberg/advent2023/Day13.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 13 - Point of Incidence * Problem Description: http://adventofcode.com/2023/day/13 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day13/ */ package com.ginsberg.advent2023 import kotlin.math.absoluteValue class Day13(input: List<String>) { private val patterns: List<List<String>> = parseInput(input) fun solvePart1(): Int = patterns.sumOf { findMirror(it, 0) } fun solvePart2(): Int = patterns.sumOf { findMirror(it, 1) } private fun findMirror(pattern: List<String>, goalTotal: Int): Int = findHorizontalMirror(pattern, goalTotal) ?: findVerticalMirror(pattern, goalTotal) ?: throw IllegalStateException("Pattern does not mirror") private fun findHorizontalMirror(pattern: List<String>, goalTotal: Int): Int? = (0 until pattern.lastIndex).firstNotNullOfOrNull { start -> if (createMirrorRanges(start, pattern.lastIndex) .sumOf { (up, down) -> pattern[up] diff pattern[down] } == goalTotal ) (start + 1) * 100 else null } private fun findVerticalMirror(pattern: List<String>, goalTotal: Int): Int? = (0 until pattern.first().lastIndex).firstNotNullOfOrNull { start -> if (createMirrorRanges(start, pattern.first().lastIndex) .sumOf { (left, right) -> pattern.columnToString(left) diff pattern.columnToString(right) } == goalTotal ) start + 1 else null } private infix fun String.diff(other: String): Int = indices.count { this[it] != other[it] } + (length - other.length).absoluteValue private fun createMirrorRanges(start: Int, max: Int): List<Pair<Int, Int>> = (start downTo 0).zip(start + 1..max) private fun List<String>.columnToString(column: Int): String = this.map { it[column] }.joinToString("") private fun parseInput(input: List<String>): List<List<String>> = input.joinToString("\n").split("\n\n").map { it.lines() } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
2,197
advent-2023-kotlin
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2020/Day07.kt
tginsberg
315,060,137
false
null
/* * Copyright (c) 2020 by <NAME> */ /** * Advent of Code 2020, Day 7 - Handy Haversacks * Problem Description: http://adventofcode.com/2020/day/7 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day7/ */ package com.ginsberg.advent2020 class Day07(input: List<String>) { private val relationships: Set<BagRule> = parseInput(input) fun solvePart1(): Int = findParents().size - 1 fun solvePart2(): Int = baggageCost() - 1 private fun findParents(bag: String = "shiny gold"): Set<String> = relationships .filter { it.child == bag } .flatMap { findParents(it.parent) }.toSet() + bag private fun baggageCost(bag: String = "shiny gold"): Int = relationships .filter { it.parent == bag } .sumBy { it.cost * baggageCost(it.child) } + 1 private fun parseInput(input: List<String>): Set<BagRule> = input.filterNot { it.contains("no other") }.flatMap { row -> val parts = row.replace(unusedText, "").split(whitespace) val parent = parts.take(2).joinToString(" ") parts.drop(2).windowed(3, 3, false).map { child -> BagRule( parent, child.first().toInt(), child.drop(1).joinToString(" ") ) } }.toSet() private data class BagRule(val parent: String, val cost: Int, val child: String) companion object { private val unusedText = """bags|bag|contain|,|\.""".toRegex() private val whitespace = """\s+""".toRegex() } }
0
Kotlin
2
38
75766e961f3c18c5e392b4c32bc9a935c3e6862b
1,641
advent-2020-kotlin
Apache License 2.0
src/main/kotlin/pl/jpodeszwik/aoc2023/Day15.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 import java.lang.Integer.parseInt private fun hash(input: String): Int { var current = 0 input.forEach { c -> current += c.code current *= 17 current %= 256 } return current } private fun part1(input: String) { val parts = input.split(",") val result = parts.sumOf { hash(it) } println(result) } data class BoxElement(val key: String, val value: Int) private fun part2(input: String) { val parts = input.split(",") val boxes = HashMap<Int, MutableList<BoxElement>>() for (i in 0..255) { boxes[i] = ArrayList() } parts.forEach { if (it.contains('-')) { val key = it.split("-")[0] val keyHash = hash(key) val boxValues = boxes[keyHash]!! val index = boxValues.indexOfFirst { it.key == key } if (index != -1) { boxValues.removeAt(index) } } else if (it.contains("=")) { val parts2 = it.split("=") val key = parts2[0] val keyHash = hash(key) val value = parseInt(parts2[1]) val boxValues = boxes[keyHash]!! val index = boxValues.indexOfFirst { it.key == key } if (index == -1) { boxValues.add(BoxElement(key, value)) } else { boxValues[index] = BoxElement(key, value) } } } val result = boxes.filter { it.value.isNotEmpty() }.entries .sumOf { box -> box.value.indices.sumOf { (box.key + 1) * (it + 1) * box.value[it].value } } println(result) } fun main() { val input = loadFile("/aoc2023/input15")[0] part1(input) part2(input) }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
1,744
advent-of-code
MIT License
src/Day11.kt
sitamshrijal
574,036,004
false
{"Kotlin": 34366}
fun main() { fun parse(input: List<String>): List<Monkey> = input.chunked(7).map { Monkey.parse(it) } fun part1(input: List<String>): Long { val monkeys = parse(input) val worryDecrease: (Item) -> (Item) = { Item(it.worryLevel / 3) } repeat(20) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val (newItem, throwTo) = monkey.inspectItem(item, worryDecrease) monkeys[throwTo].items += newItem } // Clear items monkey.items.clear() } } val (first, second) = monkeys.map { it.inspectionCount }.sortedDescending().take(2) return first * second } fun part2(input: List<String>): Long { val monkeys = parse(input) val value = monkeys.map { it.test }.reduce(Long::times) val worryDecrease: (Item) -> (Item) = { Item(it.worryLevel % value) } repeat(10_000) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val (newItem, throwTo) = monkey.inspectItem(item, worryDecrease) monkeys[throwTo].receiveItem(newItem) } // Clear items monkey.items.clear() } } val (first, second) = monkeys.map { it.inspectionCount }.sortedDescending().take(2) return first * second } val input = readInput("input11") println(part1(input)) println(part2(input)) } @JvmInline value class Item(val worryLevel: Long) data class Monkey( val items: MutableList<Item>, val operation: (Item) -> Item, val test: Long, val ifTrue: Int, val ifFalse: Int, var inspectionCount: Long = 0L ) { fun inspectItem(item: Item, worryDecrease: (Item) -> Item): Pair<Item, Int> { inspectionCount++ val itemAfterOperation = operation(item) val itemAfterWorryDecrease = worryDecrease(itemAfterOperation) val isDivisible = itemAfterWorryDecrease.worryLevel % test == 0L return itemAfterWorryDecrease to if (isDivisible) ifTrue else ifFalse } fun receiveItem(item: Item) { items += item } companion object { fun parse(input: List<String>): Monkey { val items = mutableListOf<Item>() val worryLevels = input[1].substringAfter("Starting items: ") worryLevels.split(", ").forEach { items += Item(it.toLong()) } val operationText = input[2].substringAfter("Operation: new = old ") val (sign, value) = operationText.split(" ") val isOld = value == "old" val operation: (Item) -> Item = when (sign) { "*" -> { if (isOld) { { Item(it.worryLevel * it.worryLevel) } } else { { Item(it.worryLevel * value.toLong()) } } } "+" -> { { Item(it.worryLevel + value.toLong()) } } else -> error("Not supported") } val test = input[3].substringAfter("Test: divisible by ").toLong() val ifTrue = input[4].substringAfter("If true: throw to monkey ").toInt() val ifFalse = input[5].substringAfter("If false: throw to monkey ").toInt() return Monkey(items, operation, test, ifTrue, ifFalse) } } }
0
Kotlin
0
0
fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d
3,539
advent-of-code-2022
Apache License 2.0
src/day09/Code.kt
ldickmanns
572,675,185
false
{"Kotlin": 48227}
package day09 import readInput import kotlin.math.abs fun main() { val input = readInput("day09/input") // val input = readInput("day09/input_test") // val input = readInput("day09/input_test_2") println(part1(input)) println(part2(input)) } data class Coordinates( val x: Int, val y: Int, ) { operator fun plus(other: Coordinates) = Coordinates( x = this.x + other.x, y = this.y + other.y, ) operator fun minus(other: Coordinates) = Coordinates( x = this.x - other.x, y = this.y - other.y, ) infix fun isNotAdjacentTo( other: Coordinates ) = abs(this.x - other.x) > 1 || abs(this.y - other.y) > 1 infix fun dragTo( other: Coordinates ): Coordinates { val xDelta = when (other.x - this.x) { -2, -1 -> -1 0 -> 0 1, 2 -> 1 else -> error("Further than two apart") } val yDelta = when (other.y - this.y) { -2, -1 -> -1 0 -> 0 1, 2 -> 1 else -> error("Further than two apart") } return this + Coordinates(xDelta, yDelta) } } val UP = Coordinates(0, 1) val RIGHT = Coordinates(1, 0) val DOWN = Coordinates(0, -1) val LEFT = Coordinates(-1, 0) fun part1(input: List<String>): Int { var headPosition = Coordinates(0, 0) var tailPosition = Coordinates(0, 0) val visitedPositionCounter = mutableMapOf(tailPosition to 1) input.forEach { command -> val direction = command.direction val distance = command.substringAfter(' ').toInt() repeat(distance) { headPosition += direction if (headPosition isNotAdjacentTo tailPosition) { tailPosition = updateTail(direction, headPosition) val previousCounter = visitedPositionCounter[tailPosition] ?: 0 visitedPositionCounter[tailPosition] = previousCounter + 1 } } } return visitedPositionCounter.size } private val String.direction: Coordinates get() = when { startsWith("U") -> UP startsWith("R") -> RIGHT startsWith("D") -> DOWN startsWith("L") -> LEFT else -> error("Illegal direction") } private fun updateTail(direction: Coordinates, headPosition: Coordinates) = when (direction) { UP -> headPosition + DOWN RIGHT -> headPosition + LEFT DOWN -> headPosition + UP LEFT -> headPosition + RIGHT else -> error("Illegal direction") } fun part2(input: List<String>): Int { var headPosition = Coordinates(0, 0) val tailPositions = Array(9) { Coordinates(0, 0) } val visitedPositionCounter = mutableMapOf(tailPositions.last() to 1) input.forEach { command -> val direction = command.direction val distance = command.substringAfter(' ').toInt() repeat(distance) { headPosition += direction var previousTilePosition = headPosition for (i in tailPositions.indices) { val currentTilePosition = tailPositions[i] if (currentTilePosition isNotAdjacentTo previousTilePosition) { tailPositions[i] = tailPositions[i] dragTo previousTilePosition previousTilePosition = tailPositions[i] } else return@repeat } val previousCounter = visitedPositionCounter[tailPositions.last()] ?: 0 visitedPositionCounter[tailPositions.last()] = previousCounter + 1 } } return visitedPositionCounter.size }
0
Kotlin
0
0
2654ca36ee6e5442a4235868db8174a2b0ac2523
3,599
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day03.kt
EmRe-One
726,902,443
false
{"Kotlin": 95869, "Python": 18319}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.automation.Day class Day03 : Day(3, 2023, "Gear Ratios") { class Part(val x: Int, val y: Int, val value: Int) { fun getNeighbourFields(engine: Engine): List<Char> { val neighbours = mutableListOf<Char>() /* We want to return all the neighbours of the given Part with the Value NNN. The first digit has the coordinates x, y . . . . . . N N N . . . . . . */ val valueLength = value.toString().length for (dx in -1..valueLength) { val x = this.x + dx for (dy in -1..1) { val y = this.y + dy // ignore the center part if (dy == 0 && dx != -1 && dx != valueLength) { continue } if (y in engine.field.indices) { if (x in engine.field[y].indices) { neighbours.add(engine.field[y][x]) } } } } return neighbours } fun isAdjacentTo(x: Int, y: Int): Boolean { val valueLength = value.toString().length return x in (this.x - 1)..(this.x + valueLength) && y in (this.y - 1)..(this.y + 1) } } class Engine(val field: List<CharArray>) { companion object { fun parse(input: List<String>): Engine { val field = input.map { line -> line.toCharArray() } return Engine(field) } } val parts = mutableListOf<Part>() init { for (y in this.field.indices) { var startX = 0 while (startX < this.field[y].size) { val currentChar = this.field[y][startX] if (currentChar.isDigit()) { var endX = startX + 1 while (endX in this.field[y].indices && this.field[y][endX].isDigit()) { endX++ } val value = this.field[y].joinToString("") .substring(startX until endX).toInt() this.parts.add(Part(startX, y, value)) startX = endX } else { startX++ } } } } } override fun part1(): Int { val engine = Engine.parse(inputAsList) val filteredParts = engine.parts.filter { part -> part.getNeighbourFields(engine).any { !it.isDigit() && it != '.' } } return filteredParts.sumOf { it.value } } override fun part2(): Long { val engine = Engine.parse(inputAsList) var sum = 0L engine.field.forEachIndexed { y, line -> line.forEachIndexed { x, field -> if (field == '*') { val subParts = engine.parts.filter { it.isAdjacentTo(x, y) } if (subParts.size == 2) { sum += subParts[0].value * subParts[1].value } } } } return sum } }
0
Kotlin
0
0
c75d17635baffea50b6401dc653cc24f5c594a2b
3,473
advent-of-code-2023
Apache License 2.0
src/day14/Day14.kt
MaxBeauchemin
573,094,480
false
{"Kotlin": 60619}
package day14 import readInput import java.time.Instant data class Coordinates( val x: Int, val y: Int ) { fun plus(xChange: Int, yChange: Int) = Coordinates(x + xChange, y + yChange) fun below() = plus(0, 1) fun belowLeft() = plus(-1, 1) fun belowRight() = plus(1, 1) companion object { fun fromString(input: String): Coordinates { return input.split(",").let { pair -> Coordinates(pair[0].toInt(), pair[1].toInt()) } } } } data class Sand( var location: Coordinates, var isSettled: Boolean = false ) { fun fall(occupied: Set<Coordinates>, infiniteFloorY: Int? = null) { val newCoordinates = if (!occupied.contains(this.location.below()) && (infiniteFloorY == null || this.location.below().y < infiniteFloorY)) { this.location.below() } else if (!occupied.contains(this.location.belowLeft()) && (infiniteFloorY == null || this.location.belowLeft().y < infiniteFloorY)) { this.location.belowLeft() } else if (!occupied.contains(this.location.belowRight()) && (infiniteFloorY == null || this.location.belowRight().y < infiniteFloorY)) { this.location.belowRight() } else null if (newCoordinates != null) { this.location = newCoordinates } else { this.isSettled = true } } } data class Block( val location: Coordinates ) fun parseBlocks(input: List<String>): Set<Block> { var blocks = mutableSetOf<Block>() input.forEach { line -> line.split(" -> ").windowed(2) { pair -> val start = Coordinates.fromString(pair[0]) val end = Coordinates.fromString(pair[1]) if (start == end) blocks.add(Block(start)) else { // move y direction if (start.x == end.x) { val yDelta = if (start.y < end.y) 1 else -1 var currCoords = start while (currCoords != end) { blocks.add(Block(currCoords)) currCoords = currCoords.plus(0, yDelta) } blocks.add(Block(end)) } else if (start.y == end.y) { val xDelta = if (start.x < end.x) 1 else -1 var currCoords = start while (currCoords != end) { blocks.add(Block(currCoords)) currCoords = currCoords.plus(xDelta, 0) } blocks.add(Block(end)) } else { throw Exception("Diagonals Invalid") } } } } return blocks } fun main() { fun part1(input: List<String>): Int { val blocks = parseBlocks(input) val allSand = mutableSetOf<Sand>() val lowestBlockY = blocks.maxOf { it.location.y } while (true) { val currSand = Sand(Coordinates(500, 0)) val settledSand = allSand.toSet() allSand.add(currSand) while (!currSand.isSettled) { currSand.fall(blocks.map { it.location }.plus(settledSand.map { it.location }).toSet()) if (currSand.location.y > lowestBlockY) return settledSand.size } } } fun part2(input: List<String>): Int { val blocks = parseBlocks(input) val allSand = mutableSetOf<Sand>() val lowestBlockY = blocks.maxOf { it.location.y } val infiniteFloorY = lowestBlockY + 2 while (true) { val currSand = Sand(Coordinates(500, 0)) val settledSand = allSand.toSet() allSand.add(currSand) while (!currSand.isSettled) { if (settledSand.contains(Sand(Coordinates(500, 0), true))) return settledSand.size currSand.fall(blocks.map { it.location }.plus(settledSand.map { it.location }).toSet(), infiniteFloorY) } } } val testInput = readInput("Day14_test") val input = readInput("Day14") println("Part 1 [Test] : ${part1(testInput)}") check(part1(testInput) == 24) println("Part 1 [Real] : ${part1(input)}") println("Part 2 [Test] : ${part2(testInput)}") check(part2(testInput) == 93) println("Part 2 [Real] : ${part2(input)}") }
0
Kotlin
0
0
38018d252183bd6b64095a8c9f2920e900863a79
4,401
advent-of-code-2022
Apache License 2.0
src/Day02.kt
bin-wang
573,219,628
false
{"Kotlin": 4145}
fun main() { fun occurrenceRule(minOccurrences: Int, maxOccurrences: Int, c: Char, password: String) = password.count { it == c } in minOccurrences..maxOccurrences fun positionRule(leftIndex: Int, rightIndex: Int, c: Char, password: String) = (password[leftIndex - 1] == c) xor (password[rightIndex - 1] == c) fun checkPassword(rawInput: String, rule: (Int, Int, Char, String) -> Boolean): Boolean { val regex = Regex("(\\d+)-(\\d+) (\\w): (\\w+)") val match = regex.find(rawInput)!! val (a, b, c, password) = match.destructured return rule( a.toInt(), b.toInt(), c.first(), password ) } fun part1(input: List<String>): Int { return input.map { checkPassword(it, ::occurrenceRule) }.count { it } } fun part2(input: List<String>): Int { return input.map { checkPassword(it, ::positionRule) }.count { it } } val testInput = readInput("Day02_test") check(part1(testInput) == 2) check(part2(testInput) == 1) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
929f812efb37d5aea34e741510481ca3fab0c3da
1,164
aoc20-kt
Apache License 2.0
src/year2022/13/Day13.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2022.`13` import java.util.Stack import readInput sealed class Packet : Comparable<Packet> { override fun compareTo(other: Packet): Int { return when (compare(this, other)) { true -> -1 false -> 1 null -> 0 } } data class Number(val value: Int) : Packet() { override fun toString(): String { return "$value" } } data class PacketList(val list: List<Packet>) : Packet() { override fun toString(): String { return list.joinToString(",", "[", "]") } } private fun compare(left: Packet, right: Packet): Boolean? { return when (left) { is PacketList -> { when (right) { is PacketList -> compareLists(left, right) is Number -> compareLists(left, PacketList(listOf(right))) } } is Number -> { when (right) { is PacketList -> compareLists(PacketList(listOf(left)), right) is Number -> compareInts(left, right) } } } } private fun compareLists(left: PacketList, right: PacketList): Boolean? { val leftIterator = left.list.iterator() val rightIterator = right.list.iterator() while (leftIterator.hasNext() && rightIterator.hasNext()) { val leftItem = leftIterator.next() val rightItem = rightIterator.next() val compareResult = compare(leftItem, rightItem) compareResult?.let { return it } } if (leftIterator.hasNext()) return false if (rightIterator.hasNext()) return true return null } private fun compareInts(left: Number, right: Number): Boolean? { return when { left.value < right.value -> true left.value > right.value -> false left.value == right.value -> null else -> error("!!") } } } fun parseInput(string: String): Packet.PacketList { val resList = mutableListOf<Packet>() val parentStacks = Stack<MutableList<Packet>>() var currentList = resList var inputNumberString = "" string.forEachIndexed { _, character -> when { character == '[' -> { val list = mutableListOf<Packet>() currentList.add(Packet.PacketList(list)) parentStacks.push(currentList) currentList = list } character == ']' -> { if (inputNumberString.isEmpty()) { if (currentList.isNotEmpty()) { currentList = parentStacks.pop() } } else { currentList.add(Packet.Number(inputNumberString.toInt())) } inputNumberString = "" } character == ',' -> { if (inputNumberString.isEmpty()) { currentList = parentStacks.pop() } else { currentList.add(Packet.Number(inputNumberString.toInt())) } inputNumberString = "" } character.isDigit() -> { inputNumberString += character } } } return Packet.PacketList((resList.first() as Packet.PacketList).list) } fun main() { fun part1(input: List<String>): Int { val result = input .asSequence() .windowed(2, 3) .map { (leftString, rightString) -> parseInput(leftString) to parseInput(rightString) } .mapIndexed { index, (left, right) -> (index + 1) to (left < right) } .filter { (_, isCorrect) -> isCorrect ?: false } .sumOf { it.first } return result } fun part2(input: List<String>): Int { val first = parseInput("[[2]]") val second = parseInput("[[6]]") val result = input.windowed(2, 3) .flatten() .map { parseInput(it) } .let { it + listOf(first, second) } .sorted() val i = result.indexOf(first) + 1 val j = result.indexOf(second) + 1 return i * j } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 13) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
4,586
KotlinAdventOfCode
Apache License 2.0
src/Day01.kt
handrodev
577,884,162
false
{"Kotlin": 7670}
fun main() { fun part1(input: List<String>): Int { // Keep track of maximum calories carried by any elf var maxCalories = 0 // Keep track of calories carried by current elf var calories = 0 for (line in input) { if (line.isBlank()) { // Empty line means another elf if (calories > maxCalories) // Current elf is carrying more calories than anyone else // Update maximum maxCalories = calories // Reset calories counter calories = 0 } else { // Still the same elf, keep counting calories carried calories += line.toInt() } } return maxCalories } fun part2(input: List<String>): Int { // Keep track of calories for each elf val calories = arrayListOf<Int>(0) for (line in input) { if (line.isBlank()) { // Blank line -> add a new calories counter to the list (new elf) calories.add(0) } else { // Not a blank line -> accumulate calories for current elf (last one added) calories[calories.lastIndex] += line.toInt() } } // Sort list of elves (ascending), take the last three and return their sum of calories return calories.sorted().takeLast(3).sum() } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01") // check(part1(testInput) == 1) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
d95aeb85b4baf46821981bb0ebbcdf959c506b44
1,711
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Day8.kt
amitdev
574,336,754
false
{"Kotlin": 21489}
import java.io.File import java.lang.Integer.max fun main() { val result = File("inputs/day_8.txt").useLines { findScenicScore(it) } println(result) } fun findVisible(lines: Sequence<String>) = Grid(lines.map { line -> line.map { it.digitToInt()} }.toList()) .toVisbile() fun findScenicScore(lines: Sequence<String>) = Grid(lines.map { line -> line.map { it.digitToInt()} }.toList()) .score() data class Grid(val data: List<List<Int>>) { fun toVisbile() = data.indices.flatMap { x -> (0 until data[0].size).filter { y -> left(x, y) || right(x, y) || top(x, y) || down(x, y) } }.count() fun score() = data.indices.flatMap { x -> (0 until data[0].size).map { y -> leftScore(x, y) * rightScore(x, y) * topScore(x, y) * downScore(x, y) } }.max() private fun leftScore(x: Int, y: Int) = y - max(data[x].subList(0, y).indexOfLast { it >= data[x][y] }, 0) private fun rightScore(x: Int, y: Int) = data[x].subList(y+1, data[x].size) .indexOfFirst { it >= data[x][y] } .let { if (it == -1) data[x].size-1-y else it + 1 } private fun topScore(x: Int, y: Int) = x - max((0 until x).indexOfLast { data[x][y] <= data[it][y] }, 0) private fun downScore(x: Int, y: Int) = (x+1 until data.size) .indexOfFirst { data[x][y] <= data[it][y] } .let { if (it == -1) data.size-1-x else it + 1 } private fun left(x: Int, y: Int) = data[x].subList(0, y).maxOrZero() < data[x][y] private fun right(x: Int, y: Int) = data[x].subList(y+1, data[x].size).maxOrZero() < data[x][y] private fun top(x: Int, y: Int) = (0 until x).map { data[it][y] }.maxOrZero() < data[x][y] private fun down(x: Int, y: Int) = (x+1 until data.size).map { data[it][y] }.maxOrZero() < data[x][y] fun List<Int>.maxOrZero() = if (this.isEmpty()) -1 else this.max() }
0
Kotlin
0
0
b2cb4ecac94fdbf8f71547465b2d6543710adbb9
1,805
advent_2022
MIT License
src/main/kotlin/y2022/day05/Day05.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2022.day05 fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } data class Instruction ( val numberOfCrates: Int, val from: Int, val to: Int ) fun input(): Pair<Map<Int, ArrayDeque<Char>>, List<Instruction>> { val allTheLines = AoCGenerics.getInputLines("/y2022/day05/input.txt") val stacks: Map<Int, ArrayDeque<Char>> = mutableMapOf( 1 to ArrayDeque(), 2 to ArrayDeque(), 3 to ArrayDeque(), 4 to ArrayDeque(), 5 to ArrayDeque(), 6 to ArrayDeque(), 7 to ArrayDeque(), 8 to ArrayDeque(), 9 to ArrayDeque() ) allTheLines.subList(0,8).forEach { line -> val lineElements = line.chunked(4) lineElements.forEachIndexed { index, content -> if (content.startsWith("[")) { stacks[index+1]!!.addFirst(content[1]) } } } val instructions = allTheLines.subList(10, allTheLines.size).map {line -> val lineParts = line.split(" ") Instruction( numberOfCrates = lineParts[1].toInt(), from = lineParts[3].toInt(), to = lineParts[5].toInt(), ) } return Pair(stacks, instructions) } fun part1(): String { val input = input() val stacks = input.first val instructions = input.second instructions.forEach { instruction -> repeat(instruction.numberOfCrates) { val removedElement = stacks[instruction.from]!!.last() stacks[instruction.from]!!.removeLast() stacks[instruction.to]!!.addLast(removedElement) } } return stacks.map { entry -> entry.value.last() }.joinToString("") } fun part2(): String { val input = input() val stacks = input.first val instructions = input.second instructions.forEach { instruction -> val removedElements: MutableList<Char> = mutableListOf() repeat(instruction.numberOfCrates) { removedElements.add(stacks[instruction.from]!!.last()) stacks[instruction.from]!!.removeLast() } removedElements.reversed().forEach {element -> stacks[instruction.to]!!.addLast(element) } } return stacks.map { entry -> entry.value.last() }.joinToString("") }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
2,376
AdventOfCode
MIT License
src/main/kotlin/_0079_WordSearch.kt
ryandyoon
664,493,186
false
null
// https://leetcode.com/problems/word-search fun exist(board: Array<CharArray>, word: String): Boolean { val visited = Array(board.size) { BooleanArray(board.first().size) } for (row in board.indices) { for (col in board.first().indices) { if (dfs(row = row, col = col, index = 0, word = word, board = board, visited = visited)) { return true } } } return false } fun dfs( row: Int, col: Int, index: Int, word: String, board: Array<CharArray>, visited: Array<BooleanArray> ): Boolean { if (visited[row][col] || board[row][col] != word[index]) return false if (index == word.lastIndex) return true visited[row][col] = true if (board.valid(row - 1, col) && dfs(row - 1, col, index + 1, word, board, visited)) return true if (board.valid(row + 1, col) && dfs(row + 1, col, index + 1, word, board, visited)) return true if (board.valid(row, col - 1) && dfs(row, col - 1, index + 1, word, board, visited)) return true if (board.valid(row, col + 1) && dfs(row, col + 1, index + 1, word, board, visited)) return true visited[row][col] = false return false } private fun Array<CharArray>.valid(row: Int, col: Int): Boolean { return row >= 0 && row <= this.lastIndex && col >= 0 && col <= this.first().lastIndex }
0
Kotlin
0
0
7f75078ddeb22983b2521d8ac80f5973f58fd123
1,343
leetcode-kotlin
MIT License
src/Day01.kt
andrikeev
574,393,673
false
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
fun main() { fun part1(input: List<String>): Int { var maxCals = 0 var curCal = 0 input.forEachIndexed { index, line -> if (line.isNotBlank()) { curCal += line.toInt() } if (line.isBlank() || index == line.lastIndex) { if (curCal > maxCals) { maxCals = curCal } curCal = 0 } } return maxCals } fun part2(input: List<String>): Int { val topList = intArrayOf(0, 0, 0) var curCal = 0 input.forEachIndexed { index, line -> if (line.isNotBlank()) { curCal += line.toInt() } if (line.isBlank() || index == input.lastIndex) { when { curCal > topList[2] -> { topList[0] = topList[1] topList[1] = topList[2] topList[2] = curCal } curCal > topList[1] -> { topList[0] = topList[1] topList[1] = curCal } curCal > topList[0] -> { topList[0] = curCal } } curCal = 0 } } return topList.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
1aedc6c61407a28e0abcad86e2fdfe0b41add139
1,666
aoc-2022
Apache License 2.0
src/day20/Day20.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day20 import readInput import readTestInput data class DataBuffer( val originalIndex: Int, val value: Long, ) private fun List<String>.parseDataBuffers(): List<DataBuffer> = mapIndexed { index, line -> DataBuffer(value = line.toLong(), originalIndex = index) } private fun List<DataBuffer>.mixed(): List<DataBuffer> { val dataBuffers = this val modulus = dataBuffers.lastIndex val mixedDataBuffers = dataBuffers.toMutableList() for (index in dataBuffers.indices) { val actualIndex = mixedDataBuffers.indexOfFirst { it.originalIndex == index } val item = mixedDataBuffers.removeAt(actualIndex) val targetIndex = (actualIndex + item.value).mod(modulus) mixedDataBuffers.add(targetIndex, item) } return mixedDataBuffers } private fun List<DataBuffer>.calculateCoordinates(): Long { val dataBuffers = this val startIndex = dataBuffers.indexOfFirst { it.value == 0L } return listOf(1_000, 2_000, 3_000) .sumOf { offset -> val targetIndex = (startIndex + offset).mod(dataBuffers.size) dataBuffers[targetIndex].value } } private fun DataBuffer.decryptWith(decryptionKey: Int): DataBuffer = DataBuffer(originalIndex, value * decryptionKey) private fun List<DataBuffer>.decryptWith(decryptionKey: Int): List<DataBuffer> = this.map { it.decryptWith(decryptionKey) } private fun part1(input: List<String>): Long { val dataBuffers = input.parseDataBuffers() val mixedBuffers = dataBuffers.mixed() return mixedBuffers.calculateCoordinates() } private fun part2(input: List<String>): Long { val encryptedNumbers = input.parseDataBuffers() val decryptedNumbers = encryptedNumbers.decryptWith(decryptionKey = 811589153) var mixedNumbers = decryptedNumbers repeat(10) { mixedNumbers = mixedNumbers.mixed() } return mixedNumbers.calculateCoordinates() } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day20") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
2,234
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
ZiomaleQ
573,349,910
false
{"Kotlin": 49609}
fun main() { fun part1(input: List<String>): Int { var sum = 0 for (line in input) { val splitIndex = line.length / 2 val firstSection = line.substring(0, splitIndex) val secondSection = line.substring(splitIndex) val dupes = firstSection.filter { secondSection.contains(it) }.toSet() val score = dupes.map { if (it.isLowerCase()) it.code - 96 else it.code - 38 }.sum() sum += score } return sum } // println(('A'..'Z').map{it.code - 38}) // println(('a'..'z').map{it.code - 96}) fun part2(input: List<String>): Int { var sum = 0 val list = mutableListOf<String>() for (line in input) { list.add(line) if (list.size == 3) { val dupes = list[0].filter { list[1].contains(it) && list[2].contains(it) }.toSet() sum += dupes.sumOf { if (it.isLowerCase()) it.code - 96 else it.code - 38 }.also { list.clear() } } } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b8811a6a9c03e80224e4655013879ac8a90e69b5
1,319
aoc-2022
Apache License 2.0
src/com/ncorti/aoc2023/Day22.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 typealias CharCube = Array<Array<Array<Char>>> data class Brick( val name: Char, val start: Triple<Int, Int, Int>, val end: Triple<Int, Int, Int>, var position: MutableList<Triple<Int, Int, Int>> = mutableListOf() ) { fun getBricksAbove(world: CharCube, bricks: List<Brick>): MutableList<Brick> { val result = mutableSetOf<Brick>() position.forEach { (z, x, y) -> if (z < world.size - 1 && world[z + 1][x][y] != name && world[z + 1][x][y] != '.') { result.add(bricks.first { brick -> brick.position.contains(Triple(z + 1, x, y)) }) } } return result.toMutableList() } } fun main() { fun parseInput(): Pair<CharCube, List<Brick>> { var name = ('a'.code - 1).toChar() val bricks = getInputAsText("22") { split("\n").filter(String::isNotBlank).map { val points = it.split('~', ',') name = (name.code + 1).toChar() Brick( name, Triple(points[0].toInt(), points[1].toInt(), points[2].toInt()), Triple(points[3].toInt(), points[4].toInt(), points[5].toInt()) ) } } val max = bricks.maxOf { listOf(it.start.first, it.start.second, it.start.third, it.end.first, it.end.second, it.end.third).max() } val world = Array(max + 1) { Array(max + 1) { Array(max + 1) { '.' } } } bricks.forEach { for (x in it.start.first..it.end.first) { for (y in it.start.second..it.end.second) { for (z in it.start.third..it.end.third) { world[z][x][y] = it.name it.position.add(Triple(z, x, y)) } } } } return world to bricks } fun letBrickFall(world: CharCube, bricks: List<Brick>) { val brickToFall = mutableListOf<Brick>() while (true) { brickToFall.clear() bricks.forEach { if (it.position.all { (z, x, y) -> z > 0 && (world[z - 1][x][y] == '.' || world[z - 1][x][y] == it.name) }) { brickToFall.add(it) } } if (brickToFall.isEmpty()) { break } else { brickToFall.forEach { it.position.forEach { (z, x, y) -> world[z][x][y] = '.' world[z - 1][x][y] = it.name } it.position = it.position.map { (z, x, y) -> Triple(z - 1, x, y) }.toMutableList() } } } } fun computeSustainingBricks(world: CharCube, bricks: List<Brick>) = bricks.count { candidate -> val bricksAbove = candidate.getBricksAbove(world, bricks) candidate.position.forEach { (z, x, y) -> if (z < world.size - 1 && world[z + 1][x][y] != candidate.name && world[z + 1][x][y] != '.') { bricksAbove.add(bricks.first { brick -> brick.position.contains(Triple(z + 1, x, y)) }) } } bricksAbove.none { brick -> brick.position.all { (z, x, y) -> z == 0 || (world[z - 1][x][y] == '.' || world[z - 1][x][y] == candidate.name || world[z - 1][x][y] == brick.name) } } } fun computeChainReaction(world: CharCube, bricks: List<Brick>, beginning: Brick): Int { val wouldFall = mutableListOf(beginning) var count = 0 val fallingBricksName = mutableSetOf<Char>() while (wouldFall.isNotEmpty()) { val next = wouldFall.removeAt(0) fallingBricksName.add(next.name) var bricksAbove = next.getBricksAbove(world, bricks) bricksAbove = bricksAbove.distinct().toMutableList().filter { brick -> brick.position.all { (z, x, y) -> z == 0 || (world[z - 1][x][y] == '.' || world[z - 1][x][y] == next.name || world[z - 1][x][y] == brick.name || world[z - 1][x][y] in fallingBricksName) } }.toMutableList() bricksAbove.distinct().forEach { if (it !in wouldFall) { wouldFall.add(it) fallingBricksName.add(it.name) count++ } } } return count } fun part1(): Int = parseInput().let { (world, bricks) -> letBrickFall(world, bricks) computeSustainingBricks(world, bricks) } fun part2(): Int = parseInput().let { (world, bricks) -> letBrickFall(world, bricks) bricks.sumOf { computeChainReaction(world, bricks, it) } } println(part1()) println(part2()) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
4,869
adventofcode-2023
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestStringChain.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1048. Longest String Chain * @see <a href="https://leetcode.com/problems/longest-string-chain/">Source</a> */ fun interface LongestStringChain { operator fun invoke(words: Array<String>): Int } /** * Approach 1: Top-Down Dynamic Programming (Recursion + Memoization) * Time complexity: O(L2⋅N) * Space complexity: O(N). */ class LSCTopDown : LongestStringChain { override operator fun invoke(words: Array<String>): Int { val memo: MutableMap<String, Int> = HashMap() val wordsPresent: MutableSet<String> = HashSet() wordsPresent.addAll(words) var ans = 0 for (word in words) { ans = max(ans, dfs(wordsPresent, memo, word)) } return ans } private fun dfs(words: Set<String>, memo: MutableMap<String, Int>, currentWord: String): Int { // If the word is encountered previously we just return its value present in the map (memoization). if (memo.containsKey(currentWord)) { return memo[currentWord]!! } // This stores the maximum length of word sequence possible with the 'currentWord' as the var maxLength = 1 val sb = StringBuilder(currentWord) // creating all possible strings taking out one character at a time from the `currentWord` for (i in currentWord.indices) { sb.deleteCharAt(i) val newWord = sb.toString() // If the new word formed is present in the list, we do a dfs search with this newWord. if (words.contains(newWord)) { val currentLength = 1 + dfs(words, memo, newWord) maxLength = max(maxLength, currentLength) } sb.insert(i, currentWord[i]) } memo[currentWord] = maxLength return maxLength } } /** * Approach 2: Bottom-Up Dynamic Programming * Time complexity: O(N⋅(logN+L2)). * Space complexity: O(N). */ class LSCBottomUp : LongestStringChain { override operator fun invoke(words: Array<String>): Int { val dp: MutableMap<String, Int> = HashMap() // Sorting the list in terms of the word length. words.sortWith { a, b -> a.length - b.length } var longestWordSequenceLength = 1 for (word in words) { var presentLength = 1 // Find all possible predecessors for the current word by removing one letter at a time. for (i in word.indices) { val temp = StringBuilder(word) temp.deleteCharAt(i) val predecessor = temp.toString() val previousLength = dp.getOrDefault(predecessor, 0) presentLength = max(presentLength, previousLength + 1) } dp[word] = presentLength longestWordSequenceLength = max(longestWordSequenceLength, presentLength) } return longestWordSequenceLength } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,589
kotlab
Apache License 2.0
src/Day05.kt
askeron
572,955,924
false
{"Kotlin": 24616}
class Day05 : Day<String>("CMZ", "MCD", "CNSZFDVLJ", "QNDWLMGNS") { class State(initialCols: List<List<Char>>) { private val cols = initialCols.map { it.toMutableList() } fun movePart1(move: Move) { repeat(move.count) { cols[move.to - 1] += cols[move.from - 1].removeLast() } } fun movePart2(move: Move) { cols[move.to - 1] += cols[move.from - 1].removeLast(move.count) } fun getTopCrates() = cols.map { it.last() } override fun toString() = (0 until cols.maxOf { it.size }).reversed().joinToString("\n") { i -> cols.joinToString(" ") { col -> col.getOrNull(i)?.let { "[$it]" } ?: " " } } + "\n" + cols.mapIndexed { index, _ -> " $index " }.joinToString(" ") } data class Move(val count: Int, val from: Int, val to: Int) private fun parseInput(input: List<String>): Pair<State, List<Move>> { val rows = input.takeWhile { it.isNotEmpty() }.dropLast(1).map { it.chunked(4).map { it.elementAt(1) } } val cols = rows.turnMatrix().map { it.filter { it != ' ' }.reversed() } val moves = input.takeLastWhile { it.isNotEmpty() }.map { it.split(' ') } .map { Move(it[1].toInt(), it[3].toInt(), it[5].toInt()) } return State(cols) to moves } private fun partCommon(input: List<String>, moveFunction: (State, Move) -> Unit): String { val (state, moves) = parseInput(input) //println(state) moves.forEach { moveFunction.invoke(state, it) //println(state) } return state.getTopCrates().joinToString("") } override fun part1(input: List<String>): String { return partCommon(input, State::movePart1) } override fun part2(input: List<String>): String { return partCommon(input, State::movePart2) } }
0
Kotlin
0
1
6c7cf9cf12404b8451745c1e5b2f1827264dc3b8
1,860
advent-of-code-kotlin-2022
Apache License 2.0
src/Day08.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
class MathVector(val x: Int, val y: Int) { operator fun plus(other: MathVector): MathVector { return MathVector(x + other.x, y + other.y) } } val DIRECTION_OF_VIEW = listOf(MathVector(0, 1), MathVector(1, 0), MathVector(0, -1), MathVector(-1, 0)) @Suppress("BooleanMethodIsAlwaysInverted") fun isWithinBorders(position: MathVector, borders: MathVector): Boolean { return position.x >= 0 && position.y >= 0 && position.x < borders.x && position.y < borders.y } fun part1(input: List<String>, borders: MathVector): Int { val marks = MutableList(input.size) { _ -> MutableList(input[0].length) { _ -> 0 } } val startPosition = listOf(MathVector(0, 0), MathVector(0, 0), MathVector(0, borders.y - 1), MathVector(borders.x - 1, 0)) val directionOfStartPositionChange = listOf(MathVector(1, 0), MathVector(0, 1), MathVector(1, 0), MathVector(0, 1)) for (i in 0 until 4) { var currentStartPosition = startPosition[i] while (isWithinBorders(currentStartPosition, borders)) { var position = currentStartPosition var maxHeight = -1 while (isWithinBorders(position, borders)) { if (input[position.x][position.y].digitToInt() > maxHeight) { marks[position.x][position.y] = 1 maxHeight = input[position.x][position.y].digitToInt() } position += DIRECTION_OF_VIEW[i] } currentStartPosition += directionOfStartPositionChange[i] } // println(marks.joinToString("\n")) // println("====") // marks = MutableList(input.size) { _ -> MutableList(input[0].length) { _ -> 0 } } } return marks.sumOf { x -> x.sum() } } fun part2(input: List<String>, borders: MathVector): Int { var ans = 0 for (x in 0 until borders.x) { for (y in 0 until borders.y) { var currentTotal = 1 for (direction in DIRECTION_OF_VIEW) { var currentVisibleTrees = 0 var currentPosition = MathVector(x, y) + direction while (isWithinBorders(currentPosition, borders)) { currentVisibleTrees += 1 if (input[currentPosition.x][currentPosition.y].digitToInt() >= input[x][y].digitToInt()) { break } currentPosition += direction } currentTotal *= currentVisibleTrees } if (currentTotal > ans) { ans = currentTotal } // print(currentTotal) } // println() } return ans } fun main() { val input = readInput("Day08") val borders = MathVector(input.size, input[0].length) println("Day 08") println(part1(input, borders)) println(part2(input, borders)) }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
2,878
aoc-2022
Apache License 2.0
src/Day18.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
import java.math.BigInteger import kotlin.math.abs import kotlin.math.max import kotlin.math.min data class Cube(val x: Int, val y: Int, val z: Int, val size: Int) fun main() { fun isNeighbor(cube1: Cube, cube2: Cube): Boolean { // Check if the cubes are adjacent in the x, y, or z direction return (abs(cube1.x - cube2.x) == 1 && cube1.y == cube2.y && cube1.z == cube2.z) || (abs(cube1.y - cube2.y) == 1 && cube1.x == cube2.x && cube1.z == cube2.z) || (abs(cube1.z - cube2.z) == 1 && cube1.x == cube2.x && cube1.y == cube2.y) } fun calculateSurfaceArea(cube: Cube, neighbor: Cube, exposedSides: Int): Int { var out = exposedSides if (neighbor.x == cube.x + 1) { out-- } if (neighbor.x == cube.x - 1) { out-- } // Check the top and bottom sides of the given cube if (neighbor.y == cube.y + 1) { out-- } if (neighbor.y == cube.y - 1) { out-- } // Check the left and right sides of the given cube if (neighbor.z == cube.z + 1) { out-- } if (neighbor.z == cube.z - 1) { out-- } return out } fun part1(input: List<String>): Int { val cubes = input.map { val (x, y, z) = it.split(",").map { it.toInt() } Cube(x, y, z, 1) }.toSet() return cubes.map { it.let { c -> cubes.filter { cube -> c != cube && isNeighbor(c, cube) } } .fold(6) { acc, neighbour -> calculateSurfaceArea(neighbour, it, acc) } }.sum() } fun generateGrid(cubes: Set<Cube>): List<List<List<Cube>>> { // Find the minimum and maximum x, y, and z coordinates of the cubes val minX = cubes.minBy { it.x }.x val maxX = cubes.maxBy { it.x }.x val minY = cubes.minBy { it.y }.y val maxY = cubes.maxBy { it.y }.y val minZ = cubes.minBy { it.z }.z val maxZ = cubes.maxBy { it.z }.z // Initialize the grid with empty cubes val grid = mutableListOf<MutableList<MutableList<Cube>>>() for (i in minX..maxX) { val row = mutableListOf<MutableList<Cube>>() for (j in minY..maxY) { val column = mutableListOf<Cube>() for (k in minZ..maxZ) { column.add(Cube(i, j, k, 0)) } row.add(column) } grid.add(row) } // Add the cubes from the list to the grid for (cube in cubes) { grid[cube.x - minX][cube.y - minY][cube.z - minZ] = cube } return grid } fun findTrappedEmptyCubes(grid: List<List<List<Cube>>>): List<Cube> { // Initialize a list to store the empty cubes val trappedCubes = mutableListOf<Cube>() // Iterate over the rows in the grid for (i in grid.indices) { // Iterate over the columns in the current row for (j in grid[i].indices) { // Iterate over the cubes in the current column for (k in grid[i][j].indices) { // Get the current cube val cube = grid[i][j][k] // Check if the current cube is empty if (cube.size == 0) { // Check if the current cube is completely surrounded by cubes with a size greater than 0 val isTrapped = (i == 0 || i == grid.size - 1 || grid[i - 1][j][k].size > 0 || grid[i + 1][j][k].size > 0) && (j == 0 || j == grid[i].size - 1 || grid[i][j - 1][k].size > 0 || grid[i][j + 1][k].size > 0) && (k == 0 || k == grid[i][j].size - 1 || grid[i][j][k - 1].size > 0 || grid[i][j][k + 1].size > 0) if (isTrapped) { trappedCubes.add(cube) } } } } } return trappedCubes } fun findTrappedCubes(cubes: Set<Cube>): List<Cube> { // Find the minimum and maximum x, y, and z coordinates of the cubes val minX = cubes.minBy { it.x }!!.x val maxX = cubes.maxBy { it.x }!!.x val minY = cubes.minBy { it.y }!!.y val maxY = cubes.maxBy { it.y }!!.y val minZ = cubes.minBy { it.z }!!.z val maxZ = cubes.maxBy { it.z }!!.z // Initialize a list to store the missing cubes val trappedCubes = mutableListOf<Cube>() // Iterate over the range of x, y, and z coordinates for (x in minX..maxX) { for (y in minY..maxY) { for (z in minZ..maxZ) { // Check if the current coordinates are not present in the list of cubes if (cubes.none { it.x == x && it.y == y && it.z == z }) { // Check if the missing cube is completely surrounded by cubes with a size greater than 0 val isSurrounded = (x == minX || x == maxX || cubes.any { it.x == x - 1 || it.x == x + 1 }) && (y == minY || y == maxY || cubes.any { it.y == y - 1 || it.y == y + 1 }) && (z == minZ || z == maxZ || cubes.any { it.z == z - 1 || it.z == z + 1 }) if (isSurrounded) { // Check if the missing cube is not immediately adjacent to any other missing cubes val isTrapped = !trappedCubes.any { it.x in x-1..x+1 && it.y in y-1..y+1 && it.z in z-1..z+1 } if (isTrapped) { // Add the missing cube to the list trappedCubes.add(Cube(x, y, z, 0)) } } } } } } return trappedCubes } fun part2(input: List<String>): Int { val cubes = input.map { val (x, y, z) = it.split(",").map { it.toInt() } Cube(x, y, z, 1) }.toSet() val grid = generateGrid(cubes) val surface = cubes.map { it.let { c -> cubes.filter { cube -> c != cube && isNeighbor(c, cube) } } .fold(6) { acc, neighbour -> calculateSurfaceArea(neighbour, it, acc) } }.sum() val missingCubes = findTrappedCubes(cubes) return surface } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") // check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
6,896
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ClosestMeetingNode.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 2359. Find The Closest Node to Given Two Nodes * @see <a href="https://leetcode.com/problems/find-closest-node-to-given-two-nodes/">Source</a> */ fun interface ClosestMeetingNode { operator fun invoke(edges: IntArray, node1: Int, node2: Int): Int } class ClosestMeetingNodeDFS : ClosestMeetingNode { override operator fun invoke(edges: IntArray, node1: Int, node2: Int): Int { val n = edges.size // d1[i]: shortest dist to node i starting from node 1 val d1 = IntArray(n) { Int.MAX_VALUE } val d2 = IntArray(n) { Int.MAX_VALUE } // vis1[i]: true if node i is visited else false. used for building d1 val vis1 = BooleanArray(n) val vis2 = BooleanArray(n) // dist to node1 from node1 is 0, same as node2 d2[node2] = 0 d1[node1] = d2[node2] // build the dist for d1 dfs(node1, d1, vis1, edges) // build the dist for d2 dfs(node2, d2, vis2, edges) // iterate each node to find the min max dist var ans = -1 var mi = Int.MAX_VALUE for (i in 0 until n) { if (max(d1[i], d2[i]) < mi) { mi = max(d1[i], d2[i]) ans = i } } return ans } private fun dfs(u: Int, d: IntArray, vis: BooleanArray, edges: IntArray) { // mark it visited vis[u] = true // check the outgoing edge val v = edges[u] // -1 means there is no outgoing edge, so we skip it if (v != -1 && !vis[v]) { // the dist going to node v form node u is simply d[u] + 1 d[v] = d[u] + 1 // dfs on neighbour node `v` dfs(v, d, vis, edges) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,407
kotlab
Apache License 2.0
src/Day05.kt
b0n541
571,797,079
false
{"Kotlin": 17810}
import java.util.* fun main() { fun String.parseLine(stacks: Int): List<Char> { var result = ArrayList<Char>() for (i in 0 until stacks) { result.add(this[4 * i + 1]) } return result } fun parseInitialStacks(input: List<String>): Map<Int, Deque<Char>> { val result = mutableMapOf<Int, Deque<Char>>() val stackCount = input.last().replace(" ", "").last().toString().toInt() for (i in 1..stackCount) { result[i] = ArrayDeque() } for (row in input.size - 2 downTo 0) { val cratesInRow = input[row].parseLine(stackCount) for (i in 0 until stackCount) { if (cratesInRow[i] != ' ') { result[i + 1]?.push(cratesInRow[i]) } } } return result } fun parseMoves(input: List<String>): List<CrateMove> { return input.map { it.split(" ") } .map { CrateMove(it[1].toInt(), it[3].toInt(), it[5].toInt()) } } fun parseInput(input: List<String>): Pair<Map<Int, Deque<Char>>, List<CrateMove>> { val emptyLineIndex = input.indexOf("") return Pair( parseInitialStacks(input.subList(0, emptyLineIndex)), parseMoves(input.subList(emptyLineIndex + 1, input.size)) ) } fun pickUpCrates(move: CrateMove, stacks: Map<Int, Deque<Char>>): MutableList<Char> { var cratesToMove = mutableListOf<Char>() repeat(move.crateCount) { cratesToMove.add(stacks[move.fromStack]!!.poll()) } return cratesToMove } fun moveCrates(stacks: Map<Int, Deque<Char>>, moves: List<CrateMove>, reverseOrder: Boolean = false) { moves.forEach { move -> run { var cratesToMove = pickUpCrates(move, stacks) if (reverseOrder) { cratesToMove.reverse() } for (crate in cratesToMove) { stacks[move.toStack]!!.push(crate) } } } } fun moveCratesOneByOne(stacks: Map<Int, Deque<Char>>, moves: List<CrateMove>) { moveCrates(stacks, moves) } fun moveCratesAtOnce(stacks: Map<Int, Deque<Char>>, moves: List<CrateMove>) { moveCrates(stacks, moves, true) } fun part1(input: List<String>): String { val parsedInput = parseInput(input) val stacks = parsedInput.first val moves = parsedInput.second moveCratesOneByOne(stacks, moves) return stacks.map { it.value.peek() }.joinToString("") } fun part2(input: List<String>): String { val parsedInput = parseInput(input) val stacks = parsedInput.first val moves = parsedInput.second moveCratesAtOnce(stacks, moves) return stacks.map { it.value.peek() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") val input = readInput("Day05") val resultTest1 = part1(testInput) println("Test 1: $resultTest1") check(resultTest1 == "CMZ") val resultPart1 = part1(input) println("Part 1: $resultPart1") check(resultPart1 == "QNHWJVJZW") val resultTest2 = part2(testInput) println("Test 2: $resultTest2") check(resultTest2 == "MCD") val resultPart2 = part2(input) println("Part 2: $resultPart2") check(resultPart2 == "BPCZJLFJW") } data class CrateMove(val crateCount: Int, val fromStack: Int, val toStack: Int)
0
Kotlin
0
0
d451f1aee157fd4d47958dab8a0928a45beb10cf
3,589
advent-of-code-2022
Apache License 2.0
src/main/kotlin/co/csadev/advent2022/Day08.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 8 * Problem Description: http://adventofcode.com/2021/day/8 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsList import co.csadev.adventOfCode.asInt import co.csadev.adventOfCode.indexOrMax import kotlin.math.max class Day08(override val input: List<String> = resourceAsList("22day08.txt")) : BaseDay<List<String>, Int, Int> { val size = input.maxOf { it.length } private var bestScore = 0 private val visible = mutableSetOf<Pair<Int, Int>>() init { val map = MutableList(size) { mutableListOf<Int>() } input.forEachIndexed { row, line -> line.map { it.asInt() }.forEachIndexed { col, tree -> map[col].add(row, tree) } } (0 until size).forEach { x -> val maximums = MutableList(4) { -1 } (0 until size).forEach { y -> bestScore = maxOf(bestScore, calculateScore(map, x, y)) maximums[0] = maximums[0].orMax(map[x][y]) { visible.add(x to y) } maximums[1] = maximums[1].orMax(map[x][size - y - 1]) { visible.add(x to size - y - 1) } maximums[2] = maximums[2].orMax(map[y][x]) { visible.add(y to x) } maximums[3] = maximums[3].orMax(map[size - y - 1][x]) { visible.add(size - y - 1 to x) } } } } private fun Int.orMax(other: Int, ifBigger: () -> Unit): Int { if (other > this) { ifBigger() } return max(this, other) } override fun solvePart1() = visible.size override fun solvePart2(): Int = bestScore private fun calculateScore(grid: List<List<Int>>, i: Int, j: Int, comp: Int = grid[i][j]) = (i + 1 until size).indexOrMax { grid[it][j] >= comp } * (i - 1 downTo 0).indexOrMax { grid[it][j] >= comp } * (j + 1 until size).indexOrMax { grid[i][it] >= comp } * (j - 1 downTo 0).indexOrMax { grid[i][it] >= comp } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,086
advent-of-kotlin
Apache License 2.0
src/main/kotlin/aoc2015/Day21.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2015 import AoCDay import util.match // https://adventofcode.com/2015/day/21 object Day21 : AoCDay<Int>( title = "RPG Simulator 20XX", part1Answer = 91, part2Answer = 158, ) { private class Item(val cost: Int, val damage: Int, val armor: Int) private val WEAPONS = listOf( Item(8, 4, 0), Item(10, 5, 0), Item(25, 6, 0), Item(40, 7, 0), Item(74, 8, 0), ) private val ARMOR = listOf( Item(13, 0, 1), Item(31, 0, 2), Item(53, 0, 3), Item(75, 0, 4), Item(102, 0, 5), ) private val RINGS = listOf( Item(25, 1, 0), Item(50, 2, 0), Item(100, 3, 0), Item(20, 0, 1), Item(40, 0, 2), Item(80, 0, 3), ) private val ITEM_PERMUTATIONS = sequence { val armorPermutations = sequence { // 0-1 armor yield(emptyList()) for (a in ARMOR) yield(listOf(a)) } val ringPermutations = sequence { // 0-2 rings yield(emptyList()) for (r in RINGS) yield(listOf(r)) for (r1 in RINGS) { for (r2 in RINGS) { if (r1 !== r2) yield(listOf(r1, r2)) } } } for (w in WEAPONS) { // exactly one weapon for (a in armorPermutations) { for (r in ringPermutations) { yield(a + r + w) } } } } private val BOSS_REGEX = """ Hit Points: (\d+) Damage: (\d+) Armor: (\d+) """.trimIndent().toRegex() private fun parseBoss(input: String): Character { val (hp, damage, armor) = BOSS_REGEX.match(input).toList().map(String::toInt) return Character(hp, damage, armor) } private data class Character(val hp: Int, val damage: Int, val armor: Int) { init { require(damage >= 0 && armor >= 0) } fun attack(defender: Character): Character { val dmg = (this.damage - defender.armor).coerceAtLeast(1) return defender.copy(hp = defender.hp - dmg) } } private fun wouldPlayerWin(boss: Character, items: List<Item>): Boolean { val (damage, armor) = items.fold(0 to 0) { (damage, armor), item -> (damage + item.damage) to (armor + item.armor) } var player = Character(hp = 100, damage, armor) var enemy = boss while (true) { enemy = player.attack(enemy) if (enemy.hp <= 0) return true player = enemy.attack(player) if (player.hp <= 0) return false } } override fun part1(input: String): Int { val boss = parseBoss(input) return ITEM_PERMUTATIONS .filter { items -> wouldPlayerWin(boss, items) } .minOf { items -> items.sumOf { it.cost } } } override fun part2(input: String): Int { val boss = parseBoss(input) return ITEM_PERMUTATIONS .filterNot { items -> wouldPlayerWin(boss, items) } .maxOf { items -> items.sumOf { it.cost } } } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
3,161
advent-of-code-kotlin
MIT License
src/Day02.kt
Tomcat88
572,566,485
false
{"Kotlin": 52372}
fun main() { fun part1(input: List<List<String>>): Int = input.sumOf { it[1].toRPS().round(it[0].toRPS()).total() } fun part2(input: List<List<String>>): Int = input.sumOf { it[0].toRPS().roundWithStrategy(it[1]).total() } val input = readInputAndSplit("Day02") println(part1(input)) println(part2(input)) } fun String.toRPS() = when(this) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw IllegalArgumentException("invalid value: $this") } sealed class RoundResult(private val result: Int, private val modifier: Int) { fun total() = result + modifier } class Win(result: Int) : RoundResult(result, 6) class Draw(result: Int) : RoundResult(result, 3) class Loss(result: Int) : RoundResult(result, 0) sealed class RPS(private val value: Int) { abstract val winsAgainst: RPS abstract val losesAgainst: RPS fun round(you: RPS) = when (you) { this -> Draw(value) winsAgainst -> Win(value) else -> Loss(value) } fun roundWithStrategy(strategy: String) = when(strategy) { "Y" -> round(this) "Z" -> losesAgainst.round(this) "X" -> winsAgainst.round(this) else -> throw IllegalArgumentException("invalid strategy $strategy") } } object Rock : RPS(1) { override val winsAgainst = Scissors override val losesAgainst = Paper } object Paper : RPS(2) { override val winsAgainst = Rock override val losesAgainst = Scissors } object Scissors : RPS(3) { override val winsAgainst = Paper override val losesAgainst = Rock }
0
Kotlin
0
0
6d95882887128c322d46cbf975b283e4a985f74f
1,642
advent-of-code-2022
Apache License 2.0
src/main/kotlin/net/wrony/aoc2023/a12/RiddleTake2.kt
kopernic-pl
727,133,267
false
{"Kotlin": 52043}
package net.wrony.aoc2023.a12 import kotlin.io.path.Path import kotlin.io.path.readLines fun txtToSprings2(s: String): Pair<String, List<Int>> { return s.split(" ").let { (inp, desc) -> inp to desc.split(",").map { it.toInt() } } } val cache = mutableMapOf<Pair<String, List<Int>>, Long>() fun scanput2(str: String, counts: List<Int>): Long { // if str is empty - end of story if (str.isEmpty()) return if (counts.isEmpty()) 1 else 0 if (counts.isEmpty()) return if (str.contains('#')) 0 else 1 println("Cache check for $str to $counts") return cache.getOrPut(str to counts) { println(str) var res = 0L if (str[0] in ".?") { res += scanput2(str.drop(1), counts) } if (str[0] in "#?") { if (counts[0] <= str.length && str.take(counts[0]) .all { it != '.' } && (counts[0] == str.length || str[counts[0]] != '#') ) { res += scanput2(str.drop(counts[0] + 1), counts.drop(1)) } } res } } fun main() { Path("src/main/resources/12.txt").readLines().map { txtToSprings2(it) }.also { it.sumOf { (inp, desc) -> scanput2(inp, desc) }.also { println("Part 1: $it") } } .also { it.map { (inp, blocks) -> generateSequence { inp }.take(5).toList() .joinToString("?") to List(5) { blocks }.flatten() } .sumOf { (inp, blocks) -> scanput2(inp, blocks) }.let { p2res -> println("Part 2: $p2res") } } }
0
Kotlin
0
0
1719de979ac3e8862264ac105eb038a51aa0ddfb
1,563
aoc-2023-kotlin
MIT License
2021/src/day09/Solution.kt
vadimsemenov
437,677,116
false
{"Kotlin": 56211, "Rust": 37295}
package day09 import java.nio.file.Files import java.nio.file.Paths fun main() { val dx = arrayOf(0, 1, 0, -1) val dy = arrayOf(-1, 0, 1, 0) fun part1(lines: Input): Int { var answer = 0 for (x in lines.indices) { outer@for (y in lines[x].indices) { for (d in 0 until 4) { val xx = x + dx[d] val yy = y + dy[d] if (xx in lines.indices && yy in lines[xx].indices) { if (lines[xx][yy] <= lines[x][y]) continue@outer } } answer += lines[x][y].code - '0'.code + 1 } } return answer } fun part2(lines: Input): Int { class DSU(size: Int) { private val parent = IntArray(size) { it } val size = IntArray(size) { 1 } fun getParent(v: Int): Int = if (v == parent[v]) v else getParent(parent[v]).also { parent[v] = it } fun unite(v: Int, u: Int): Boolean { val vp = getParent(v) val up = getParent(u) if (up != vp) { parent[up] = vp size[vp] += size[up] return true } return false } } val dsu = DSU(lines.size * lines[0].length) for (x in lines.indices) { for (y in lines[x].indices) { if (lines[x][y] == '9') continue for (d in 0 until 4) { val xx = x + dx[d] val yy = y + dy[d] if (xx in lines.indices && yy in lines[xx].indices) { if (lines[xx][yy] <= lines[x][y]) { dsu.unite(yy * lines.size + xx, y * lines.size + x) } } } } } val map = buildMap { for (x in lines.indices) { for (y in lines[x].indices) { val root = dsu.getParent(y * lines.size + x) val size = dsu.size[root] put(root, size) } } } return map.values.sortedDescending().take(3).fold(1, Int::times) } check(part1(readInput("test-input.txt")) == 15) check(part2(readInput("test-input.txt")) == 1134) println(part1(readInput("input.txt"))) println(part2(readInput("input.txt"))) } private fun readInput(s: String): Input { return Files.newBufferedReader(Paths.get("src/day09/$s")).readLines() } private typealias Input = List<String>
0
Kotlin
0
0
8f31d39d1a94c862f88278f22430e620b424bd68
2,230
advent-of-code
Apache License 2.0
src/Dec8.kt
karlstjarne
572,529,215
false
{"Kotlin": 45095}
object Dec8 { fun a(): Int { val trees: List<List<Tree>> = getTreeMatrix() trees.forEach { updateTreeVisibility(it) updateTreeVisibility(it.reversed()) } transpose(trees).forEach { updateTreeVisibility(it) updateTreeVisibility(it.reversed()) } return trees.sumOf { it.filter { tree -> tree.isSeen }.size } } fun b(): Int { val trees: List<List<Tree>> = getTreeMatrix() for (i in trees.indices) { for (j in trees[i].indices) { val tree = trees[i][j] // Left var k = j - 1 var scoreLeft = 0 while (trees[i].indices.contains(k)) { scoreLeft++ if (tree.height <= trees[i][k].height) { break } k-- } //Right k = j + 1 var scoreRight = 0 while (trees[i].indices.contains(k)) { scoreRight++ if (tree.height <= trees[i][k].height) { break } k++ } // Up k = i - 1 var scoreUp = 0 while (trees.indices.contains(k)) { scoreUp++ if (tree.height <= trees[k][j].height) { break } k-- } // Down k = i + 1 var scoreDown = 0 while (trees.indices.contains(k)) { scoreDown++ if (tree.height <= trees[k][j].height) { break } k++ } tree.scenicScore = scoreLeft * scoreRight * scoreUp * scoreDown } } return trees.maxOf { it.maxOf { tree -> tree.scenicScore } } } private fun getTreeMatrix(): List<List<Tree>> { val input = readInput("dec8") val trees: List<List<Tree>> = List(input.size) { List(input.first().length) { Tree() } } for (i in input.indices) { for (j in input[i].indices) { trees[i][j].height = input[i][j].digitToInt() } } return trees } private fun updateTreeVisibility(trees: List<Tree>) { var currentLargest = -1 for (i in trees.indices) { val tree = trees[i] if (tree.height > currentLargest) { currentLargest = tree.height tree.isSeen = true } } } private fun transpose(input: List<List<Tree>>): List<List<Tree>> { val transpose: MutableList<MutableList<Tree>> = MutableList(input.size) { MutableList(input.first().size) { Tree() } } for (i in input.indices) { for (j in input[i].indices) { transpose[j][i] = input[i][j] } } return transpose } class Tree( var isSeen: Boolean = false, var height: Int = 0, var scenicScore: Int = 0 ) }
0
Kotlin
0
0
9220750bf71f39f693d129d170679f3be4328576
3,285
AoC_2022
Apache License 2.0
src/Day02.kt
iamriajul
573,026,906
false
{"Kotlin": 3041}
fun main() { fun part1(input: List<String>): Int { fun shapeScore(shape: Char): Int { return shape - 'X' + 1 } fun resultScore(line: String): Int { return when (line) { "B X", "C Y", "A Z" -> 0 "A X", "B Y", "C Z" -> 3 "C X", "A Y", "B Z" -> 6 else -> throw IllegalArgumentException("Invalid line: $line") } } return input.sumOf { shapeScore(it[2]) + resultScore(it) } } fun part2(input: List<String>): Int { fun shapeScore(line: String): Int { return when (line) { "A Y", "B X", "C Z" -> 1 "B Y", "C X", "A Z" -> 2 "C Y", "A X", "B Z" -> 3 else -> throw IllegalArgumentException("Invalid line: $line") } } fun resultScore(shape: Char): Int { return (shape - 'X') * 3 } return input.sumOf { shapeScore(it) + resultScore(it[2]) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") val testResult = part1(testInput) check(testResult == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
10c67022363478b37a7516e13a45552c7fd06097
1,346
advent-of-code-kotlin-2022
Apache License 2.0
rmq/SimpleSegmentTree.kt
wangchaohui
737,511,233
false
{"Kotlin": 36737}
class SimpleSegmentTree(private val n: Int) { data class Interval( val sum: Long = 0, val maxPrefixSum: Long = sum, val maxSuffixSum: Long = sum, val maxSubArraySum: Long = sum, ) { companion object { fun combineNullable(l: Interval?, r: Interval?): Interval? = when { l == null -> r r == null -> l else -> combine(l, r) } fun combine(l: Interval, r: Interval) = Interval( sum = l.sum + r.sum, maxPrefixSum = max(l.maxPrefixSum, l.sum + r.maxPrefixSum), maxSuffixSum = max(r.maxSuffixSum, l.maxSuffixSum + r.sum), maxSubArraySum = maxOf( l.maxSubArraySum, r.maxSubArraySum, l.maxSuffixSum + r.maxPrefixSum, ), ) } } private val t = Array(n * 2) { Interval() } constructor(values: List<Long>) : this(values.size) { values.forEachIndexed { i, v -> t[i + n] = Interval(v) } for (i in n - 1 downTo 1) t[i] = Interval.combine(t[i * 2], t[i * 2 + 1]) } fun query(l: Int, r: Int): Interval? { var resL: Interval? = null var resR: Interval? = null var i = l + n var j = r + n while (i < j) { if (i and 1 > 0) resL = Interval.combineNullable(resL, t[i++]) if (j and 1 > 0) resR = Interval.combineNullable(t[--j], resR) i /= 2 j /= 2 } return Interval.combineNullable(resL, resR) } fun update(p: Int, delta: Int) { var i = p + n t[i] = Interval(t[i].sum + delta) while (i > 1) { i /= 2 t[i] = Interval.combine(t[i * 2], t[i * 2 + 1]) } } }
0
Kotlin
0
0
241841f86fdefa9624e2fcae2af014899a959cbe
1,835
kotlin-lib
Apache License 2.0
src/year2021/Day10.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2021 import readLines fun main() { val input = readLines("2021", "day10") val testInput = readLines("2021", "day10_test") check(part1(testInput) == 26397) println("Part 1:" + part1(input)) check(part2(testInput) == 288957L) println("Part 2:" + part2(input)) } private fun part1(input: List<String>): Int { val evaluateError = hashMapOf(")" to 3, "]" to 57, "}" to 1197, ">" to 25137) var result = 0 for (line in input) { val chars = line.split("").filter { it != "" } val stack = mutableListOf<String>() for (char in chars) { if (isChunkOpening(char)) { stack.add(char) continue } if (stack.isEmpty()) { print("Input invalid, too many closing chunks") break } val previous = stack.removeLast() if (!isCorresponding(previous, char)) { result += evaluateError[char]!! } } } return result } private fun part2(input: List<String>): Long { val evaluateError = hashMapOf("(" to 1, "[" to 2, "{" to 3, "<" to 4) val lineScores = mutableListOf<Long>() for (line in input) { val chars = line.split("").filter { it != "" } val stack = mutableListOf<String>() for (char in chars) { if (isChunkOpening(char)) { stack.add(char) continue } if (stack.isEmpty()) { print("Input invalid, too many closing chunks") break } val previous = stack.removeLast() if (!isCorresponding(previous, char)) { stack.clear() break } } if (stack.isNotEmpty()) { val lineScore = stack.foldRight(0L) { char, acc -> acc * 5 + evaluateError[char]!! } lineScores.add(lineScore) } } return lineScores.sorted()[lineScores.size / 2] } private fun isChunkOpening(c: String): Boolean = setOf("(", "[", "{", "<").contains(c) private fun isCorresponding( start: String, end: String, ) = listOf("(", "[", "{", "<").indexOf(start) == listOf(")", "]", "}", ">").indexOf(end)
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
2,276
advent_of_code
MIT License
advent2022/src/main/kotlin/year2022/Day02.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import year2022.Shape.* import year2022.Outcome.* private typealias Strategy = (String, String) -> Shape private enum class Shape(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3) } private enum class Outcome(val points: Int) { LOSS(0), DRAW(3), WIN(6) } private infix fun Shape.computeOutcome(other: Shape): Outcome = when (other) { this -> DRAW this.getBeatenBy() -> WIN else -> LOSS } private fun Shape(value: String): Shape = when (value) { "X", "A" -> ROCK "Y", "B" -> PAPER else -> SCISSORS } private fun Shape.getBeatenBy(): Shape = when (this) { ROCK -> PAPER PAPER -> SCISSORS else -> ROCK } private fun score(opponent: Shape, you: Shape): Int = you.points + (opponent computeOutcome you).points private fun strategyPart1(a: String, b: String): Shape = when { Shape(a) == Shape(b) -> Shape(a) Shape(b) == Shape(a).getBeatenBy() -> Shape(a).getBeatenBy() else -> Shape(a).getBeatenBy().getBeatenBy() } private fun strategyPart2(opponent: String, goal: String): Shape = when (goal) { // Lose "X" -> Shape(opponent).getBeatenBy().getBeatenBy() // Draw "Y" -> Shape(opponent) // Win else -> Shape(opponent).getBeatenBy() } private fun score(row: String, strategy: Strategy): Int { val (a, b) = row.split(" ") return score(Shape(a), strategy(a, b)) } class Day02 : AdventDay(2022, 2) { override fun part1(input: List<String>): Int = input.sumOf { score(it, ::strategyPart1) } override fun part2(input: List<String>): Int = input.sumOf { score(it, ::strategyPart2) } } fun main() = Day02().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
1,658
advent-of-code
Apache License 2.0
src/main/kotlin/aoc2023/Day01.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import readInput object Day01 { fun part1(input: List<String>): Int { return input.map { "${it.filter { c -> c.isDigit() }.take(1)}${it.filter { c -> c.isDigit() }.takeLast(1)}" } .sumOf { it.toInt() } } fun part2(input: List<String>): Int { val replacements = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9", ) val list: List<String> = input.map { line -> var newLine = line // keep the original text before and after the replacement to account for overlapping texts: eightwo replacements.forEach { newLine = newLine.replace(it.key, "${it.key}${it.value}${it.key}") } newLine } return part1(list) } } fun main() { val testInput = readInput("Day01_test", 2023) check(Day01.part1(testInput) == 142) val testInput2 = readInput("Day01_test_2", 2023) check(Day01.part2(testInput2) == 281) val input = readInput("Day01", 2023) println(Day01.part1(input)) println(Day01.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
1,254
adventOfCode
Apache License 2.0
src/main/kotlin/com/aoc2023/day2/Day2.kt
brookseakate
729,329,997
false
{"Kotlin": 8231}
package main.kotlin.com.aoc2023.day2 import main.kotlin.com.aoc2023.util.Utils.Companion.readFileAsMutableList class Day2 { companion object { fun main() { println("hello Day 2") val bagContents = mapOf( "red" to 12, "green" to 13, "blue" to 14, ) // val input = readFileAsMutableList("day2/SampleInput") val input = readFileAsMutableList("day2/Input") // val total = getPossibleGameIdTotal(input, bagContents) // Part 1 val total = getSumOfGamePowers(input) // Part 2 println(total) } /** * Part 1 */ private fun parseAndCheckGameIsPossible( line: String, bagContents: Map<String, Int>, ): Int { val (gameString, allGamesString) = line.split(": ") val gameNumber = gameString.substringAfter("Game ").toInt() val gameSetsStrings = allGamesString.split("; ") var gameIsPossible = true for (setString in gameSetsStrings) { val cubeQtys = setString.split(", ") for (cubeQty in cubeQtys) { val (qtyString, color) = cubeQty.split(" ") val qty = qtyString.toInt() if (bagContents[color]!! < qty) { gameIsPossible = false } } } return if (gameIsPossible) { gameNumber } else 0 } private fun getPossibleGameIdTotal( input: List<String>, bagContents: Map<String, Int>, ): Int { return input.sumOf { line -> parseAndCheckGameIsPossible(line, bagContents) } } /** * Part 2 */ private fun parseAndGetGamePower( line: String, ): Int { val (_, allGamesString) = line.split(": ") val gameSetsStrings = allGamesString.split("; ") val minimumsMap = mutableMapOf( "red" to 0, "blue" to 0, "green" to 0, ) for (setString in gameSetsStrings) { val cubeQtys = setString.split(", ") for (cubeQty in cubeQtys) { val (qtyString, color) = cubeQty.split(" ") val qty = qtyString.toInt() if (minimumsMap[color]!! < qty) { minimumsMap[color] = qty } } } return minimumsMap.values.reduce { x, y -> x * y} } private fun getSumOfGamePowers( input: List<String>, ): Int { return input.sumOf { line -> parseAndGetGamePower(line) } } } }
0
Kotlin
0
0
885663f27a8d5f6e6c5eaf046df4234b49bc53b9
2,401
advent-of-code-2023
MIT License
src/Day02.kt
sungi55
574,867,031
false
{"Kotlin": 23985}
fun main() { val day = "Day02" val winCombination = setOf("A Y", "B Z", "C X") val drawCombination = setOf("B X", "C Y", "A Z") fun sumScore(moves: List<String>, isDefaultStrategy: Boolean) = moves.map { move -> move.takeIf { isDefaultStrategy } ?: move.swapToNewStrategy() }.sumOf { move -> when (move) { in winCombination -> 6 in drawCombination -> 0 else -> 3 }.plus(move.takeLast(1).asMoveBonus()) } fun part1(input: List<String>): Int = sumScore(input, isDefaultStrategy = true) fun part2(input: List<String>): Int = sumScore(input, isDefaultStrategy = false) val testInput = readInput(name = "${day}_test") val input = readInput(name = day) check(part1(testInput) == 15) check(part2(testInput) == 12) println(part1(input)) println(part2(input)) } private fun String.asMoveBonus() = when (this) { "X" -> 1 "Y" -> 2 else -> 3 } private fun String.swapToNewStrategy() = take(2).plus( when (takeLast(1)) { "X" -> first().asLoseMove() "Y" -> first().asDrawMove() else -> first().asWinMove() } ) private fun Char.asLoseMove() = when (this) { 'A' -> "Z" 'B' -> "X" else -> "Y" } private fun Char.asDrawMove() = when (this) { 'A' -> "X" 'B' -> "Y" else -> "Z" } private fun Char.asWinMove() = when (this) { 'A' -> "Y" 'B' -> "Z" else -> "X" }
0
Kotlin
0
0
2a9276b52ed42e0c80e85844c75c1e5e70b383ee
1,597
aoc-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2017/Day16.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 /** * AoC 2017, Day 16 * * Problem Description: http://adventofcode.com/2017/day/16 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day16/ */ class Day16(input: String, private val programNames: String = "abcdefghijklmnop") { private val initialState: CharArray = programNames.toCharArray() private val instructions: List<Dance> = parseInput(input) fun solvePart1(): String = executeInstructions() tailrec fun solvePart2(memory: Map<String, Int> = mapOf(), loopNumber: Int = 0, hash: String = programNames): String { return if (hash in memory) { // We found it! val cycleStart = memory.getValue(hash) val offset = (1_000_000_000 % (loopNumber - cycleStart)) - cycleStart memory.entries.first { it.value == offset }.key } else { solvePart2(memory + (hash to loopNumber), loopNumber.inc(), executeInstructions(hash.toCharArray())) } } private fun executeInstructions(startState: CharArray = initialState): String = instructions.fold(startState) { carry, next -> evaluate(carry, next) }.joinToString("") private fun evaluate(programs: CharArray, instruction: Dance): CharArray = when (instruction) { is Spin -> { (programs.takeLast(instruction.amount) + programs.dropLast(instruction.amount)).toCharArray() } is Exchange -> programs.swap(instruction.left, instruction.right) is Partner -> programs.swap(programs.indexOf(instruction.left), programs.indexOf(instruction.right)) } private fun parseInput(input: String): List<Dance> = input .split(",") .map { it.trim() } .map { when (it.first()) { 's' -> Spin(it.drop(1).toInt()) 'x' -> { val (a, b) = it.drop(1).split("/").map { it.toInt() } Exchange(a, b) } 'p' -> { Partner(it[1], it[3]) } else -> throw IllegalArgumentException("Bad input: $it") } } } sealed class Dance class Spin(val amount: Int) : Dance() class Exchange(val left: Int, val right: Int) : Dance() class Partner(val left: Char, val right: Char) : Dance()
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
2,513
advent-2017-kotlin
MIT License
src/Day04.kt
F-bh
579,719,291
false
{"Kotlin": 5785}
fun main() { val input = readDayInput(4) val pairList = input.map { line -> val pairList = line.split(",") Pair(pairList[0], pairList[1]) }.map { pair -> val split1 = pair.first.split("-") val split2 = pair.second.split("-") Pair( split1[0].toInt()..split1[1].toInt(), split2[0].toInt()..split2[1].toInt() ) } pt1(pairList) pt2(pairList) } fun pt1(pairs: List<Pair<IntRange, IntRange>>){ val res = pairs .filter { pair -> pair.first.contains(pair.second.first) && pair.first.contains(pair.second.last) || pair.second.contains(pair.first.first) && pair.second.contains(pair.first.last) } println(res.size) } fun pt2(pairs: List<Pair<IntRange, IntRange>>) { val res = pairs. filter { pair -> pair.first.contains(pair.second.first) || pair.first.contains(pair.second.last) || pair.second.contains(pair.first.first) || pair.second.contains(pair.first.last) } println(res.size) }
0
Kotlin
0
0
19fa2db8842f166daf3aaffd201544658f41d9e0
1,039
Christmas2022
Apache License 2.0
src/main/kotlin/y2016/day01/Day01.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2016.day01 import java.lang.IllegalStateException import kotlin.math.abs fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } data class Instructions( val turnDirection: TurnDirection, val distance: Int ) enum class TurnDirection { LEFT, RIGHT } enum class Direction { NORTH, EAST, SOUTH, WEST } fun input(): List<Instructions> { return AoCGenerics.getInputLines("/y2016/day01/input.txt").first() .split(",") .map { it.trim() } .map { Instructions( turnDirection = when { it.first() == 'L' -> TurnDirection.LEFT it.first() == 'R' -> TurnDirection.RIGHT else -> throw IllegalStateException() }, distance = it.substring(1).toInt() ) } } fun part1(): Int { var facing = Direction.NORTH var distanceX = 0 var distanceY = 0 input().forEach{instruction -> facing = changeDirection(facing, instruction.turnDirection) when (facing) { Direction.NORTH -> distanceY += instruction.distance Direction.EAST -> distanceX += instruction.distance Direction.SOUTH -> distanceY -= instruction.distance Direction.WEST -> distanceX -= instruction.distance } } return abs(distanceX) + abs(distanceY) } fun part2(): Int { var facing = Direction.NORTH var distanceX = 0 var distanceY = 0 val visitedLocation = mutableSetOf("0,0") input().forEach{instruction -> facing = changeDirection(facing, instruction.turnDirection) when (facing) { Direction.NORTH -> { repeat(instruction.distance) { if (visitedLocation.contains("$distanceX,${distanceY + 1}")) { return abs(distanceX) + abs(distanceY + 1) } else { distanceY += 1 visitedLocation.add("$distanceX,$distanceY") } } } Direction.EAST -> { repeat(instruction.distance) { if (visitedLocation.contains("${distanceX+1},$distanceY")) { return abs(distanceX+1) + abs(distanceY) } else { distanceX += 1 visitedLocation.add("$distanceX,$distanceY") } } } Direction.SOUTH -> { repeat(instruction.distance) { if (visitedLocation.contains("$distanceX,${distanceY - 1}")) { return abs(distanceX) + abs(distanceY - 1) } else { distanceY -= 1 visitedLocation.add("$distanceX,$distanceY") } } } Direction.WEST -> { repeat(instruction.distance) { if (visitedLocation.contains("${distanceX-1},$distanceY")) { return abs(distanceX-1) + abs(distanceY) } else { distanceX -= 1 visitedLocation.add("$distanceX,$distanceY") } } } } } return abs(distanceX) + abs(distanceY) } fun changeDirection(curDirection: Direction, turn: TurnDirection): Direction = when (curDirection) { Direction.NORTH -> if (turn == TurnDirection.LEFT) Direction.WEST else Direction.EAST Direction.EAST -> if (turn == TurnDirection.LEFT) Direction.NORTH else Direction.SOUTH Direction.SOUTH -> if (turn == TurnDirection.LEFT) Direction.EAST else Direction.WEST Direction.WEST -> if (turn == TurnDirection.LEFT) Direction.SOUTH else Direction.NORTH }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
3,948
AdventOfCode
MIT License
2023/src/day09/day09.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day09 import GREEN import RESET import printTimeMillis import readInput private fun List<Int>.toDiffList(): List<List<Int>> { val diffList = mutableListOf<List<Int>>().also { it.add(this) } val diffs = toMutableList() while (diffs.any { it != 0 }) { val newDiffs = buildList { for (i in 0 until diffs.lastIndex) { add(diffs[i + 1] - diffs[i]) } } diffs.clear() diffs.addAll(newDiffs) if (newDiffs.isNotEmpty()) diffList.add(newDiffs) } return diffList } fun part1(input: List<String>) = input.map { val seq = it.split(" ").map { it.toInt() } seq.toDiffList().map { it.last() }.sum() }.sum() fun part2(input: List<String>) = input.map { val seq = it.split(" ").map { it.toInt() } seq.toDiffList().map { it.first() }.reversed().fold(0) { acc, i -> i - acc } }.sum() fun main() { val testInput = readInput("day09_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day09.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,346
advent-of-code
Apache License 2.0
src/day_02/Day02.kt
the-mgi
573,126,158
false
{"Kotlin": 5720}
package day_02 import readInput fun main() { fun obtainResult(myChoice: String, elfChoice: String): Int { return when (myChoice) { "X" -> if (elfChoice == "C") (1 + 6) else if (elfChoice == "A") (1 + 3) else 1 "Y" -> if (elfChoice == "A") (2 + 6) else if (elfChoice == "B") (2 + 3) else 2 "Z" -> if (elfChoice == "B") (3 + 6) else if (elfChoice == "C") (3 + 3) else 3 else -> 0 } } fun questionOne(): Int { return readInput("day_02/input") .map { val (elfChoice, myChoice) = it.split(" ") return@map obtainResult(myChoice, elfChoice) }.sum() } fun questionTwo(): Int { return readInput("day_02/input") .map { val (elfChoice, indicatingOutcome) = it.split(" ") return@map when (elfChoice) { "A" -> obtainResult(if (indicatingOutcome == "X") "Z" else if (indicatingOutcome == "Y") "X" else "Y", elfChoice) "B" -> obtainResult(if (indicatingOutcome == "X") "X" else if (indicatingOutcome == "Y") "Y" else "Z", elfChoice) "C" -> obtainResult(if (indicatingOutcome == "X") "Y" else if (indicatingOutcome == "Y") "Z" else "X", elfChoice) else -> 0 } } .sum() } println("Question 01: ${questionOne()}") println("Question 02: ${questionTwo()}") }
0
Kotlin
0
0
c7f9e9727ccdef9231f0cf125e678902e2d270f7
1,477
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/day8.kt
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
data class Instruction( val operation: String, val positive: Boolean, val amount: Int ) { companion object { const val NOP = "nop" const val ACC = "acc" const val JUMP = "jmp" } } fun day8ProblemReader(string: String): List<Instruction> { val instructionRegex = """(\w+)\s(\+|\-)(\d+)""".toRegex() return string .split("\n") .map { line -> val (instruction, signStr, amount) = instructionRegex.matchEntire(line)!!.destructured if (signStr == "+") { Instruction(instruction, true, amount.toInt()) } else { Instruction(instruction, false, amount.toInt()) } }.toList() } // https://adventofcode.com/2020/day/8 class Day8( private val code: List<Instruction>, ) { fun solvePart1(): Int { val (_, acc: Int) = executeCode(code) return acc } fun solvePart2(): Int { for (index in code.indices) { if (code[index].operation == Instruction.ACC) { continue } val mutatedCode = code.toMutableList() if (code[index].operation == Instruction.NOP) { mutatedCode[index] = Instruction(Instruction.JUMP, code[index].positive, code[index].amount) } else { mutatedCode[index] = Instruction(Instruction.NOP, code[index].positive, code[index].amount) } val (visited: List<Int>, acc: Int) = executeCode(mutatedCode) val isLoop = visited.filter { it == 2 }.count() != 0 if (!isLoop) { return acc } } return 0 } private fun executeCode(instructions: List<Instruction>): Pair<List<Int>, Int> { var acc = 0 val visited = instructions.map { 0 }.toMutableList() var index = 0 visited[index] = 1 while (visited[index] == 1) { val instruction = instructions[index] when (instruction.operation) { Instruction.ACC -> { acc = calculateNext(instruction, acc) index += 1 } Instruction.JUMP -> { index = calculateNext(instruction, index) } Instruction.NOP -> { index += 1 } } if (index == visited.size){ return Pair(visited, acc) } visited[index] += 1 } return Pair(visited, acc) } private fun calculateNext(instruction: Instruction, counter: Int): Int { return if (instruction.positive) { counter.plus(instruction.amount) } else { counter.minus(instruction.amount) } } } fun main() { val problem = day8ProblemReader(Day6::class.java.getResource("day8.txt").readText()) println("solution = ${Day8(problem).solvePart1()}") println("solution part 2 = ${Day8(problem).solvePart2()}") }
0
Ruby
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
3,050
adventofcode_2020
MIT License
libraries/mindiff/src/commonMain/kotlin/com/zegreatrob/mindiff/StringDiff.kt
robertfmurdock
172,112,213
false
{"Kotlin": 170915, "JavaScript": 796, "Batchfile": 697, "Dockerfile": 282}
package com.zegreatrob.mindiff import kotlin.math.max import kotlin.math.min fun stringDiff(l: String, r: String): String { val diff = diff(l, r) val firstDiffIndex = diff.firstDiffIndex() if (firstDiffIndex == -1) { return "" } return differentSectionDescription(l, r, firstDiffIndex) .joinToString("\n") } private fun differentSectionDescription(l: String, r: String, firstDiffIndex: Int): List<String> { val reverseDiff = diff(l.reversed(), r.reversed()) val reverseDiffIndex = reverseDiff.firstDiffIndex() val largestSize = max(l.length, r.length) val endDiffIndex = largestSize - reverseDiffIndex val eDiffRange = l.diffRange(firstDiffIndex, min(endDiffIndex, l.length)) val aDiffRange = r.diffRange(firstDiffIndex, min(endDiffIndex, r.length)) return if (eDiffRange.length > 20) { splitIntoTwoDiffSections(firstDiffIndex, eDiffRange, aDiffRange) .ifEmpty { diffDescription(index = firstDiffIndex, eDiff = eDiffRange, aDiff = aDiffRange) } } else { diffDescription(index = firstDiffIndex, eDiff = eDiffRange, aDiff = aDiffRange) } } private fun splitIntoTwoDiffSections(originalFirstDiff: Int, eDiffRange: String, aDiffRange: String): List<String> { for (eIndex in 0 until min(eDiffRange.length, 20)) { for (aIndex in 0 until min(aDiffRange.length, 20)) { val diff = diff(eDiffRange.substring(eIndex), aDiffRange.substring(aIndex)) val innerFirstDiffIndex = diff.firstDiffIndex() if (innerFirstDiffIndex > 2) { return diffDescription( index = originalFirstDiff, eDiff = eDiffRange.substring(0 until eIndex), aDiff = aDiffRange.substring(0 until aIndex), ) + diffDescription( index = originalFirstDiff + eIndex + innerFirstDiffIndex, eDiff = eDiffRange.substring(eIndex + innerFirstDiffIndex), aDiff = aDiffRange.substring(aIndex + innerFirstDiffIndex), ) } } } return emptyList() } private fun diffDescription(index: Int, eDiff: String, aDiff: String) = listOf( "Difference at index $index.", "E: $eDiff", "A: $aDiff", ) private fun String.diffRange(firstDiffIndex: Int, endOfString: Int) = (firstDiffIndex until endOfString).let { substring(it) } private fun String.firstDiffIndex() = indexOf("x")
0
Kotlin
2
6
9044806e7f09bb6365b1854a69a8cf67f2404587
2,488
testmints
MIT License
src/day20/Day20.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day20 import getWrapped import readInput const val day = "20" fun <T> MutableList<T>.swap(idx1: Int, idx2: Int) { val temp = this[idx1] this[idx1] = this[idx2] this[idx2] = temp } fun main() { fun calculatePart1Score(input: List<String>): Int { val numbers = input.map { it.toInt() }.withIndex() val result = numbers.toMutableList() numbers.forEach { indexedNumber -> val currentIndex = result.indexOf(indexedNumber) result.removeAt(currentIndex) var newIndex = (currentIndex + indexedNumber.value).mod(result.size) if (newIndex == 0) { newIndex = result.size } result.add(newIndex, indexedNumber) // println(result.map { it.value }) } val resultNumbers = result.map { it.value } val firstZeroIdx = resultNumbers.indexOf(0) return resultNumbers.getWrapped(firstZeroIdx + 1000) + resultNumbers.getWrapped(firstZeroIdx + 2000) + resultNumbers.getWrapped(firstZeroIdx + 3000) } fun calculatePart2Score(input: List<String>): Long { val numbers = input.map { it.toInt() * 811589153L }.withIndex() val result = numbers.toMutableList() repeat(10) { numbers.forEach { indexedNumber -> val currentIndex = result.indexOf(indexedNumber) result.removeAt(currentIndex) var newIndex = (currentIndex + indexedNumber.value).mod(result.size) if (newIndex == 0) { newIndex = result.size } result.add(newIndex, indexedNumber) // println(result.map { it.value }) } } val resultNumbers = result.map { it.value } val firstZeroIdx = resultNumbers.indexOf(0) return resultNumbers.getWrapped(firstZeroIdx + 1000) + resultNumbers.getWrapped(firstZeroIdx + 2000) + resultNumbers.getWrapped(firstZeroIdx + 3000) } // test if implementation meets criteria from the description, like: val testInput = readInput("/day$day/Day${day}_test") val input = readInput("/day$day/Day${day}") val part1TestPoints = calculatePart1Score(testInput) println("Part1 test points: $part1TestPoints") check(part1TestPoints == 3) val part1points = calculatePart1Score(input) println("Part1 points: $part1points") val part2TestPoints = calculatePart2Score(testInput) println("Part2 test points: $part2TestPoints") check(part2TestPoints == 1623178306L) val part2points = calculatePart2Score(input) println("Part2 points: $part2points") }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
2,728
advent-of-code-22-kotlin
Apache License 2.0
day-01/src/main/kotlin/SonarSweep.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
fun main() { println("Part One Solution: ${partOne()}") println("Part Two Solution: ${partTwo()}") println("Part One Functional Solution: ${partOneFunctional()}") println("Part Two Windowed Solution: ${partTwoWindowed()}") } fun partOne(): Int { val lines = readInput() var count = 0 for (i in lines.indices) { if (i == 0) { continue } if (lines[i] > lines[i - 1]) { count++ } } return count } fun partTwo(): Int { val lines = readInput() var count = 0 var previous: ThreeMeasureSlide? = null for (i in lines.indices) { if ((i + 2) < lines.size) { val current = ThreeMeasureSlide(lines[i], lines[i + 1], lines[i + 2]) if ((previous != null) && (current.sum() > previous.sum())) { count++ } previous = current } } return count } data class ThreeMeasureSlide( val first: Int, val second: Int, val third: Int, ) { fun sum() = first.plus(second).plus(third) } fun partOneFunctional(): Int { val lines = readInput() return lines.drop(1) .filterIndexed { index, element -> element > lines[index] } .count() } fun partTwoWindowed(): Int { val lines = readInput() val slides = lines.windowed(3, 1, false) { it[0] + it[1] + it[2] } return slides.drop(1) .filterIndexed { index, element -> element > slides[index] } .count() } private fun readInput(): List<Int> { return {}::class.java.classLoader.getResource("input.txt") .readText() .split("\n") .filter { it.isNotBlank() } .map { Integer.parseInt(it) } }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
1,765
aoc-2021
MIT License
src/main/kotlin/day8/Day8.kt
mortenberg80
574,042,993
false
{"Kotlin": 50107}
package day8 class Day8(val input: List<String>) { private val transposed = transpose(input) val inputInts = input.map { it.toCharArray().map { it.digitToInt() } } val transposedInts = transposed.map { it.toCharArray().map { it.digitToInt() } } val visibleFromLeft = input.mapIndexed { rowNo, row -> visibleFromStart(rowNo, row) }.flatten().toSet() val visibleFromRight = input.mapIndexed { rowNo, row -> visibleFromEnd(rowNo, row) }.flatten().toSet() val visibleFromTop = transposed.mapIndexed { rowNo, row -> visibleFromTop(rowNo, row) }.flatten().toSet() val visibleFromBottom = transposed.mapIndexed { rowNo, row -> visibleFromBottom(rowNo, row) }.flatten().toSet() fun visibleFromStart(rowNo: Int, row: String): Set<Pair<Int, Int>> { if (row.isBlank()) return setOf() val rowInfo = row.foldIndexed(RowInfo(rowNo, -1, setOf())) { index, rowInfo, char -> rowInfo.add(char, index) } return rowInfo.positions.map { Pair(rowNo, it) }.toSet() } fun visibleFromEnd(rowNo: Int, row: String): Set<Pair<Int, Int>> { if (row.isBlank()) return setOf() val rowInfo = row.foldRightIndexed(RowInfo(rowNo, -1, setOf())) { index, char, rowInfo -> rowInfo.add(char, index) } return rowInfo.positions.map { Pair(rowNo, it) }.toSet() } fun visibleFromTop(colNo: Int, col: String): Set<Pair<Int, Int>> { if (col.isBlank()) return setOf() val rowInfo = col.foldIndexed(RowInfo(colNo, -1, setOf())) { index, rowInfo, char -> rowInfo.add(char, index) } return rowInfo.positions.map { Pair(it, colNo) }.toSet() } fun visibleFromBottom(colNo: Int, col: String): Set<Pair<Int, Int>> { if (col.isBlank()) return setOf() val rowInfo = col.foldRightIndexed(RowInfo(colNo, -1, setOf())) { index, char, rowInfo -> rowInfo.add(char, index) } return rowInfo.positions.map { Pair(it, colNo) }.toSet() } fun part1(): Int { val union = visibleFromLeft.union(visibleFromRight).union(visibleFromTop).union(visibleFromBottom) println("Union: ${union.sortedWith(compareBy<Pair<Int, Int>> { it.first }.thenBy { it.second })}") return union.size } val pairs = (input.indices).map { column -> (transposed.indices).map { row -> Pair(row, column) } }.flatten() fun part2(): Int { val associateWith = pairs.associateWith { sightLeft(it) * sightRight(it) * sightDown(it) * sightUp(it) } val entry = associateWith.maxWith { a, b -> a.value.compareTo(b.value) } println("Max pair is ${entry.key} = ${entry.value}") return entry.value } fun calculateScenicScore(pair: Pair<Int, Int>): Int { val up = sightUp(pair) val left = sightLeft(pair) val down = sightDown(pair) val right = sightRight(pair) println("[up=$up][left=$left][down=$down][right=$right]") val sum = up * left * down * right println("sum = $sum") return sum } fun sightUp(position: Pair<Int, Int>): Int { val height = inputInts[position.first][position.second] val consideredTrees = transposedInts[position.second].take(position.first) val count = consideredTrees.takeLastWhile { it < height }.count() if (count == consideredTrees.count()) return count return count + 1 } fun sightDown(position: Pair<Int, Int>): Int { val height = inputInts[position.first][position.second] val consideredTrees = transposedInts[position.second].drop(position.first + 1) val count = consideredTrees.takeWhile { it < height }.count() if (count == consideredTrees.count()) return count return count + 1 } fun sightRight(position: Pair<Int, Int>): Int { val height = inputInts[position.first][position.second] val consideredTrees = inputInts[position.first].drop(position.second + 1) val count = consideredTrees.takeWhile { it < height }.count() if (count == consideredTrees.count()) return count return count + 1 } fun sightLeft(position: Pair<Int, Int>): Int { val height = inputInts[position.first][position.second] val consideredTrees = inputInts[position.first].take(position.second) val count = consideredTrees.takeLastWhile { it < height }.count() if (count == consideredTrees.count()) return count return count + 1 } } data class RowInfo(val rowNo: Int, val highestNumber: Int, val positions: Set<Int>) { fun add(input: Char, index: Int): RowInfo { val inputDigit = input.digitToInt() if (highestNumber == 9 || inputDigit <= highestNumber) return this return this.copy(highestNumber = inputDigit, positions = positions + index) } } private fun transpose(input: List<String>): List<String> { val columns = input.first().length - 1 return (0..columns).map { column -> input.map { string -> string[column] }.joinToString("") } } fun main() { val testInput = Day8::class.java.getResourceAsStream("/day8_test.txt").bufferedReader().readLines() val input = Day8::class.java.getResourceAsStream("/day8_input.txt").bufferedReader().readLines() val day8test = Day8(testInput) val day8input = Day8(input) println("From left: ${day8test.visibleFromLeft}") println("From right: ${day8test.visibleFromRight}") println("From top: ${day8test.visibleFromTop}") println("From bottom: ${day8test.visibleFromBottom}") println("Part 1 test result: ${day8test.part1()}") println("Part 1 result: ${day8input.part1()}") println("Part 2 test result: ${day8test.part2()}") println("Part 2 result: ${day8input.part2()}") // println(day8test.sightUp(Pair(3,2))) // println(day8test.sightLeft(Pair(3,2))) // println(day8test.sightDown(Pair(3,2))) // println(day8test.sightRight(Pair(3,2))) // // println("1,1=" + day8test.calculateScenicScore(Pair(1,1))) // println("1,2=" + day8test.calculateScenicScore(Pair(1,2))) // println("3,2=" + day8test.calculateScenicScore(Pair(3,2))) } /* abc def ghi */
0
Kotlin
0
0
b21978e145dae120621e54403b14b81663f93cd8
6,188
adventofcode2022
Apache License 2.0
src/main/kotlin/aoc23/Day08.kt
tahlers
725,424,936
false
{"Kotlin": 65626}
package aoc23 object Day08 { enum class Direction { LEFT, RIGHT } data class Turn(val name: String, val leftName: String, val rightName: String) { fun doTurn(direction: Direction) = if (direction == Direction.LEFT) leftName else rightName } data class PathStep(val stepCount: Int, val currentTurn: Turn) data class DesertMap(val directions: List<Direction>, val turnMap: Map<String, Turn>) fun stepsToReachTarget(input: String): Int { val desertMap = parseInput(input) val path = generatePathSequence(desertMap.turnMap["AAA"]!!, desertMap) val finish = path.first { it.currentTurn.name == "ZZZ" } return finish.stepCount } fun stepsToReachGhostTarget(input: String): Long { val desertMap = parseInput(input) val ghostStarts = desertMap.turnMap.filterKeys { it.endsWith('A') }.values val cycles = ghostStarts.map { generatePathSequence(it, desertMap) } .map { path -> path.first { it.currentTurn.name.endsWith('Z') } } val cycleLengths = cycles.map { it.stepCount } val lcm = findLCM(cycleLengths.map { it.toLong() }) return lcm } private fun generatePathSequence(startTurn: Turn, desertMap: DesertMap): Sequence<PathStep> { return generateSequence(0) { it + 1 }.runningFold(PathStep(0, startTurn)) { acc, step -> val currentDirIndex = step % desertMap.directions.size val currentDir = desertMap.directions[currentDirIndex] val newTurn = acc.currentTurn.doTurn(currentDir) PathStep(acc.stepCount + 1, desertMap.turnMap[newTurn]!!) } } private fun parseInput(input: String): DesertMap { val directions = input.lineSequence().first().map { if (it == 'L') Direction.LEFT else Direction.RIGHT } val lines = input.trim().lines().drop(2) val turnMap = lines.associate { line -> val name = line.substringBefore('=').trim() val leftName = line.substringAfter('(').substringBefore(',') val rightName = line.substringAfter(", ").substringBefore(')') name to Turn(name, leftName, rightName) } return DesertMap(directions, turnMap) } }
0
Kotlin
0
0
0cd9676a7d1fec01858ede1ab0adf254d17380b0
2,247
advent-of-code-23
Apache License 2.0
src/main/kotlin/Day13.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset fun main() { fun findReflectionPont(it: List<String>): Int { it.forEachIndexed { index, s -> if (index < it.lastIndex && s == it[index + 1]) { if (index >= it.lastIndex / 2) { val listAfterMirror = it.subList(index + 1, it.size) val listBeforeMirror = it.subList(index - listAfterMirror.lastIndex, index + 1).reversed() if (listBeforeMirror == listAfterMirror) { return (index + 1) } } else { val listBeforeMirror = it.subList(0, index + 1) val listAfterMirror = it.subList(index + 1, index + listBeforeMirror.size + 1) if (listBeforeMirror.reversed() == listAfterMirror) { return (index + 1) } } } } return 0 } fun valueOfReflection(list: List<String>): Int { val valueOfReflectionHorizontal = findReflectionPont(list) return if (valueOfReflectionHorizontal != 0) { (valueOfReflectionHorizontal) * 100 } else { findReflectionPont((0..list.first.lastIndex).map { list.map { s -> s[it] }.joinToString("") }) } } fun smudgedCompare(s1: String, s2: String): Int { if (s1 == s2) return 0 return s1.mapIndexed { index, c -> if (c == s2[index]) { 0 } else { 1 } }.sum() } fun smudgedCompare(list1: List<String>, list2: List<String>): Int { return list1.mapIndexed { index, s -> smudgedCompare(s, list2[index]) }.sum() } fun findSmudgedReflectionPont(it: List<String>): Int { it.forEachIndexed { index, s -> if (index < it.lastIndex && smudgedCompare(s, it[index + 1]) <= 1) { if (index >= it.lastIndex / 2) { val listAfterMirror = it.subList(index + 1, it.size) val listBeforeMirror = it.subList(index - listAfterMirror.lastIndex, index + 1).reversed() if (smudgedCompare(listBeforeMirror, listAfterMirror) == 1) { return (index + 1) } } else { val listBeforeMirror = it.subList(0, index + 1) val listAfterMirror = it.subList(index + 1, index + listBeforeMirror.size + 1).reversed() if (smudgedCompare(listBeforeMirror, listAfterMirror) == 1) { return (index + 1) } } } } return 0 } fun valueOfSmudgedReflection(list: List<String>): Int { val valueOfReflectionHorizontal = findSmudgedReflectionPont(list) return if (valueOfReflectionHorizontal != 0) { (valueOfReflectionHorizontal) * 100 } else { findSmudgedReflectionPont((0..list.first.lastIndex).map { list.map { s -> s[it] }.joinToString("") }) } } fun splitInput(input: List<String>): List<List<String>> { val patternSeparators = input.mapIndexedNotNull { index, s -> if (s.isEmpty()) index else null } var start = 0 return (patternSeparators + input.size).map { val item = input.subList(start, it) start = it + 1 item } } fun part1(input: List<String>): Int { return splitInput(input).sumOf { valueOfReflection(it) } } fun part2(input: List<String>): Int { return splitInput(input).sumOf { valueOfSmudgedReflection(it) } } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day13-input.txt") val result1 = part1(input) "Result1: $result1".println() val result2 = part2(input) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
4,205
aoc-2023-in-kotlin
Apache License 2.0
src/main/kotlin/com/sk/set3/373. Find K Pairs with Smallest Sums.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set3 import java.util.* class Solution373 { // TLE fun kSmallestPairs(nums1: IntArray, nums2: IntArray, k: Int): List<List<Int>> { val q = PriorityQueue<Pair<Int, List<Int>>> { p1, p2 -> p1.first - p2.first } for (u in nums1) { for (v in nums2) { q.add(Pair(u + v, mutableListOf(u, v))) } } val res = mutableListOf<MutableList<Int>>() var count = 0 while (count < k && q.isNotEmpty()) { res.add(q.poll().second.toMutableList()) count++ } return res } fun kSmallestPairs2(nums1: IntArray, nums2: IntArray, k: Int): List<List<Int>> { var k = k val que = PriorityQueue<IntArray> { a, b -> a[0] + a[1] - b[0] - b[1] } val res = mutableListOf<List<Int>>() var i = 0 while (i < nums2.size && i < k) { que.offer(intArrayOf(nums1[0], nums2[i], 0)) i++ } while (k-- > 0 && que.isNotEmpty()) { val cur = que.poll() res.add(listOf(cur[0], cur[1])) val idx1 = cur[2] if (idx1 == nums1.size - 1) continue que.offer(intArrayOf(cur[idx1+1], cur[1], idx1 + 1)) } return res } } // https://leetcode.com/problems/find-k-pairs-with-smallest-sums/solutions/84551/simple-java-o-klogk-solution-with-explanation/comments/168485 class Solution373_1 { fun kSmallestPairs(nums1: IntArray, nums2: IntArray, k: Int): List<IntArray> { var k = k val pq = PriorityQueue<IntArray> { a, b -> nums1[a[0]] + nums2[a[1]] - (nums1[b[0]] + nums2[b[1]]) } val res: MutableList<IntArray> = ArrayList() var i = 0 while (i < nums1.size && i < k) { pq.offer(intArrayOf(i, 0)) i++ } while (k-- > 0 && !pq.isEmpty()) { val cur = pq.poll() res.add(intArrayOf(nums1[cur[0]], nums2[cur[1]])) if (cur[1] == nums2.size - 1) continue //Don't add the next index if there is no more left in 2nd array pq.offer(intArrayOf(cur[0], cur[1] + 1)) } return res } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
2,192
leetcode-kotlin
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day20.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2016 import se.saidaspen.aoc.util.Day fun main() = Day20.run() object Day20 : Day(2016, 20) { override fun part1(): Any { var available = listOf(Pair(0L, 4294967295L)) for (l in input.lines()) { val (a, b) = l.split("-") val block = Pair(a.toLong(), b.toLong()) available = available.flatMap { split(it, block) } } return available.map { it.first }.minOfOrNull { it }!! } override fun part2(): Any { var available = listOf(Pair(0L, 4294967295L)) for (l in input.lines()) { val (a, b) = l.split("-") val block = Pair(a.toLong(), b.toLong()) available = available.flatMap { split(it, block) } } return available.sumOf { it.second - it.first + 1 } } fun split(available: Pair<Long, Long>, blocked: Pair<Long, Long>): List<Pair<Long, Long>> { val result = mutableListOf<Pair<Long, Long>>() if (blocked.first > available.second || blocked.second < available.first) { // None blocked result.add(available) } else if (blocked.first <= available.first && blocked.second >= available.second) { // All blocked! } else if (blocked.first <= available.first) { // Blocks lower range result.add(Pair(blocked.second + 1, available.second)) } else if (blocked.second >= available.second) { // Blocks higher range result.add(Pair(available.first, blocked.first - 1)) } else { // Blocks middle result.add(Pair(available.first, blocked.first - 1)) // Lower range result.add(Pair(blocked.second + 1, available.second)) // Upper range } return result } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,752
adventofkotlin
MIT License
src/main/kotlin/aoc2015/WizardSimulator.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2015 import utils.shortestPathWithCost fun wizardSimulator(hard: Boolean = false): Int { val initial = WizardSimulatorState( bossHitPoints = 55, wizardHitPoints = 50, wizardMana = 500, effects = emptyList(), hard = hard ) return shortestPathWithCost(initial, WizardSimulatorState::isWin, WizardSimulatorState::validTransitions)?.second ?: error("no path") } private data class WizardSimulatorState( private val bossHitPoints: Int, private val wizardHitPoints: Int, private val wizardMana: Int, private val effects: List<Effect>, private val hard: Boolean ) { val isWin: Boolean get() = bossHitPoints <= 0 && wizardHitPoints > 0 private val isOver: Boolean get() = bossHitPoints <= 0 || wizardHitPoints <= 0 fun validTransitions(): List<Pair<WizardSimulatorState, Int>> { val state = applyPreTurnEffects(wizardTurn = true) return if (state.isOver) emptyList() else Spell.values().filter { state.mayCast(it) }.map { spell -> Pair(state.cast(spell).handleBossTurn(), spell.cost) } } private fun handleBossTurn(): WizardSimulatorState { val s = applyPreTurnEffects(wizardTurn = false) if (s.isOver) return s val armor = if (s.isActive(EffectType.SHIELD)) 7 else 0 return s.copy( wizardHitPoints = s.wizardHitPoints - (8 - armor).coerceAtLeast(1), ) } private fun applyPreTurnEffects(wizardTurn: Boolean) = copy( bossHitPoints = bossHitPoints - if (isActive(EffectType.POISON)) 3 else 0, wizardMana = wizardMana + if (isActive(EffectType.RECHARGE)) 101 else 0, effects = effects.mapNotNull { it.decrease() }, wizardHitPoints = wizardHitPoints - if (hard && wizardTurn) 1 else 0 ) private fun cast(spell: Spell) = copy( bossHitPoints = bossHitPoints - spell.damage, wizardHitPoints = wizardHitPoints + spell.heal, wizardMana = wizardMana - spell.cost, effects = if (spell.effect != null) effects + Effect(spell.effect) else effects ) private fun mayCast(spell: Spell) = wizardMana >= spell.cost && (spell.effect == null || !isActive(spell.effect)) private fun isActive(effect: EffectType) = effects.any { it.type == effect } } private enum class Spell(val cost: Int, val damage: Int = 0, val heal: Int = 0, val effect: EffectType? = null) { MAGIC_MISSILE(cost = 53, damage = 4), DRAIN(cost = 73, damage = 2, heal = 2), SHIELD(cost = 113, effect = EffectType.SHIELD), POISON(cost = 173, effect = EffectType.POISON), RECHARGE(cost = 229, effect = EffectType.RECHARGE); } private enum class EffectType(val turns: Int) { SHIELD(turns = 6), POISON(turns = 6), RECHARGE(turns = 5); } private data class Effect(val type: EffectType, val turns: Int = type.turns) { fun decrease() = if (turns == 1) null else Effect(type, turns - 1) }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
3,053
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxValueBoundedArray.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 /** * 1802. Maximum Value at a Given Index in a Bounded Array * @see <a href="https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/">Source</a> */ fun interface MaxValueBoundedArray { fun maxValue(n: Int, index: Int, maxSum: Int): Int } /** * Approach: Greedy + Binary Search */ class MaxValueBoundedArraySolution : MaxValueBoundedArray { override fun maxValue(n: Int, index: Int, maxSum: Int): Int { var left = 1 var right = maxSum while (left < right) { val mid = (left + right + 1) / 2 if (getSum(index, mid, n) <= maxSum) { left = mid } else { right = mid - 1 } } return left } private fun getSum(index: Int, value: Int, n: Int): Long { var count: Long = 0 // On index's left: // If value > index, there are index + 1 numbers in the arithmetic sequence: // [value - index, ..., value - 1, value]. // Otherwise, there are value numbers in the arithmetic sequence: // [1, 2, ..., value - 1, value], plus a sequence of length (index - value + 1) of 1s. count += if (value > index) { (value + value - index).toLong() * (index + 1) / 2 } else { (value + 1).toLong() * value / 2 + index - value + 1 } // On index's right: // If value >= n - index, there are n - index numbers in the arithmetic sequence: // [value, value - 1, ..., value - n + 1 + index]. // Otherwise, there are value numbers in the arithmetic sequence: // [value, value - 1, ..., 1], plus a sequence of length (n - index - value) of 1s. count += if (value >= n - index) { (value + value - n + 1 + index).toLong() * (n - index) / 2 } else { (value + 1).toLong() * value / 2 + n - index - value } return count - value } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,594
kotlab
Apache License 2.0
advent-of-code-2023/src/main/kotlin/Day02.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
// Day 2: Cube Conundrum // https://adventofcode.com/2023/day/2 import java.io.File import kotlin.math.max private const val RED = "red" private const val GREEN = "green" private const val BLUE = "blue" private const val COLON = ":" private const val COMMA = "," private const val SEMI_COLON = ";" fun main() { val lines = File("src/main/resources/Day02.txt").readLines() val sumOfIds = lines.sumOf { line -> if (isPossible(line.substringAfter(COLON))) { line.substringAfter("Game ").substringBefore(COLON).toInt() } else { 0 } } println(sumOfIds) val powers = lines.sumOf { line -> getPowerSet(line.substringAfter(COLON)) } println(powers) } private fun isPossible(line: String): Boolean { line.split(SEMI_COLON).forEach { draw -> draw.split(COMMA).forEach { cube -> if (cube.endsWith(RED) && cube.substringBefore(RED).trim().toInt() > 12) { return false } else if (cube.endsWith(GREEN) && cube.substringBefore(GREEN).trim().toInt() > 13) { return false } else if (cube.endsWith(BLUE) && cube.substringBefore(BLUE).trim().toInt() > 14) { return false } } } return true } private fun getPowerSet(line: String): Int { var redPower = 0 var greenPower = 0 var bluePower = 0 line.split(SEMI_COLON).forEach { draw -> draw.split(COMMA).forEach { cube -> if (cube.endsWith(RED)) { redPower = max(redPower, cube.substringBefore(RED).trim().toInt()) } else if (cube.endsWith(GREEN)) { greenPower = max(greenPower, cube.substringBefore(GREEN).trim().toInt()) } else if (cube.endsWith(BLUE)) { bluePower = max(bluePower, cube.substringBefore(BLUE).trim().toInt()) } } } return redPower * greenPower * bluePower }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
1,956
advent-of-code
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/combination_sum/CombinationSum.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.combination_sum import datsok.shouldEqual import org.junit.Test class CombinationSumTests { @Test fun `find all unique combinations where numbers sum up to target`() { emptyList<Int>().combinations(target = 1) shouldEqual emptyList() listOf(1).combinations(target = 0) shouldEqual listOf(emptyList()) listOf(1).combinations(target = 1) shouldEqual listOf(listOf(1)) listOf(1).combinations(target = 2) shouldEqual listOf(listOf(1, 1)) listOf(1, 2).combinations(target = 2) shouldEqual listOf(listOf(1, 1), listOf(2)) listOf(2, 3, 6, 7).combinations(target = 7) shouldEqual listOf(listOf(2, 2, 3), listOf(7)) listOf(2, 3, 5).combinations(target = 8) shouldEqual listOf(listOf(2, 2, 2, 2), listOf(2, 3, 3), listOf(3, 5)) listOf(100).combinations(target = 1) shouldEqual emptyList() } } private fun List<Int>.combinations(target: Int): List<List<Int>> = when { target == 0 -> listOf(emptyList()) target < 0 || isEmpty() -> emptyList() else -> combinations(target - first()).map { listOf(first()) + it } + drop(1).combinations(target) } private fun List<Int>.combinations_(target: Int): List<List<Int>> { return mapIndexed { index, n -> when { n == target -> listOf(listOf(n)) n < target -> subList(index, size).combinations(target - n).map { listOf(n) + it } else -> emptyList() } }.flatten() }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,583
katas
The Unlicense
src/main/kotlin/Day01.kt
rogierbom1
573,165,407
false
{"Kotlin": 5253}
package main.kotlin import readInput data class Snack(var calories: Int) data class Elf(var snacks: List<Snack>) private fun Elf.totalCalories() = snacks.sumOf { it.calories } private fun List<String>.toElves(): List<Elf> = this.flatMapIndexed { index, calories -> when { index == 0 || index == lastIndex -> listOf(index) calories.isEmpty() -> listOf(index - 1, index + 1) else -> emptyList() } }.windowed(2, 2) { (from, to) -> this.slice(from..to) }.map { stringList -> Elf( snacks = stringList.map { stringValue -> Snack(stringValue.toInt()) } ) } fun main() { fun part1(input: List<String>): Int = input.toElves().maxOf { elf -> elf.totalCalories() } fun part2(input: List<String>): Int = input.toElves().sortedByDescending { elf -> elf.totalCalories() }.take(3).sumOf { elf -> elf.totalCalories() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b7a03e95785cb4a2ec0bfa170f4f667fc574c1d2
1,158
aoc-2022-in-kotlin
Apache License 2.0
src/Day25.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
fun main() { val digits = mapOf('2' to 2L, '1' to 1L, '0' to 0L, '-' to -1L, '=' to -2L) val revDigits = mapOf(2L to '2', 1L to '1', 0L to '0', -1L to '-', -2L to '=') fun fromFiveBalanced(line: String): Long { var power = 1L var value = 0L line.reversed().forEach { value += power * (digits[it] ?: error("Wrong char")) power *= 5L } return value } fun toFiveBalanced(value: Long): String { val result = StringBuilder() var valueCopy = value while (valueCopy > 0L) { var rawRec = valueCopy % 5L if (rawRec >= 3L) { rawRec -= 5L valueCopy += 5 } result.append(revDigits[rawRec]) valueCopy /= 5L } return result.reversed().toString() } fun part1(input: List<String>): String { return toFiveBalanced(input.sumOf { fromFiveBalanced(it)} ) } fun part2(input: List<String>): String { return "Merry Christmas!!" } // test if implementation meets criteria from the description, like: val testInput = readInput("Day25_test") check(part1(testInput) == "2=-1=0") // check(part2(testInput) == TODO()) val input = readInput("Day25") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
1,351
advent-of-kotlin-2022
Apache License 2.0
src/Day02.kt
KristianAN
571,726,775
false
{"Kotlin": 9011}
fun main() { fun part1(input: List<String>): Int = input.fold(0) { acc, s -> val moves = s.split(" ") acc + play(Move.fromInput(moves[0]), Move.fromInput(moves[1])) } fun part2(input: List<String>): Int = input.fold(0) { acc, s -> val moves = s.split(" ") acc + decode(Move.fromInput(moves[0]), Move.fromInput(moves[1])) } // test if implementation meets criteria from the description, like: val input = readInput("day02") println(part1(input)) println(part2(input)) } enum class Move(val value: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun fromInput(input: String): Move = when (input) { "A", "X"-> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> throw Exception("Invalid input: $input") } } } fun play(move1: Move, move2: Move): Int = when (move1) { Move.ROCK -> if (move2 == Move.ROCK) move2.value + 3 else if (move2 == Move.PAPER) move2.value + 6 else move2.value Move.PAPER -> if (move2 == Move.PAPER) move2.value + 3 else if (move2 == Move.SCISSORS) move2.value + 6 else move2.value Move.SCISSORS -> if (move2 == Move.SCISSORS) move2.value + 3 else if (move2 == Move.ROCK) move2.value + 6 else move2.value } fun decode(move1: Move, move2: Move): Int = when (move1) { Move.ROCK -> if (move2 == Move.ROCK) Move.SCISSORS.value else if (move2 == Move.PAPER) Move.ROCK.value + 3 else Move.PAPER.value + 6 Move.PAPER -> if (move2 == Move.ROCK) Move.ROCK.value else if (move2 == Move.PAPER) Move.PAPER.value + 3 else Move.SCISSORS.value + 6 Move.SCISSORS -> if (move2 == Move.ROCK) Move.PAPER.value else if (move2 == Move.PAPER) Move.SCISSORS.value + 3 else Move.ROCK.value + 6 }
0
Kotlin
0
0
3a3af6e99794259217bd31b3c4fd0538eb797941
1,852
AoC2022Kt
Apache License 2.0
src/Day05.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
class Depot { private val stacks = mutableListOf<ArrayDeque<Char>>() private val moves = mutableListOf<Move>() fun setup(stackCount: Int) { repeat(stackCount) { stacks.add(ArrayDeque()) } } fun add(stackNumber: Int, crate: Char) = stacks[stackNumber - 1].addLast(crate) fun add(move: Move) = moves.add(move) fun applyMoves(move: Depot.(Move) -> Unit) { moves.forEach { move(it) } } fun moveOneByOne(move: Move) { repeat(move.amount) { stacks[move.destination - 1].addLast(stacks[move.source - 1].removeLast()) } } fun moveAll(move: Move) { val moving = mutableListOf<Char>() repeat(move.amount) { moving.add(stacks[move.source - 1].removeLast()) } moving.reverse() stacks[move.destination - 1].addAll(moving) } fun result(): String { return buildString { stacks.forEach { append(it.last()) } } } } class Move(val amount: Int, val source: Int, val destination: Int) { companion object { private val MoveParser = """move ([0-9]+) from ([0-9]+) to ([0-9]+)""".toRegex() fun from(line: String): Move { val result = MoveParser.find(line) ?: error("Invalid input") return Move(result.groups[1]!!.value.toInt(), result.groups[2]!!.value.toInt(), result.groups[3]!!.value.toInt()) } } } fun parseDepot(input: List<String>): Depot { val depot = Depot() val depotLines = mutableListOf<String>() val (initial, moves) = input.partition { line -> !line.startsWith("move") } for (line in initial) { if (line.startsWith(" 1")) { val count = line.trim().last().digitToInt() depot.setup(count) depotLines.reverse() depotLines.forEach { depotLine -> for (index in 1..count) { val pos = 1 + ((index - 1) * 4) if (pos < depotLine.length) { val char = depotLine[pos] if (char != ' ') depot.add(index, char) } } } } else if (line.isNotBlank()) { depotLines.add(line) } } moves.forEach { line -> depot.add(Move.from(line)) } return depot } fun main() { fun part1(input: List<String>): String { val depot = parseDepot(input) depot.applyMoves(Depot::moveOneByOne) return depot.result() } fun part2(input: List<String>): String { val depot = parseDepot(input) depot.applyMoves(Depot::moveAll) return depot.result() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") val input = readInput("Day05") check(part1(input) == "PSNRGBTFT") check(part2(input) == "BNTZFPMMW") }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
3,000
advent-of-code-kotlin-2022
Apache License 2.0
src/Day08.kt
Oli2861
572,895,182
false
{"Kotlin": 16729}
fun getNumList(input: List<String>) = input.map { line -> line.toCharArray().map { character -> character.digitToInt() } } fun getAmountOfVisibleTrees(input: List<String>): Int { val numList = getNumList(input) val isVisibleList: List<MutableList<Boolean>> = numList.map { it.map { false }.toMutableList() } val lastVisibleInColumn: MutableList<Int> = numList.first().toMutableList() val lastVisibleFromBottom: MutableList<Int> = numList.last().toMutableList() for (rowIndex in numList.indices) { var lastVisibleInRow = 0 var lastVisibleFromBack = 0 for (columnIndex in numList[rowIndex].indices) { // Compare to last visible in row. if (lastVisibleInRow < numList[rowIndex][columnIndex] || columnIndex == 0) { lastVisibleInRow = numList[rowIndex][columnIndex] isVisibleList[rowIndex][columnIndex] = true } // Compare from back. val indexFromBack = numList[rowIndex].size - columnIndex - 1 if (lastVisibleFromBack < numList[rowIndex][indexFromBack] || indexFromBack == numList[rowIndex].size - 1) { lastVisibleFromBack = numList[rowIndex][indexFromBack] isVisibleList[rowIndex][indexFromBack] = true } // Compare to last visible in column. if (lastVisibleInColumn[columnIndex] < numList[rowIndex][columnIndex] || rowIndex == 0) { lastVisibleInColumn[columnIndex] = numList[rowIndex][columnIndex] isVisibleList[rowIndex][columnIndex] = true } // Compare from bottom. val rowIndexFromBottom = numList.size - rowIndex - 1 if (lastVisibleFromBottom[columnIndex] < numList[rowIndexFromBottom][columnIndex] || rowIndexFromBottom == numList.size - 1) { lastVisibleFromBottom[columnIndex] = numList[rowIndexFromBottom][columnIndex] isVisibleList[rowIndexFromBottom][columnIndex] = true } } } return isVisibleList.map { list -> list.map { if (it) 1 else 0 } }.sumOf { it.sum() } } fun main() { val test = listOf( "30373", "25512", "65332", "33549", "35390" ) println(getAmountOfVisibleTrees(test)) println("-------") val input = readInput("Day08_test") val result = getAmountOfVisibleTrees(input) println(result) check(result == 1669) }
0
Kotlin
0
0
138b79001245ec221d8df2a6db0aaeb131725af2
2,480
Advent-of-Code-2022
Apache License 2.0
kotlin/combinatorics/BinomialCoefficients.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package combinatorics import java.math.BigInteger object BinomialCoefficients { fun binomialTable(n: Int): Array<LongArray> { val c = Array(n + 1) { LongArray(n + 1) } for (i in 0..n) for (j in 0..i) c[i][j] = if (j == 0) 1 else c[i - 1][j - 1] + c[i - 1][j] return c } fun binomial(n: Long, m: Long): Long { var m = m m = Math.min(m, n - m) var res: Long = 1 for (i in 0 until m) { res = res * (n - i) / (i + 1) } return res } // for (int i = 1; i < f.length; i++) f[i] = f[i - 1] + Math.log(i); fun binomial(n: Int, m: Int, f: DoubleArray): Double { return if (m < 0 || m > n) 0 else Math.exp(f[n] - f[m] - f[n - m]) } // n! % mod fun factorial(n: Int, mod: Int): Int { var res: Long = 1 for (i in 2..n) res = res * i % mod return (res % mod).toInt() } // n! mod p, p - prime, O(p*log(n)) complexity fun factorial2(n: Int, p: Int): Int { var n = n var res = 1 while (n > 1) { res = res * if (n / p % 2 == 1) p - 1 else 1 % p for (i in 2..n % p) res = res * i % p n /= p } return res % p } // fact[0] = ifact[0] = fact[1] = ifact[1] = inv[1] = 1; // for (int i = 2; i < fact.length; i++) // fact[i] = (int)c((long) fact[i - 1] * i % mod); // inv[i] = (int) ((long) (p - p / i) * inv[p % i] % p); // ifact[i] = (int)c((long) ifact[i - 1] * inv[i] % mod); fun binomial(n: Int, m: Int, fact: IntArray, ifact: IntArray, mod: Int): Int { return (fact[n].toLong() * ifact[m] % mod * ifact[n - m] % mod).toInt() } // Usage example fun main(args: Array<String?>?) {} }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,764
codelibrary
The Unlicense
src/Day25.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
import kotlin.math.abs import kotlin.math.pow infix fun Long.`**`(exponent: Int): Long = toDouble().pow(exponent).toLong() val powersOf5 = (0..20).map { 5L `**` it } val powersOf5Max = (0..20).map { (0..it).sumOf { p -> 2 * powersOf5[p] } } fun main() { fun parseSnafuToDecimal(snafu: String): Long { return snafu.reversed().mapIndexed { i, it -> if (it.isDigit()) { it.digitToInt() * powersOf5[i] } else { when (it) { '=' -> -2 * powersOf5[i] '-' -> -1 * powersOf5[i] else -> throw Exception("Unknown SNAFU digit") } } }.sum() } fun convertDecimalToSnafu(n: Long): String { val digits = mutableListOf<Char>() var remaining = abs(n) // todo; do we need to worry about negatives? // var powerIndex = powersOf5.indexOfFirst { n <= 2*it } // 1=-0-2 = 1747 // 3,125 + (-2 * 625) + (-1 * 125) + (0) + (-1 * 5) + 2 for (powerIndex in powersOf5.lastIndex downTo 1) { val currentPower = powersOf5[powerIndex] val currentPowerTwoMax = powersOf5Max[powerIndex] val nextLowerPowerMax = powersOf5Max[powerIndex-1] val currentPowerOneMax = nextLowerPowerMax + currentPower if (remaining == 0L) { digits.add('0') continue } // current value is too high, because we had to go up a power if (remaining < 0L) { // if what we have left fits in the next lower power, add a 0 here if (abs(remaining) <= nextLowerPowerMax) { digits.add('0') continue } if (abs(remaining) <= currentPowerOneMax) { digits.add('-') remaining += currentPower continue } if (abs(remaining) <= currentPowerTwoMax) { digits.add('=') remaining += currentPower * 2 continue } } // if what we have left fits in the next lower power, add a 0 here if (remaining <= nextLowerPowerMax) { digits.add('0') continue } if (remaining <= currentPowerOneMax) { // but it fits in 1x currentPower digits.add('1') remaining -= currentPower continue } if (remaining <= currentPowerTwoMax) { // it must fit in 2x currentPower digits.add('2') remaining -= currentPower * 2 continue } } when (remaining) { 2L -> { digits.add('2') } 1L -> { digits.add('1') } 0L -> { digits.add('0') } -1L -> { digits.add('-') } -2L -> { digits.add('=') } else -> throw Exception("BUG: I got a remainder of $remaining") } val firstNonZero = digits.indexOfFirst { it != '0' } return digits.drop(if (firstNonZero == -1) 0 else firstNonZero).joinToString("") } fun part1(input: List<String>): Long { listOf(1,2,3,4,5,6,7,8,9,10, 15, 20, 2022, 12345, 314159265).forEach { print("$it = ") print(convertDecimalToSnafu(it.toLong())) println() } val sum = input.sumOf { parseSnafuToDecimal(it) } println("Answer for $sum is ${convertDecimalToSnafu(sum)}") return sum } // fun part2(input: List<String>): Long { // return input.size.toLong() // } // test if implementation meets criteria from the description, like: val testInput = readInput("Day25_test") check(part1(testInput) == 4890L) println("Part 1 checked out!") // check(part2(testInput) == 1L) // println("Part 2 checked out!") val input = readInput("Day25") println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
4,117
advent-of-code-2022
Apache License 2.0
src/year2022/day08/Day08.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day08 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day08_test") check(part1(testInput), 21) check(part2(testInput), 8) val input = readInput("2022", "Day08") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { return parseTreeMap(input).countVisibleTrees() } private fun part2(input: List<String>): Int { return parseTreeMap(input).getHighestTreeScenicScore() } private fun parseTreeMap(input: List<String>): List<List<Int>> { return input.map { line -> line.map { it.digitToInt() } } } private fun List<List<Int>>.countVisibleTrees(): Int { val maxY = lastIndex val maxX = first().lastIndex var count = 2 * (maxY + maxX) for (y in 1 until maxY) { for (x in 1 until maxX) { if (isVisible(y, x)) count++ } } return count } private fun List<List<Int>>.isVisible(y: Int, x: Int): Boolean { val height = get(y)[x] var isVisibleTop = true var isVisibleBottom = true var isVisibleLeft = true var isVisibleRight = true for (topY in 0 until y) { if (get(topY)[x] >= height) { isVisibleTop = false break } } if (isVisibleTop) return true for (bottomY in y + 1..lastIndex) { if (get(bottomY)[x] >= height) { isVisibleBottom = false break } } if (isVisibleBottom) return true for (leftX in 0 until x) { if (get(y)[leftX] >= height) { isVisibleLeft = false break } } if (isVisibleLeft) return true for (rightX in x + 1..first().lastIndex) { if (get(y)[rightX] >= height) { isVisibleRight = false break } } return isVisibleRight } private fun List<List<Int>>.getHighestTreeScenicScore(): Int { val maxY = lastIndex val maxX = first().lastIndex val scores = mutableListOf<Int>() for (y in 1 until maxY) { for (x in 1 until maxX) { scores += computeTreeScenicScore(y, x) } } return scores.max() } private fun List<List<Int>>.computeTreeScenicScore(y: Int, x: Int): Int { val height = get(y)[x] var countTop = 0 var countBottom = 0 var countLeft = 0 var countRight = 0 for (topY in (0 until y).reversed()) { countTop++ if (get(topY)[x] >= height) break } for (bottomY in (y + 1..lastIndex)) { countBottom++ if (get(bottomY)[x] >= height) break } for (leftX in (0 until x).reversed()) { countLeft++ if (get(y)[leftX] >= height) break } for (rightX in x + 1..first().lastIndex) { countRight++ if (get(y)[rightX] >= height) break } return countTop * countBottom * countLeft * countRight }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,947
AdventOfCode
Apache License 2.0
src/main/kotlin/days/y2023/day21/Day21.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day21 import util.InputReader typealias PuzzleLine = String typealias PuzzleInput = List<PuzzleLine> class Day21(val input: PuzzleInput) { data class Position( val y: Int, val x: Int, ) operator fun PuzzleInput.get(at: Position): Char { return this[at.y][at.x] } fun partOne(n: Int): Int { val positions = input.positions() val s = positions.first { input[it] == 'S' } var lastGeneration = mutableSetOf(s) println(printable(input, lastGeneration)) for (i in 1..n) { val nextGeneration = input.notRocks().filter { position -> input.neighborsAt(position).intersect(lastGeneration).isNotEmpty() } // println(printable(input, nextGeneration)) lastGeneration = nextGeneration.toMutableSet() } return lastGeneration.size } private fun printable(input: PuzzleInput, generation: Collection<Position>): String { val genSet = generation.toSet() return input.mapIndexed { y, row -> row.mapIndexed { x, c -> when { input.rocks().contains(Position(x, y)) -> '#' genSet.contains(Position(x, y)) -> 'O' else -> c } }.joinToString("") }.joinToString("\n") } } private fun Day21.Position.neighbors(w: Int, h: Int): Set<Day21.Position> { return setOf( Day21.Position(x - 1, y), Day21.Position(x + 1, y), Day21.Position(x, y - 1), Day21.Position(x, y + 1) ).filter { it.x in 0 until w && it.y in 0 until h }.toSet() } val rocksCache = mutableMapOf<PuzzleInput, Set<Day21.Position>>() private fun PuzzleInput.rocks(): Set<Day21.Position> { return rocksCache.getOrPut(this) { positions().filter { this[it.y][it.x] == '#' }.toSet() } } val notRocksCache = mutableMapOf<String, Set<Day21.Position>>() private fun PuzzleInput.notRocks(): Set<Day21.Position> { return notRocksCache.getOrPut(this.joinToString("")) { positions().toSet() - rocks().toSet() } } val neighborsCache = mutableMapOf<String, Map<Day21.Position, Set<Day21.Position>>>() private fun PuzzleInput.neighbors(): Map<Day21.Position, Set<Day21.Position>> { return neighborsCache.getOrPut(this.joinToString("")) { positions().associateWith { position -> position.neighbors(w = width(), h = height()) - rocks() } } } private fun PuzzleInput.width(): Int { return this[0].length } private fun PuzzleInput.height(): Int { return this.size } val positionsCache = mutableMapOf<String, Collection<Day21.Position>>() private fun PuzzleInput.positions(): Collection<Day21.Position> { return positionsCache.getOrPut(this.joinToString("")) { flatMapIndexed { y, row -> row.mapIndexed { x, _ -> (Day21.Position(x, y)) } } } } private fun PuzzleInput.neighborsAt(position: Day21.Position): Set<Day21.Position> { return neighbors()[position]!! } fun main() { val year = 2023 val day = 21 val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day) println(exampleInput) val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day) fun partOne(input: PuzzleInput, n: Int = 64) = Day21(input).partOne(n) // println("Example 1: ${partOne(exampleInput, 6)}") print("Part 1: ${partOne(puzzleInput, 65)}") }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
3,523
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/org/example/adventofcode/puzzle/Day03.kt
peterlambrechtDev
573,146,803
false
{"Kotlin": 39213}
package org.example.adventofcode.puzzle import org.example.adventofcode.util.FileLoader class Group { private val elves : List<String> constructor(elves: List<String>) { this.elves = elves } fun intersect(): String { var intersectSet = emptySet<Char>() for (elf in elves) { if (intersectSet.isEmpty()) { intersectSet = elf.toSet() } else { intersectSet = intersectSet.intersect(elf.toSet()) } } return intersectSet.toList().first().toString() } } object Day03 { fun part1(filePath: String): Int { val stringLines = FileLoader.loadFromFile<String>(filePath) var priorities = priorities() println(priorities) var sum = 0 for (line in stringLines) { val trimmedLine = line.trim() if (trimmedLine.length > 0) { val halfwayPoint = (trimmedLine.length / 2) - 1 val rs1 = trimmedLine.slice(0..halfwayPoint).toSet() val rs2 = trimmedLine.slice(halfwayPoint + 1..trimmedLine.length - 1).toSet() val intersect = rs1.intersect(rs2) sum += priorities[intersect.toList()[0].toString()]!!.toInt() } } return sum } fun part2(filePath: String): Int { val stringLines = FileLoader.loadFromFile<String>(filePath) var priorities = priorities() val chunked = stringLines.chunked(3) val groups = mutableListOf<Group>() chunked.forEach { groups.add(Group(it)) } var sum = 0 groups.forEach { sum += priorities.get(it.intersect())!!.toInt() } return sum } fun priorities(): Map<String, Int> { var c = 'a' var priority = 1 var map = mutableMapOf<String, Int>() while (c <= 'z') { map.put(c.toString(), priority) priority++ ++c } c = 'A' while (c <= 'Z') { map.put(c.toString(), priority) priority++ ++c } return map } } fun main() { var day = "day03" println("Example 1: ${Day03.part1("/${day}_example.txt")}") println("Solution 1: ${Day03.part1("/${day}.txt")}") println("Example 2: ${Day03.part2("/${day}_example.txt")}") println("Solution 2: ${Day03.part2("/${day}.txt")}") }
0
Kotlin
0
0
aa7621de90e551eccb64464940daf4be5ede235b
2,426
adventOfCode2022
MIT License
src/main/kotlin/hu/advent/of/code/year2022/day11/Puzzle11A.kt
sztojkatamas
568,512,275
false
{"Kotlin": 157914}
package hu.advent.of.code.year2022.day11 import hu.advent.of.code.AdventOfCodePuzzle import hu.advent.of.code.BaseChallenge import kotlin.math.floor @AdventOfCodePuzzle class Puzzle11A: BaseChallenge(2022) { override fun run() { printPuzzleName() loadDataFromFile("data11.txt") val monkeys = buildMonkeys(data) repeat(20) { monkeys.doTheMonkeyBusiness(true) } val mm = monkeys.sortedByDescending { it.inspection } println("Level of monkey business wih calming: ${mm[0].inspection * mm[1].inspection}") } } fun buildMonkeys(input: List<String>): List<Monkey> { val monkeyList = mutableListOf<Monkey>() input.forEachIndexed { index, s -> if (s.startsWith("Monkey")) { val cheeta = Monkey(s.lowercase().dropLast(1)) monkeyList.add(cheeta) val items = input[index+1].split(":")[1].trim().split(", ") items.forEach { cheeta.addItem(it.toDouble()) } cheeta.operand = input[index+2].split("= old ")[1].split(" ") cheeta.divBy = input[index+3].split(" ").last().toDouble() cheeta.trueMonkey = input[index+4].split(" to ")[1].lowercase() cheeta.falseMonkey = input[index+5].split(" to ")[1].lowercase() } } return monkeyList } fun List<Monkey>.getMonkey(name: String): Monkey { return this.find { it.name == name.lowercase() }!! } fun List<Monkey>.doTheMonkeyBusiness(calmDown: Boolean) { var supermod = 1.0 this.forEach { supermod *= it.divBy } this.forEachIndexed { _, monkey -> monkey.items.forEachIndexed { _, it -> var x = monkey.changeWorryLevel(it) if (calmDown) { //x /= 3 x = floor(x/3) } else { x %= supermod } if (x.mod(monkey.divBy) == 0.0) { this.getMonkey(monkey.trueMonkey).items.add(x) } else { this.getMonkey(monkey.falseMonkey).items.add(x) } } monkey.inspection += monkey.items.count().toLong() monkey.items.clear() } } class Monkey(val name: String) { val items = mutableListOf<Double>() var operand = listOf<String>() var divBy = 0.0 var trueMonkey = "" var falseMonkey = "" var inspection = 0L fun addItem(item: Double) { items.add(item) } fun changeWorryLevel(input: Double): Double { val op2 = when (operand[1]) { "old" -> input else -> operand[1].toDouble() } return when (operand[0]) { "+" -> input.plus(op2) "*" -> input.times(op2) else -> { -1000.0 } } } }
0
Kotlin
0
0
6aa9e53d06f8cd01d9bb2fcfb2dc14b7418368c9
2,728
advent-of-code-universe
MIT License