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/day08/Day08.kt | commanderpepper | 574,647,779 | false | {"Kotlin": 44999} | package day08
import readInput
fun main(){
val day08Input = readInput("day08")
println(day08Input)
val trees : List<List<Tree>> = day08Input.mapIndexed {rowIndex, row ->
row.mapIndexed { colIndex, height ->
Tree(height = height.toString().toInt(), row = rowIndex, col = colIndex)
}
}
println("Edge trees: ${trees.countEdgeTrees()}")
println("Inner visible: ${trees.countVisibleTrees()}")
println(trees.countEdgeTrees() + trees.countVisibleTrees())
println("Highest scenic value is ${trees.findHighestScenicValue()}")
}
data class Tree(val height: Int, val row: Int, val col: Int)
private fun List<List<Tree>>.countEdgeTrees(): Int {
var edgeTrees = 0
this.forEach { trees ->
trees.forEach { tree ->
if(tree.isOnEdge(rightEdge = trees.size - 1, bottomEdge = this.size - 1)){
edgeTrees++
}
}
}
return edgeTrees
}
private fun List<List<Tree>>.countVisibleTrees(): Int {
var visibleTrees = 0
this.forEach { trees ->
trees.forEach { tree ->
// If tree is not on edge then check if tree is visible
if(tree.isOnEdge(rightEdge = trees.size - 1, bottomEdge = this.size - 1).not()){
val topTrees = this.getTopTrees(tree)
val isVisibleFromTop = tree.isVisible(topTrees)
val bottomTrees = this.getBottomTrees(tree)
val isVisibleFromBottom = tree.isVisible(bottomTrees)
val leftTrees = this.getLeftTrees(tree)
val isVisibleFromLeft = tree.isVisible(leftTrees)
val rightTrees = this.getRightTrees(tree)
val isVisibleFromRight = tree.isVisible(rightTrees)
if(isVisibleFromTop || isVisibleFromBottom || isVisibleFromLeft || isVisibleFromRight){
visibleTrees++
}
}
}
}
return visibleTrees
}
private fun List<List<Tree>>.findHighestScenicValue(): Int {
var highestScenicValue = Int.MIN_VALUE
this.forEach { trees ->
trees.forEach { tree ->
if(tree.isOnEdge(rightEdge = trees.size - 1, bottomEdge = this.size - 1).not()) {
val topTrees = this.getTopTrees(tree)
val bottomTrees = this.getBottomTrees(tree)
val leftTrees = this.getLeftTrees(tree)
val rightTrees = this.getRightTrees(tree)
val topScenicValue = tree.countVisibleTrees(topTrees)
val bottomScenicValue = tree.countVisibleTrees(bottomTrees)
val leftScenicValue = tree.countVisibleTrees(leftTrees)
val rightScenicValue = tree.countVisibleTrees(rightTrees)
val treeScenicValue = topScenicValue * bottomScenicValue * leftScenicValue * rightScenicValue
if(treeScenicValue > highestScenicValue){
highestScenicValue = treeScenicValue
}
}
}
}
return highestScenicValue
}
private fun List<List<Tree>>.getTopTrees(startingTree: Tree): List<Tree> {
val topTrees = mutableListOf<Tree>()
for(i in startingTree.row - 1 downTo 0){
topTrees.add(this[i][startingTree.col])
}
return topTrees
}
private fun List<List<Tree>>.getBottomTrees(startingTree: Tree): List<Tree> {
val bottomTrees = mutableListOf<Tree>()
for(i in startingTree.row + 1 until this.size){
bottomTrees.add(this[i][startingTree.col])
}
return bottomTrees
}
private fun List<List<Tree>>.getLeftTrees(startingTree: Tree): List<Tree> {
val leftTrees = mutableListOf<Tree>()
for(i in startingTree.col - 1 downTo 0){
leftTrees.add(this[startingTree.row][i])
}
return leftTrees
}
private fun List<List<Tree>>.getRightTrees(startingTree: Tree): List<Tree> {
val rightTrees = mutableListOf<Tree>()
for(i in startingTree.col + 1 until this.first().size){
rightTrees.add(this[startingTree.row][i])
}
return rightTrees
}
private fun Tree.countVisibleTrees(treeLine: List<Tree>): Int {
var visibleTrees = 0
check@for(element in treeLine){
if(this.height > element.height){
visibleTrees++
}
if(this.height == element.height){
visibleTrees++
break@check
}
if(this.height < element.height){
visibleTrees++
break@check
}
}
return visibleTrees
}
private fun Tree.isVisible(treeLine: List<Tree>): Boolean {
return treeLine.all { this.height > it.height }
}
private fun Tree.isOnEdge(leftEdge: Int = 0, rightEdge: Int, topEdge: Int = 0, bottomEdge: Int): Boolean {
return this.col == leftEdge || this.col == rightEdge || this.row == topEdge || this.row == bottomEdge
} | 0 | Kotlin | 0 | 0 | fef291c511408c1a6f34a24ed7070ceabc0894a1 | 4,837 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/BeautifulPartitions.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import kotlin.math.max
/**
* 2478. Number of Beautiful Partitions
* @see <a href="https://leetcode.com/problems/number-of-beautiful-partitions">Source</a>
*/
fun interface BeautifulPartitions {
operator fun invoke(s: String, k: Int, minLength: Int): Int
}
class BeautifulPartitionsDP : BeautifulPartitions {
override operator fun invoke(s: String, k: Int, minLength: Int): Int {
val cs: CharArray = s.toCharArray()
val n = cs.size
// make sure the input is valid
if (!prime(cs[0]) || prime(cs[n - 1])) return 0
val dp = Array(k) { IntArray(n) }
// base case. If k = 1, the only thing required is to check if a character is prime
var i: Int = n - minLength
while (0 <= i) {
dp[0][i] = if (prime(cs[i])) 1 else 0
--i
}
for (i1 in 1 until k) {
// re-use dp[k - 1][] and compute the `prefix sum` backwards
// sum is the number of valid end points
run {
var j: Int = n - i1 * minLength
var sum = 0
while (0 <= j) {
// if dp[][] is 0, store the sum. othewise, it could be a possible valid end point.
if (0 == dp[i1 - 1][j]) {
dp[i1 - 1][j] = sum
} else if (0 != j && 0 == dp[i1 - 1][j - 1]) {
sum = (sum + dp[i1 - 1][j]) % MOD
}
--j
}
}
// use 2 pointers [j, p] to find a valid substring
var j = 0
var p: Int = minLength - 1
while (j + minLength * i1 < n) {
if (!prime(cs[j])) {
++j
continue
}
p = max(p, j + minLength - 1)
while (prime(cs[p])) p++ // boundary check is skipped as the last character is not prime
if (0 == dp[i1 - 1][p]) break // early break because there's no valid end points
dp[i1][j] = dp[i1 - 1][p]
++j
}
}
return dp[k - 1][0]
}
private fun prime(c: Char): Boolean {
return '2' == c || '3' == c || '5' == c || '7' == c
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,940 | kotlab | Apache License 2.0 |
src/Day09.kt | bin-wang | 572,801,360 | false | {"Kotlin": 19395} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class Point(val x: Int, val y: Int) {
fun move(direction: String) = when (direction) {
"U" -> Point(x, y + 1)
"D" -> Point(x, y - 1)
"L" -> Point(x - 1, y)
"R" -> Point(x + 1, y)
else -> error("Unexpected direction")
}
fun follow(other: Point) =
if (abs(other.x - x) <= 1 && abs(other.y - y) <= 1) {
this
} else {
Point(x + (other.x - x).sign, y + (other.y - y).sign)
}
}
fun part1(input: List<String>): Int {
val directions = input.flatMap {
val (direction, n) = it.split(" ")
List(n.toInt()) { direction }
}
val tailHistory = directions
.asSequence()
.scan(Pair(Point(0, 0), Point(0, 0))) { rope: Pair<Point, Point>, direction: String ->
val (head, tail) = rope
val newHead = head.move(direction)
val newTail = tail.follow(head)
Pair(newHead, newTail)
}
.map { it.second }
.toSet()
return tailHistory.size
}
fun part2(input: List<String>): Int {
val directions = input.flatMap { line ->
val (direction, n) = line.split(" ")
List(n.toInt()) { direction }
}
val tailHistory = directions
.asSequence()
.scan(List(10) { Point(0, 0) }) { rope: List<Point>, direction: String ->
val newHead = rope.first().move(direction)
rope.drop(1).scan(newHead) { prev: Point, point: Point ->
point.follow(prev)
}
}
.map { it.last() }
.toSet()
return tailHistory.size
}
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dca2c4915594a4b4ca2791843b53b71fd068fe28 | 1,952 | aoc22-kt | Apache License 2.0 |
kotlin/src/Day13.kt | ekureina | 433,709,362 | false | {"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386} | import java.lang.Integer.parseInt
import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val pairs = input.takeWhile { line -> line != "" }.map { line ->
val (x, y) = line.split(",")
parseInt(x) to parseInt(y)
}
val (type, value) = input
.dropWhile { line -> line != "" }
.drop(1)
.first()
.split(" ")
.last()
.split("=")
.let { (type, value) -> type to parseInt(value) }
return pairs.map { point ->
when (type) {
"x" -> {
(value - abs(value - point.first)) to point.second
}
"y" -> {
point.first to (value - abs(value - point.second))
}
else -> {
throw IllegalStateException("Wrong type of fold: $type")
}
}
}.toSet().size
}
fun part2(input: List<String>) {
val pairs = input.takeWhile { line -> line != "" }.map { line ->
val (x, y) = line.split(",")
parseInt(x) to parseInt(y)
}
val instructions = input
.dropWhile { line -> line != "" }
.drop(1)
.map { instructionLine ->
instructionLine
.split(" ")
.last()
.split("=")
.let { (type, value) -> type to parseInt(value) }
}
val points = instructions.fold(pairs.toSet()) { pairs, instruction ->
pairs.map { point ->
when (instruction.first) {
"x" -> {
(instruction.second - abs(instruction.second - point.first)) to point.second
}
"y" -> {
point.first to (instruction.second - abs(instruction.second - point.second))
}
else -> {
throw IllegalStateException("Wrong type of fold: ${instruction.first}")
}
}
}.toSet()
}
val dimensions = points.fold(Pair(0, 0)) { dimensions, point ->
Pair(maxOf(dimensions.first, point.first), maxOf(dimensions.second, point.second))
}
(0..dimensions.second).forEach { yCoord ->
(0..dimensions.first).forEach { xCoord ->
if (points.contains(Pair(xCoord, yCoord))) {
print("#")
} else {
print(".")
}
}
println()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 17) { "${part1(testInput)}" }
part2(testInput)
val input = readInput("Day13")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 1 | 391d0017ba9c2494092d27d22d5fd9f73d0c8ded | 2,968 | aoc-2021 | MIT License |
src/day07/Day07.kt | felldo | 572,762,654 | false | {"Kotlin": 104604} | package day07
import readInputString
data class File(val name: String, val size: Long)
class Directory(val parent: Directory?) {
val children = mutableMapOf<String, Directory>()
val files = mutableListOf<File>()
}
fun main() {
fun getDirectorySize(directory: Directory): Long {
var totalSize = directory.files.sumOf { it.size }
for (c in directory.children) {
totalSize += getDirectorySize(c.value)
}
return totalSize
}
fun getAllChildren(directory: Directory): List<Directory> {
return directory.children.values.flatMap { getAllChildren(it) } + directory
}
fun traverseDirectory(directory: Directory, path: String): Directory {
val dirs = path.split("/")
var currentDir = directory
for (d in dirs) {
if (d.isNotEmpty())
currentDir = currentDir.children[d]!!
}
return currentDir
}
fun readInput(root: Directory, input: List<String>) {
var currentDirectory = root
var currentLine = 0
while (currentLine < input.size) {
var line = input[currentLine]
if (line.substring(0, 4) == "$ cd") {
// Change directories
val newDirectory = line.split(" ")[2]
if (newDirectory[0] == '/') {
currentDirectory = traverseDirectory(root, newDirectory.substringAfter('/'))
} else if (newDirectory == ".." && currentDirectory.parent != null) {
currentDirectory = currentDirectory.parent!!
} else {
currentDirectory = traverseDirectory(currentDirectory, newDirectory)
}
currentLine++
} else if (line.substring(0, 4) == "$ ls") {
// Add children
currentLine++
line = input[currentLine]
while (currentLine < input.size && line[0] != '$') {
if (line.substring(0, 3) == "dir") {
// Add directory as child
val newDirectory = Directory(currentDirectory)
currentDirectory.children[line.split(" ")[1]] = newDirectory
} else {
// Add file as child
val fileInfo = line.split(" ")
currentDirectory.files.add(File(fileInfo[1], fileInfo[0].toLong()))
}
currentLine++
if (currentLine < input.size) line = input[currentLine]
}
}
}
}
fun part1(input: List<String>): Long {
val root = Directory(null)
readInput(root, input)
val directories = getAllChildren(root)
return directories.sumOf { it ->
val size = getDirectorySize(it)
if (size <= 100_000) size else 0
}
}
fun part2(input: List<String>): Long {
val root = Directory(null)
readInput(root, input)
val requiredSpace = 30_000_000 - (70_000_000 - getDirectorySize(root))
val directories = getAllChildren(root).map {
val size = getDirectorySize(it)
if (size >= requiredSpace) size else Long.MAX_VALUE
}
return directories.minByOrNull { it }!!
}
val testInput = readInputString("day07/test")
val input = readInputString("day07/input")
check(part1(testInput) == 95_437L)
println(part1(input))
check(part2(testInput) == 24_933_642L)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 3,594 | advent-of-code-kotlin-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/threesum/ThreeSum.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.threesum
import com.google.common.collect.HashMultiset
import com.google.common.collect.Multiset
import datsok.shouldEqual
import org.junit.Test
import kotlin.random.Random
import kotlin.random.nextInt
//
// https://leetcode.com/problems/3sum ✅
// https://en.wikipedia.org/wiki/3SUM
//
// Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0?
// Find all unique triplets in the array which gives the sum of zero.
// Notice that the solution set must not contain duplicate triplets.
// Constraints:
// 0 <= nums.length <= 3000
// -105 <= nums[i] <= 105
//
// Example 1:
// Input: nums = [-1,0,1,2,-1,-4]
// Output: [[-1,-1,2],[-1,0,1]]
//
// Example 2:
// Input: nums = []
// Output: []
//
// Example 3:
// Input: nums = [0]
// Output: []
//
//
// why?
// naming :| (hard to search for it online)
// bad function name ->
// IntArray is a bad idea
// Set<Triple<Int>> as return type (although Triple is really a Multiset/Bag of size 3)
// n^3 is just fine
//
// conclusions:
// - unbelievably bad naming
// - really specific constraints => devs expect precise requirements
// => reinforces solution-oriented "tasks" (instead of talking about the actual problem)
// =>
// - normalise software development
//
//
class ThreeSumTests {
@Test fun `find all unique triplets in the array which gives the sum of zero`() {
listOf<Int>().findZeroSumTriplets() shouldEqual emptySet()
listOf(0).findZeroSumTriplets() shouldEqual emptySet()
listOf(-1, 0, 1).findZeroSumTriplets() shouldEqual setOf(Triplet(-1, 0, 1))
listOf(-1, 0, 1, 1).findZeroSumTriplets() shouldEqual setOf(Triplet(-1, 0, 1))
listOf(0, 0, 0, 0).findZeroSumTriplets() shouldEqual setOf(Triplet(0, 0, 0))
listOf(1, 2, 3).findZeroSumTriplets() shouldEqual emptySet()
listOf(-1, 0, 1, 2, -1, -4).findZeroSumTriplets() shouldEqual setOf(
Triplet(-1, -1, 2),
Triplet(-1, 0, 1)
)
}
// @Ignore
@Test fun `three sum of huge array`() {
val random = Random(seed = 123)
val largeList = generateSequence { random.nextInt(range = -100..100) }.take(3000).toList()
largeList.findZeroSumTriplets().size shouldEqual 5101
}
}
fun threeSum(nums: IntArray): List<List<Int>> {
return nums.toList()
.findZeroSumTriplets()
.map { it.toList() }
}
private fun List<Int>.findZeroSumTriplets(): Set<Triplet> = sorted().let {
val result = LinkedHashSet<Triplet>()
(0..lastIndex - 2).forEach { i ->
var start = i + 1
var end = lastIndex
while (start < end) {
val sum = it[i] + it[start] + it[end]
when {
sum < 0 -> start++
sum > 0 -> end--
else -> result.add(Triplet(it[i], it[start++], it[end--]).sorted())
}
}
}
return result
}
private typealias Triplet = Triple<Int, Int, Int>
private fun Triplet.sorted(): Triplet =
when {
second < first -> Triple(second, first, third).sorted()
third < second -> Triple(first, third, second).sorted()
else -> this
}
private fun Triplet.sum(): Int =
first + second + third
private fun List<Int>.findZeroSumTriplets_(): Set<Triplet> {
val result = LinkedHashSet<Triplet>()
(0..lastIndex - 2).forEach { i ->
(i + 1..lastIndex - 1).forEach { j ->
(j + 1..lastIndex).forEach { k ->
val triplet = Triplet(this[i], this[j], this[k])
if (triplet.sum() == 0) result.add(triplet.sorted())
}
}
}
return result
}
/*
class Triplet private constructor(value: Triple<Int, Int, Int>) :
Value<Triple<Int, Int, Int>>(value, validation = { it.first <= it.second && it.second <= it.third }) {
val sum = value.first + value.second + value.third
constructor(val1: Int, val2: Int, val3: Int) : this(Triple(val1, val2, val3).sorted())
override fun toString() = value.toString()
}
*/
private fun <T> multisetOf(vararg elements: T): Multiset<T> =
HashMultiset.create(elements.toList())
fun Random.intArray(
size: Int = -1,
sizeRange: IntRange = IntRange.EMPTY,
valuesRange: IntRange = IntRange(Int.MIN_VALUE, Int.MAX_VALUE),
): IntArray {
require(size != -1 || !sizeRange.isEmpty()) { "`size` or `sizeRange` must be specified (but not both)" }
var i = if (size != -1) size else nextInt(sizeRange)
val result = IntArray(i)
while (--i >= 0) {
result[i] = nextInt(valuesRange)
}
return result
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 4,620 | katas | The Unlicense |
src/Day10/Solution.kt | cweinberger | 572,873,688 | false | {"Kotlin": 42814} | package Day10
import readInput
import kotlin.math.abs
object Day10 {
fun runInstructions(instructions: List<String>, registerValue: Int, maxCycles: Int) : List<Int> {
val register = mutableListOf<Int>()
var instructionIndex = 0
while (register.size <= maxCycles) {
val lastValue = register.lastOrNull() ?: registerValue
when (val line = instructions[instructionIndex % instructions.size]) {
"noop" -> register.add(lastValue)
else -> {
val instruction = line.split(" ")
register.add(lastValue)
register.add(lastValue + instruction.last().toInt())
}
}
instructionIndex++
}
return register.subList(0, maxCycles)
}
fun getSignalStrength(register: List<Int>, cycle: Int): Int {
val value = register[cycle-2]
val result = value * cycle
println("getSignalStrength: $cycle, $value => $result")
return result
}
fun part1(input: List<String>): Int {
val cycles = listOf(20, 60, 100, 140, 180, 220)
val register = runInstructions(input, 1, cycles.last())
return cycles.sumOf {
getSignalStrength(register, it)
}
}
fun part2(input: List<String>) {
val cycles = listOf(40, 80, 120, 160, 200, 240)
val register = runInstructions(input, 1, cycles.last())
val rows = mutableListOf<String>()
cycles.forEach { cycle ->
val row = MutableList(40) { '.'}
for(idx in cycle-39 .. cycle) {
val registerValue = register[idx-1]
val crtIndex = idx%40
if (abs(crtIndex-registerValue) < 2) {
row[crtIndex] = '#'
} else {
row[crtIndex] = '.'
}
}
rows.add(String(row.toCharArray()))
}
rows.forEach { println(it) }
}
}
fun main() {
val testInput = readInput("Day10/TestInput")
val input = readInput("Day10/Input")
println("\n=== Part 1 - Test Input 2 ===")
println(Day10.part1(testInput))
println("\n=== Part 1 - Final Input ===")
println(Day10.part1(input))
println("\n=== Part 2 - Test Input ===")
println(Day10.part2(testInput))
println("\n=== Part 2 - Final Input ===")
println(Day10.part2(input))
}
| 0 | Kotlin | 0 | 0 | 883785d661d4886d8c9e43b7706e6a70935fb4f1 | 2,442 | aoc-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day11.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInputSplitOnBlank
object Day11 : Day {
override val input: List<Input> = readInputSplitOnBlank(11).map { parse(it) }
override fun part1() = solve(20) { it / 3 }
override fun part2() = solve(10000) { it % input.map { i -> i.denominator.toLong() }.reduce(Long::times) }
private fun solve(rounds: Int, worryReducer: (Long) -> Long): Long {
val monkeys = input.map { Monkey(it.worryLevels, it.rules) }
repeat(rounds) { monkeys.forEach { m -> m.round(worryReducer).forEach { (k, v) -> monkeys[k].add(v) } } }
val (a, b) = monkeys.map { it.inspected }.sortedDescending()
return a * b
}
class Monkey(private var worryLevels: List<Long>, private val rules: Rules) {
var inspected = 0L
private set
fun round(worryReducer: (Long) -> Long): Map<Int, List<Long>> {
return worryLevels
.map { rules.throwItem(it, worryReducer) }
.onEach { inspected++ }
.also { worryLevels = emptyList() }
.groupBy({ it.first }, { it.second })
}
fun add(worryLevels: List<Long>) {
this.worryLevels += worryLevels
}
}
class Rules(
private val operation: (Long) -> Long,
private val predicate: (Long) -> Boolean,
private val whenTrue: Int,
private val whenFalse: Int
) {
fun throwItem(
initialLevel: Long,
worryReducer: (Long) -> Long
): Pair<Int, Long> {
val worryLevel = worryReducer(operation(initialLevel))
return if (predicate(worryLevel)) {
whenTrue
} else {
whenFalse
} to worryLevel
}
}
data class Input(val worryLevels: List<Long>, val rules: Rules, val denominator: Int)
private fun parse(input: String): Input {
val (rawItems, rawOperation, rawTest, rawTrueAction, rawFalseAction) = input.lines().drop(1)
val (denominator, test) = parseTest(rawTest)
return Input(
parseItems(rawItems),
Rules(
parseOperation(rawOperation),
test,
parseAction(rawTrueAction),
parseAction(rawFalseAction)
),
denominator
)
}
private fun parseItems(input: String): List<Long> {
return input.substringAfter(':').split(',').map { it.trim().toLong() }
}
private fun parseOperation(input: String): (worryLevel: Long) -> Long {
val (left, ope, right) = input.substringAfter('=')
.split(' ')
.map { it.trim() }
.filter { it.isNotBlank() }
return { worryLevel ->
val a = if (left == "old") worryLevel else left.toLong()
val b = if (right == "old") worryLevel else right.toLong()
when (ope.single()) {
'+' -> a + b
'*' -> a * b
else -> error("Unknown operation")
}
}
}
private fun parseTest(input: String): Pair<Int, (Long) -> Boolean> {
val level = input.substringAfter("divisible by").trim()
return level.toInt() to { it % level.toLong() == 0L }
}
private fun parseAction(input: String) = input.substringAfter("monkey ").trim().toInt()
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 3,471 | aoc2022 | MIT License |
src/main/kotlin/y2022/day11/Day11.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2022.day11
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
data class Monkey(
val items: MutableList<Long>,
val inspectionOperation: String,
val inspectionChangeValue: Int?, // null means old value
val testDivision: Int,
val testTrueTargetMonkeyId: Int,
val testFalseTargetMonkeyId: Int,
var itemsInspected: Long = 0,
)
fun input(): List<Monkey> {
val monkeys = mutableListOf<Monkey>()
AoCGenerics.getInputLines("/y2022/day11/input.txt")
.chunked(7).forEachIndexed { index, monkeyInput ->
monkeys.add(
Monkey(
items = monkeyInput[1]
.split(":")[1]
.split(',')
.map { it.trim().toLong() }
.toMutableList(),
inspectionOperation = when {
monkeyInput[2].contains("*") -> "*"
else -> "+"
},
inspectionChangeValue = when {
monkeyInput[2].split(" ").last() == "old" -> null
else -> monkeyInput[2].split(" ").last().toInt()
},
testDivision = monkeyInput[3].split(" ").last().toInt(),
testTrueTargetMonkeyId = monkeyInput[4].split(" ").last().toInt(),
testFalseTargetMonkeyId = monkeyInput[5].split(" ").last().toInt(),
))
}
return monkeys.toList()
}
fun doMonkeyBusiness(monkeys: List<Monkey>, easyRelief: Boolean, leastCommonMultiple: Int) {
monkeys.forEach { monkey ->
val itemIterator = monkey.items.iterator()
while (itemIterator.hasNext()) {
var item = itemIterator.next()
// inspect Item
item = when (monkey.inspectionOperation) {
"*" ->
if (monkey.inspectionChangeValue == null) item * item else item * monkey.inspectionChangeValue
else ->
if (monkey.inspectionChangeValue == null) item * item else item + monkey.inspectionChangeValue
}
monkey.itemsInspected++
// relief
item = if (easyRelief) {
item / 3
} else {
item % leastCommonMultiple
}
// test stress level and throw item to another monkey
if (item % monkey.testDivision.toLong() == 0L) {
monkeys[monkey.testTrueTargetMonkeyId].items.add(item)
} else {
monkeys[monkey.testFalseTargetMonkeyId].items.add(item)
}
itemIterator.remove()
}
}
}
fun part1(): Long {
val monkeys = input()
val leastCommonMultiple = monkeys.map { it.testDivision }.reduce{ acc, element -> acc * element}
val numberIfRounds = 20
for (i in 1..numberIfRounds) {
println("Starting round $i")
doMonkeyBusiness(monkeys, true, leastCommonMultiple)
}
val activeMonkeys = monkeys.sortedBy { it.itemsInspected }.takeLast(2)
return activeMonkeys[0].itemsInspected * activeMonkeys[1].itemsInspected
}
fun part2(): Long {
val monkeys = input()
val leastCommonMultiple = monkeys.map { it.testDivision }.reduce{ acc, element -> acc * element}
val numberIfRounds = 10000
for (i in 1..numberIfRounds) {
doMonkeyBusiness(monkeys, false, leastCommonMultiple)
}
val activeMonkeys = monkeys.sortedBy { it.itemsInspected }.takeLast(2)
return activeMonkeys[0].itemsInspected * activeMonkeys[1].itemsInspected
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 3,689 | AdventOfCode | MIT License |
src/main/kotlin/org/sjoblomj/adventofcode/day7/Node.kt | sjoblomj | 161,537,410 | false | null | package org.sjoblomj.adventofcode.day7
private val regex = "Step (?<dep>[A-Z]) must be finished before step (?<id>[A-Z]) can begin.".toRegex()
data class Node(val id: String, val prerequisites: MutableList<Node>, val dependers: MutableList<Node>) {
fun setAsDependency(otherNode: Node) {
dependers.add(otherNode)
otherNode.prerequisites.add(this)
}
override fun toString(): String {
return "$id - Prerequisites: ${prerequisites.map { it.id }} - Dependers: ${dependers.map { it.id }}"
}
}
internal fun createNodesFromInput(input: List<String>): List<Node> {
val pairs = input.map { parseLine(it) }
val accumulatedDeps = groupDependencies(pairs)
return createNodes(accumulatedDeps)
}
private fun groupDependencies(pairs: List<Pair<String, String>>): MutableMap<String, MutableList<String>> {
val accumulatedDeps = mutableMapOf<String, MutableList<String>>()
for ((id, dep) in pairs) {
if (accumulatedDeps[id]?.isEmpty() != false) {
accumulatedDeps[id] = mutableListOf(dep)
} else {
val list = accumulatedDeps[id]!! + listOf(dep)
accumulatedDeps[id] = list.sorted().toMutableList()
}
if (accumulatedDeps[dep]?.isEmpty() != false) {
accumulatedDeps[dep] = mutableListOf()
}
}
return accumulatedDeps
}
private fun createNodes(accumulatedDeps: MutableMap<String, MutableList<String>>): List<Node> {
val allNodes = accumulatedDeps.flatMap { it.value + it.key }.distinct().map { Node(it, mutableListOf(), mutableListOf()) }
for (idAndDeps in accumulatedDeps) {
val node = getNode(allNodes, idAndDeps.key)
val deps = idAndDeps.value.map { depId -> getNode(allNodes, depId) }
deps.forEach { dep -> dep.setAsDependency(node) }
}
return allNodes
}
private fun getNode(nodes: List<Node>, id: String): Node {
return nodes.filter { it.id == id }[0]
}
internal fun parseLine(string: String): Pair<String, String> {
val id = getRegexGroup(string, "id")
val dep = getRegexGroup(string, "dep")
return Pair(id, dep)
}
private fun getRegexGroup(input: String, group: String) =
regex
.matchEntire(input)
?.groups
?.get(group)
?.value
?: throw IllegalArgumentException("Can't find $group in input '$input'")
| 0 | Kotlin | 0 | 0 | 80db7e7029dace244a05f7e6327accb212d369cc | 2,232 | adventofcode2018 | MIT License |
src/main/kotlin/Day2.kt | amitdev | 574,336,754 | false | {"Kotlin": 21489} | import RPS.PAPER
import RPS.ROCK
import RPS.SCISSORS
import java.io.File
import kotlin.IllegalArgumentException
fun main() {
val result = File("inputs/day_2.txt").useLines { computeScorePart2(it) }
println(result)
}
// Part 1
fun computeScorePart1(lines: Sequence<String>) =
lines.map { it.split(" ") }
.map { scorePart1(it.first().toRPS(), it.last().toRPS()) }
.sum()
fun scorePart1(opponent: RPS, mine: RPS): Int {
return mine.points + when {
opponent == mine -> 3
opponent.wins() == mine -> 6
else -> 0
}
}
// Part 2
fun computeScorePart2(lines: Sequence<String>) =
lines.map { it.split(" ") }
.map { scorePart2(it.first().toRPS(), it.last()) }
.sum()
fun scorePart2(opponent: RPS, result: String) = when (result) {
"X" -> opponent.lose().points
"Y" -> 3 + opponent.points
else -> 6 + opponent.wins().points
}
enum class RPS(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun wins() = order.first { (first, _) -> first == this }.second
fun lose() = order.first { (_, second) -> second == this }.first
companion object {
val order = listOf(ROCK to PAPER, PAPER to SCISSORS, SCISSORS to ROCK)
}
}
fun String.toRPS() = when (this) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException()
}
| 0 | Kotlin | 0 | 0 | b2cb4ecac94fdbf8f71547465b2d6543710adbb9 | 1,319 | advent_2022 | MIT License |
src/main/kotlin/com/sk/topicWise/dp/medium/72. Edit Distance.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.dp.medium
class Solution72 {
// https://leetcode.com/problems/edit-distance/solutions/25895/step-by-step-explanation-of-how-to-optimize-the-solution-from-simple-recursion-to-dp
/**
* Top-down
*/
fun minDistance(word1: String, word2: String): Int {
if (word1.isEmpty()) return word2.length
if (word2.isEmpty()) return word1.length
val c1 = word1.toCharArray()
val c2 = word2.toCharArray()
val cache = Array(c1.size) { IntArray(c2.size) { -1 } }
// Min operation required at index i & j
fun match(c1: CharArray, c2: CharArray, i: Int, j: Int): Int {
if (c1.size == i) return c2.size - j
if (c2.size == j) return c1.size - i
if (cache[i][j] == -1) {
if (c1[i] == c2[j]) {
cache[i][j] = match(c1, c2, i + 1, j + 1) // no operation needed at these indexes, go to next index
} else {
//Case1: insert
val insert = match(c1, c2, i, j + 1)
//Case2: delete
val delete = match(c1, c2, i + 1, j)
//Case3: replace
val replace = match(c1, c2, i + 1, j + 1)
cache[i][j] = minOf(insert, delete, replace) + 1
}
}
return cache[i][j]
}
return match(c1, c2, 0, 0)
}
/**
* Bottom-up approach
*/
fun minDistance2(word1: String, word2: String): Int {
if (word1.isEmpty()) return word2.length
if (word2.isEmpty()) return word1.length
val c1 = word1.toCharArray()
val c2 = word2.toCharArray()
val matched = Array(c1.size + 1) { IntArray(c2.size + 1) }
//matched[length of c1 already been matched][length of c2 already been matched]
for (i in 0..c1.size) {
matched[i][0] = i
}
for (j in 0..c2.size) {
matched[0][j] = j
}
for (i in c1.indices) {
for (j in c2.indices) {
if (c1[i] == c2[j]) {
matched[i + 1][j + 1] = matched[i][j]
} else {
matched[i + 1][j + 1] = minOf(
matched[i][j + 1], // i is deleted
matched[i + 1][j], // insert at j
matched[i][j] // both j is replaced
) + 1
//Since it is bottom up, we are considering in the ascending order of indexes.
//Insert means plus 1 to j, delete means plus 1 to i, replace means plus 1 to both i and j.
//above sequence is delete, insert and replace.
}
}
}
return matched[c1.size][c2.size]
}
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,833 | leetcode-kotlin | Apache License 2.0 |
src/Day03.kt | bananer | 434,885,332 | false | {"Kotlin": 36979} | fun main() {
fun countBits(input: Iterable<String>): IntArray {
val setBitCounts = IntArray(input.first().length)
for (line in input) {
line.toCharArray().forEachIndexed { index, c ->
if (c == '1') {
setBitCounts[index]++
}
}
}
return setBitCounts
}
fun part1(input: List<String>): Int {
val setBitCounts = countBits(input)
val gamma = setBitCounts.map {
if (it > input.size / 2) {
'1'
}
else {
'0'
}
}.joinToString("")
val epsilon = gamma.map {
when(it) {
'1' -> '0'
'0' -> '1'
else -> throw IllegalStateException()
}
}.joinToString("")
return Integer.parseInt(gamma, 2) * Integer.parseInt(epsilon, 2)
}
fun part2(input: List<String>): Int {
val candidatesOxygen = input.toMutableSet()
val candidatesScrubber = input.toMutableSet()
for(i in input.indices) {
if (candidatesOxygen.size > 1) {
val setBitCounts = countBits(candidatesOxygen)
val desiredBit = if(setBitCounts[i].toFloat() / candidatesOxygen.size.toFloat() >= 0.5f) '1' else '0'
candidatesOxygen.retainAll { it[i] == desiredBit }
}
if (candidatesScrubber.size > 1) {
val setBitCounts = countBits(candidatesScrubber)
val desiredBit = if(setBitCounts[i].toFloat() / candidatesScrubber.size.toFloat() < 0.5f) '1' else '0'
candidatesScrubber.retainAll { it[i] == desiredBit }
}
}
val oxy = candidatesOxygen.also { check(it.size == 1)}.first().toInt(2)
val scr = candidatesScrubber.also { check(it.size == 1)}.first().toInt(2)
return oxy * scr
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val testOutput1 = part1(testInput)
println("test output: $testOutput1")
check(testOutput1 == 198)
val testOutput2 = part2(testInput)
println("test output: $testOutput2")
check(testOutput2 == 230)
val input = readInput("Day03")
println("output part1: ${part1(input)}")
println("output part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 98f7d6b3dd9eefebef5fa3179ca331fef5ed975b | 2,410 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/com/tonnoz/adventofcode23/day19/Day19Part2.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day19
import com.tonnoz.adventofcode23.utils.println
import com.tonnoz.adventofcode23.utils.readInput
import kotlin.math.max
import kotlin.math.min
import kotlin.system.measureTimeMillis
object Day19Part2 {
data class Workflow(val name: String, val rules: List<Rule>)
data class Rule(val part: Char, val next: String, val operator: Char, val value: Int){ fun greater() = operator == '>' }
data class Ranges(var x: IntRange, var m: IntRange, var a: IntRange, var s: IntRange, val wfName: String) {
operator fun get(property: Char): IntRange {
return when (property) {
'x' -> x
'm' -> m
'a' -> a
's' -> s
else -> throw IllegalArgumentException("Unknown part")
}
}
}
@JvmStatic
fun main(args: Array<String>) {
val input = "input19.txt".readInput()
println("time part1: ${measureTimeMillis { part2(input).println() }}ms")
}
private fun part2(input: List<String>): Long {
val (workflowsS, _) = input.splitByEmptyLine()
val workflows = parseWorkflows(workflowsS)
val initialRanges = Ranges(1..4000, 1..4000, 1..4000, 1..4000, "in")
return processWorkflows(workflows, initialRanges)
}
private fun processWorkflows(workflows: List<Workflow>, initialRanges: Ranges): Long {
val toProcess = mutableListOf(initialRanges)
val acceptedRanges = mutableListOf<Ranges>()
while (toProcess.isNotEmpty()) {
val next = toProcess.removeFirst().let { range ->
workflows.first { it.name == range.wfName }.rules.mapNotNull { rule ->
val pr = range[rule.part]
val rightR = rightRange(rule, pr)
val leftR = leftRange(rule, pr)
when (rule.part) {
'x' -> { range.x = leftR; Ranges(rightR, range.m, range.a, range.s, rule.next) }
'm' -> { range.m = leftR; Ranges(range.x, rightR, range.a, range.s, rule.next) }
'a' -> { range.a = leftR; Ranges(range.x, range.m, rightR, range.s, rule.next) }
's' -> { range.s = leftR; Ranges(range.x, range.m, range.a, rightR, rule.next) }
else -> null
}
}
}
acceptedRanges += next.filter { it.wfName == "A" }
toProcess += next.filterNot { it.isInvalid() }
}
return acceptedRanges.sumOf {
(it.x.last.toLong() - it.x.first + 1) *
(it.m.last - it.m.first + 1) *
(it.a.last - it.a.first + 1) *
(it.s.last - it.s.first + 1)
}
}
private fun Ranges.isInvalid() =
listOf(this.x, this.m, this.a, this.s).any { it.isInvalid() } || this.isFinalState()
private fun Ranges.isFinalState() = this.wfName == "A" || this.wfName == "R"
private fun IntRange.isInvalid() = this.first > this.last
private fun leftRange(rule: Rule, pr: IntRange) =
if (rule.greater()) pr.first..min(rule.value, pr.last) else max(rule.value, pr.first)..pr.last
private fun rightRange(rule: Rule, pr: IntRange) =
if (rule.greater()) max(rule.value + 1, pr.first)..pr.last else pr.first..min(rule.value - 1, pr.last)
private fun List<String>.splitByEmptyLine() =
this.takeWhile { it.isNotEmpty() } to this.dropWhile { it.isNotEmpty() }.drop(1)
private fun parseWorkflows(workflowsS: List<String>) = workflowsS.map { workflow ->
val (name, rulesS) = workflow.dropLast(1).split("{")
val rulesSplit = rulesS.split(",")
val rules = rulesSplit.dropLast(1).map { rule ->
val (part, operator) = rule.first() to rule[1]
val (value, nextWorkflow) = rule.substring(2).split(":")
Rule(part, nextWorkflow, operator, value.toInt())
}
val fallbackRule = Rule('x', rulesSplit.last(), '>', -1)
Workflow(name, rules + fallbackRule)
}
} | 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 3,706 | adventofcode23 | MIT License |
src/Day04.kt | dmdrummond | 573,289,191 | false | {"Kotlin": 9084} | fun main() {
fun toRanges(input: String): Pair<IntRange, IntRange> {
val (range1Str, range2Str) = input.split(',')
val (range1Start, range1End) = range1Str.split('-')
val (range2Start, range2End) = range2Str.split('-')
return Pair(range1Start.toInt()..range1End.toInt(), range2Start.toInt()..range2End.toInt())
}
fun part1(input: List<String>): Int {
return input
.map { toRanges(it) }
.count {
(it.first.first >= it.second.first && it.first.last <= it.second.last) // first range within second
|| (it.second.first >= it.first.first && it.second.last <= it.first.last) // second range within first
}
}
fun part2(input: List<String>): Int {
return input
.map { toRanges(it) }
.count {
it.first.first <= it.second.last && it.first.last >= it.second.first
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 2493256124c341e9d4a5e3edfb688584e32f95ec | 1,188 | AoC2022 | Apache License 2.0 |
src/Day01.kt | andydenk | 573,909,669 | false | {"Kotlin": 24096} | fun main() {
// 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("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<String>): Int {
return calculateElvInventories(input)
.maxOf { it.totalCalories() }
}
private fun part2(input: List<String>): Int {
return calculateElvInventories(input)
.map { it.totalCalories() }
.sortedDescending()
.take(3)
.sum()
}
private fun calculateElvInventories(input: List<String>): MutableList<Elv> {
val elves = mutableListOf<Elv>()
var currentElv = Elv()
for (inputLine in input) {
val calorieItem = inputLine.toIntOrNull()
calorieItem?.let { currentElv += calorieItem }
if (inputLine.isEmpty()) {
elves += currentElv
currentElv = Elv()
}
}
if (currentElv.calorieItems.isNotEmpty()) {
elves += currentElv
}
return elves
}
private typealias CalorieItem = Int
private data class Elv(val calorieItems: MutableList<CalorieItem> = emptyList<CalorieItem>().toMutableList()) {
operator fun plusAssign(calorieItem: CalorieItem) {
calorieItems.add(calorieItem)
}
fun totalCalories() = calorieItems.sumOf { it }
}
| 0 | Kotlin | 0 | 0 | 1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1 | 1,439 | advent-of-code-2022 | Apache License 2.0 |
src/year2021/day4/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2021.day4
import java.util.stream.IntStream
import readInput
fun main() {
fun toCard(it: List<String>) {
TODO("Not yet implemented")
}
fun part1(input: List<String>): Int {
val possible = input[0].split(",").map { it.toInt() }
val cards = input.drop(2).filterNot { it.isEmpty() }.chunked(5).map { Card(it) }
for (v in possible) {
for (card in cards) {
if(card.bingo(v)){
return card.remaining.sum() * v
}
}
}
return -1
}
fun part2(input: List<String>): Int {
val possible = input[0].split(",").map { it.toInt() }
val cards = input.drop(2).filterNot { it.isEmpty() }.chunked(5).map { Card(it) }
var countRemaining = cards.size
for (v in possible) {
for (card in cards) {
if(card.isNotBing() && card.bingo(v)) {
if (--countRemaining == 0) {
return card.remaining.sum() * v
}
}
}
}
return -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("year2021/day4/test")
println(part1(testInput))
check(part1(testInput) == 4512)
val input = readInput("year2021/day4/input")
println(part1(input))
check(part2(testInput) == 1924)
println(part2(input))
}
class Card {
val lines: List<MutableSet<Int>>
val columns: List<MutableSet<Int>>
val remaining: MutableSet<Int>
constructor(l: List<String>) {
val tempLines = l.map { it.split(" ").filterNot { it.isEmpty() }.map { it -> it.toInt() }.toList() }
lines = tempLines.map { it.toMutableSet() }
columns = IntRange(0, 4).map { i -> tempLines.map { it -> it[i] }.toMutableSet() }
remaining = lines.flatten().toMutableSet()
}
fun bingo(i: Int): Boolean {
lines.forEach { it.remove(i) }
columns.forEach { it.remove(i) }
remaining.remove(i)
return lines.any { it.isEmpty() } || columns.any { it.isEmpty() }
}
fun isNotBing(): Boolean {
return lines.all { it.isNotEmpty() } && columns.all { it.isNotEmpty() }
}
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 2,271 | adventOfCode | Apache License 2.0 |
src/Day03.kt | kuolemax | 573,740,719 | false | {"Kotlin": 21104} | fun main() {
fun part1(input: List<String>): Int {
// 将String变成char数组,均分后取交集,转成ascii相加
return input.sumOf { backpack ->
val chunked = backpack.toCharArray().toList().chunked(backpack.length / 2)
val chars = chunked[0].toSet() intersect chunked[1].toSet()
if (chars.first().code < 96) {
// Upper 65 -> 27
chars.first().code - 38
} else {
// lower 97 -> 1
chars.first().code - 96
}
}
}
fun part2(input: List<String>): Int {
// 每三个背包是一组,一组的三个背包交集是徽章
return input.chunked(3).sumOf { group ->
val chars = group[0].toSet() intersect group[1].toSet() intersect group[2].toSet()
if (chars.first().code < 96) {
// Upper 65 -> 27
chars.first().code - 38
} else {
// lower 97 -> 1
chars.first().code - 96
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3045f307e24b6ca557b84dac18197334b8a8a9bf | 1,355 | aoc2022--kotlin | Apache License 2.0 |
y2021/src/main/kotlin/adventofcode/y2021/Day21.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
object Day21 : AdventSolution(2021, 21, "<NAME>") {
override fun solvePartOne(input: String): Int {
var (p1, p2) = parse(input)
p1--
p2--
var p1Score = 0
var p2Score = 0
var dice = 1
var rolls = 0
fun next() = dice.also { rolls++;if (++dice > 100) dice = 1 }
while (p2Score < 1000) {
p1 += next() + next() + next()
p1 %= 10
p1Score += p1 + 1
p1 = p2.also { p2 = p1 }
p1Score = p2Score.also { p2Score = p1Score }
}
return p1Score * rolls
}
override fun solvePartTwo(input: String): Long {
val universes = mutableMapOf<State, WinCount>()
val distribution3d3 = mapOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1)
fun winnings(s: State): WinCount = universes.getOrPut(s) {
when {
s.score1 >= 21 -> WinCount(1, 0)
s.score2 >= 21 -> WinCount(0, 1)
else -> distribution3d3.map { (roll, frequency) ->
winnings(
State(
pos1 = s.pos2,
pos2 = (s.pos1 + roll) % 10,
score1 = s.score2,
score2 = s.score1 + (s.pos1 + roll) % 10 + 1
)
).flip() * frequency.toLong()
}
.fold(WinCount(0, 0), WinCount::plus)
}
}
val (p1, p2) = parse(input)
val (p1Wins, p2Wins) = winnings(State(p1 - 1, p2 - 1, 0, 0))
return maxOf(p1Wins, p2Wins)
}
private fun parse(input: String) = input.lines().map { it.last() - '0' }
private data class WinCount(val p1: Long, val p2: Long) {
operator fun plus(o: WinCount) = WinCount(p1 + o.p1, p2 + o.p2)
operator fun times(s: Long) = WinCount(p1 * s, p2 * s)
fun flip() = WinCount(p2, p1)
}
private data class State(val pos1: Int, val pos2: Int, val score1: Int, val score2: Int)
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,141 | advent-of-code | MIT License |
src/Day07.kt | a2xchip | 573,197,744 | false | {"Kotlin": 37206} | class FilesystemNode(
private val name: String,
val parent: FilesystemNode?,
) {
val children: MutableList<FilesystemNode> = mutableListOf()
val fileSizes: MutableList<Int> = mutableListOf()
fun getTotalSize(): Int {
return fileSizes.fold(0) { acc, i -> acc + i } + getChildSize()
}
private fun getChildSize(): Int {
return children.sumOf { it.getTotalSize() }
}
fun findChild(name: String): FilesystemNode {
return children.find { it.name == name }!!
}
fun getRoot(): FilesystemNode {
if (parent == null) {
return this
}
return parent.getRoot()
}
fun listNodes(): List<FilesystemNode> {
return all(this.getRoot())
}
companion object {
fun fromInput(input: List<String>): FilesystemNode {
var cwd: FilesystemNode? = null
for (l in input) {
if (l == "$ ls") continue
if (l.startsWith("\$ cd")) {
val targetDir = l.split(" ").last()
cwd = when (targetDir) {
"/" -> {
cwd?.getRoot() ?: FilesystemNode(targetDir, null)
}
".." -> {
cwd!!.parent
}
else -> {
cwd!!.findChild(targetDir)
}
}
continue
}
val (first, second) = l.split(" ")
if (first == "dir") {
cwd!!.children.add(FilesystemNode(second, cwd))
} else {
cwd!!.fileSizes.add(first.toInt())
}
}
return cwd!!.getRoot()
}
fun all(node: FilesystemNode?): List<FilesystemNode> {
if (node == null) {
return mutableListOf()
}
val list = mutableListOf(node)
for (c in node.children) {
list += this.all(c)
}
return list
}
fun findNodesSmallerThan(amount: Int, node: FilesystemNode?): List<FilesystemNode> {
val list = mutableListOf<FilesystemNode>()
if (node == null) {
return mutableListOf()
}
if (node.getTotalSize() <= amount) {
list.add(node)
}
for (c in node.children) {
list += this.findNodesSmallerThan(amount, c)
}
return list
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val rootNode = FilesystemNode.fromInput(input)
return FilesystemNode.findNodesSmallerThan(100000, rootNode).sumOf { it.getTotalSize() }
}
fun part2(input: List<String>): Int {
val rootNode = FilesystemNode.fromInput(input)
val diskCapacity = 70000000
val needSpace = 30000000
val diskSpaceLeft = diskCapacity - rootNode.getTotalSize()
val amountOfAdditionalSpaceRequired = needSpace - diskSpaceLeft
return rootNode.listNodes().map { it.getTotalSize() }.filter { it >= amountOfAdditionalSpaceRequired }
.minByOrNull { it }!!
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println("Part 1 - ${part1(input)}")
println("Part 2 - ${part2(input)}")
check(part1(input) == 2031851)
check(part2(input) == 2568781)
}
| 0 | Kotlin | 0 | 2 | 19a97260db00f9e0c87cd06af515cb872d92f50b | 3,620 | kotlin-advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/day14/Day14.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day14
import java.io.File
fun main() {
val (template, rules) = parse("src/main/kotlin/day14/Day14.txt")
val answer1 = part1(template, rules)
val answer2 = part2(template, rules)
println("🎄 Day 14 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private typealias Template = String
private typealias Rules = Map<String, Char>
private fun parse(path: String): Pair<Template, Rules> {
val (template, rulesPart) = File(path)
.readText()
.trim()
.split("""(\n\n)|(\r\n\r\n)""".toRegex())
val rules = rulesPart
.lines()
.associate(String::toRule)
return template to rules
}
private fun String.toRule() =
this.split(" -> ")
.let { (match, element) -> match to element.first() }
private fun expand(template: Template, rules: Rules, iterations: Int): Long {
val frequencies = template
.groupingBy { it }
.eachCount()
.mapValuesTo(mutableMapOf()) { (_, v) -> v.toLong() }
var patterns = template
.zipWithNext { a, b -> "$a$b" }
.groupingBy { it }
.eachCount()
.mapValues { (_, v) -> v.toLong() }
repeat(iterations) {
val next = mutableMapOf<String, Long>()
for ((pattern, count) in patterns) {
val element = rules.getValue(pattern)
val lhs = "${pattern[0]}$element"
val rhs = "$element${pattern[1]}"
next.merge(lhs, count, Long::plus)
next.merge(rhs, count, Long::plus)
frequencies.merge(element, count, Long::plus)
}
patterns = next
}
val max = frequencies.maxOf { it.value }
val min = frequencies.minOf { it.value }
return max - min
}
private fun part1(template: Template, rules: Rules) =
expand(template, rules, iterations = 10)
private fun part2(template: Template, rules: Rules) =
expand(template, rules, iterations = 40)
| 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 2,026 | advent-of-code-2021 | MIT License |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p04/Leet435v2.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p04
import java.util.TreeMap
private class Leet435v2 {
val knownOverlaps = TreeMap<Int, Int>()
val filteredOutKeys = HashSet<Int>()
fun eraseOverlapIntervals(intervals: Array<IntArray>): Int {
knownOverlaps.clear()
filteredOutKeys.clear()
for (i in intervals.indices) {
calcAndSaveOverlaps(intervals, i)
}
println("Known overlaps: $knownOverlaps")
while (consumeOneOverlap(intervals)) {
}
return filteredOutKeys.size
}
private fun consumeOneOverlap(intervals: Array<IntArray>): Boolean {
val keyToConsume = knownOverlaps.keys.firstOrNull() ?: return false
if (knownOverlaps[keyToConsume]!! > 0) {
val intervalToRemove = intervals.withIndex()
.filter { !filteredOutKeys.contains(it.index) }
.filter { keyToConsume >= it.value[0] && keyToConsume < it.value[1] }
.maxByOrNull { it.value[1] }
intervalToRemove?.let { removeInterval(it.value[0], it.value[1]) }
intervalToRemove?.let { filteredOutKeys.add(it.index) }
} else {
knownOverlaps.remove(keyToConsume)
}
return true
}
private fun removeInterval(start: Int, end: Int) {
println("Remove interval $start - $end")
knownOverlaps.tailMap(start).headMap(end).keys.forEach {
val newValue = knownOverlaps[it]!! - 1
knownOverlaps[it] = newValue
}
}
private fun saveOverlap(start: Int, size: Int) {
knownOverlaps[start] = (knownOverlaps.floorEntry(start)?.value ?: 0)
knownOverlaps.tailMap(start).headMap(start + size).keys.forEach { knownOverlaps[it] = knownOverlaps[it]!! + 1 }
val end = start + size
if (!knownOverlaps.contains(end)) // if the next key after range already has value do nothing
knownOverlaps[end] = knownOverlaps.floorEntry(end).value - 1
}
private fun calcAndSaveOverlaps(allIntervals: Array<IntArray>, currentIntervalNumber: Int) {
val overlapsForInterval = TreeMap<Int, Int>()
for (i in 0 until currentIntervalNumber) {
val anOverlap = calcOverlap(
allIntervals[i][0],
allIntervals[i][1],
allIntervals[currentIntervalNumber][0],
allIntervals[currentIntervalNumber][1]
)
anOverlap?.let {
overlapsForInterval[it.first] = maxOf(it.second, overlapsForInterval[it.first] ?: 0)
}
}
val mergedOverlaps = mergeOverlaps(overlapsForInterval)
saveOverlaps(mergedOverlaps)
// println(mergedOverlaps)
}
private fun saveOverlaps(oneRangeOverlaps: TreeMap<Int, Int>) {
oneRangeOverlaps.forEach { (t, u) ->
saveOverlap(t, u)
}
}
private fun mergeOverlaps(knownIntervals: TreeMap<Int, Int>): TreeMap<Int, Int> {
val cleanTree = TreeMap<Int, Int>()
var lastKey = 0
knownIntervals.entries.firstOrNull()?.let {
cleanTree[it.key] = it.value
lastKey = it.key
}
knownIntervals.entries.zipWithNext().forEach {
val lastValue = cleanTree[lastKey]!!
if (lastKey + lastValue >= it.second.key) {
cleanTree[lastKey] =
maxOf(cleanTree[lastKey]!!, it.second.value + (it.second.key - lastKey))
} else {
cleanTree[it.second.key] = it.second.value
lastKey = it.second.key
}
}
return cleanTree
}
private fun calcOverlap(start1: Int, end1: Int, start2: Int, end2: Int): Pair<Int, Int>? {
if (start1 >= start2 && start1 < end2) {
val size = minOf(end1, end2) - start1
return start1 to size
}
if (start2 >= start1 && start2 < end1) {
val size = minOf(end1, end2) - start2
return start2 to size
}
return null
}
}
fun main() {
val solution = Leet435v2()
val myTest = "[[1,10],[2,5],[4,11],[1,4]]" // 2
// doWork(myTest, solution)
val testCase1 = "[[1,2],[2,3],[3,4],[1,3]]" // 1
// doWork(testCase1, solution)
val testCase2 = "[[1,2],[1,2],[1,2]]" // 2
// doWork(testCase2, solution)
val testCase3 = "[[1,2],[2,3]]" // 0
// doWork(testCase3, solution)
val wrongAnswer1 = "[[0,2],[1,3],[2,4],[3,5],[4,6]]" // 2
// doWork(wrongAnswer1, solution)
val wrongAnswer2 = "[[-52,31],[-73,-26],[82,97],[-65,-11],[-62,-49],[95,99],[58,95],[-31,49],[66,98],[-63,2]," +
"[30,47],[-40,-26]]" // 7
// doWork(wrongAnswer2, solution)
val wrongAnswer3 = "[[-36057,-16287],[-35323,-26257],[-27140,-14703],[-15279,21851],[-15129,-5773]," +
"[-12098,16264],[-8144,1080],[-3035,30075],[1937,6906],[11834,20971],[19621,34415],[10508,46685]," +
"[28565,37578],[32985,36313],[44578,45600],[47939,48626]]"
// doWork(wrongAnswer3, solution)
val nullPointer1 = "[[-25322,-4602],[-35630,-28832],[-33802,29009],[13393,24550],[-10655,16361],[-2835,10053]," +
"[-2290,17156],[1236,14847],[-45022,-1296],[-34574,-1993],[-14129,15626],[3010,14502],[42403,45946]," +
"[-22117,13380],[7337,33635],[-38153,27794],[47640,49108],[40578,46264],[-38497,-13790],[-7530,4977]," +
"[-29009,43543],[-49069,32526],[21409,43622],[-28569,16493],[-28301,34058]]"
// doWork(nullPointer1, solution)
val wrongAnswer4 = "[[-70,27],[-41,11],[78,85],[-95,55],[-63,4],[-96,38],[33,65],[-16,38],[-43,15],[-69,-7]," +
"[64,67],[-33,97],[58,74],[75,83],[87,94],[-64,20],[-77,-7],[48,65],[-80,3],[-10,61],[71,87],[75,82]," +
"[-79,-34],[-67,50],[-13,4],[34,42],[-50,-12],[32,51],[-73,40],[18,87],[-16,74],[-27,75],[15,60]," +
"[-15,63],[-70,57],[-6,57],[-77,85],[59,94],[38,73],[18,25],[-57,36],[88,95],[72,98],[38,40],[-73,9]," +
"[-27,60],[79,92],[-77,47],[47,67],[86,96],[16,44],[37,54],[37,76],[-92,-81],[90,92],[77,84],[-88,5]," +
"[26,64],[13,26],[-42,-36],[-96,60],[98,100],[92,94],[94,100],[63,70],[-41,-22],[6,38],[-53,-5]," +
"[35,79],[49,50],[-46,-15],[90,93],[-45,63],[20,48],[-50,-30],[17,85],[-9,97],[-97,-12],[43,96]," +
"[-4,64],[-34,60],[29,87],[-90,-59],[46,81],[-77,86],[56,86],[-30,-24],[-39,-37],[-17,44],[-40,-1]," +
"[71,81]]" // 79
doWork(wrongAnswer4, solution)
}
private fun doWork(data: String, service: Leet435v2): Int {
return data.trim('[', ']').split("],[")
.map { it.split(",").map { el -> el.toInt() } }
.map { intArrayOf(it[0], it[1]) }
.toTypedArray()
.let { service.eraseOverlapIntervals(it) }
.also { println("Result: $it\n") }
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 6,831 | playground | MIT License |
src/main/kotlin/graph/variation/PalindromicPath.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.*
import util.OneArray
import util.get
import util.max
import util.set
// given a DAG G = (V, E), with each vertex associated with a character,
// find the longest path from in V : the string composed of characters
// from corresponding vertices in this path is palindromic
// report the length of such path
fun Graph<Char>.palindrome(checkIdentity: Boolean = true): Int {
val G = this
// topological order of vertices
val V = G.topoSort(checkIdentity) // O(V + E)
// V.prettyPrintln()
// dp[i, j]: len of longest path from V[i] to V[j] that MUST include V[i]
// and V[j] : string described above is palindromic
val dp = OneArray(V.size) { OneArray(V.size) { 0 } }
// space: O(V^2)
// we want max_{i, j} { dp[i, j] }
var max = 0
// base case:
// dp[i, j] = 1 if i = j (G is a DAG so there won't be a cycle)
// = 2 if V[i] -> V[j] in E and V[i] = V[j]
// = 0 if i > j or i, j !in 1..V.size
for (i in 1..V.size) {
dp[i, i] = 1
max = 1
}
edges
.filter { (u, v) -> u.data == v.data }
.forEach { (u, v) ->
dp[V.indexOf(u), V.indexOf(v)] = 2
max = 2
}
val reachable = HashMap<Vertex<Char>, Set<Vertex<Char>>>()
vertices.forEach {
reachable[it] = whateverFirstSearch(it, checkIdentity)
}
// println(reachable)
// recursive case:
// dp[i, j] = 0 if V[i] != V[j]
// = 2 + max_{u, v} { dp[u, v] } o/w where i < u <= v < j
// , i -> u, j -> v in E, and v is reachable from u
// dp[i, j] depends on entries to the lower-left
// eval order: outer loop for i decreasing from V.size - 2 down to 1
for (i in V.size - 2 downTo 1) {
// inner loop for j increasing from i + 2 to V.size
for (j in i + 2..V.size) {
dp[i, j] = if (V[i].data != V[j].data) {
0
} else {
var innerMax = 0
getEdgesFrom(V[i], checkIdentity).forEach { (_, u) ->
val uIdx = V.indexOf(u)
getEdgesTo(V[j], checkIdentity)
.filter { (v, _) ->
val vIdx = V.indexOf(v)
vIdx >= uIdx && reachable[u]!!.contains(v)
}
.forEach { (v, _) ->
val vIdx = V.indexOf(v)
innerMax = max(innerMax, dp[uIdx, vIdx] + 2)
}
}
innerMax
}
max = max(max, dp[i, j])
}
}
// time: O(V^2 + E^2)
// dp.prettyPrintTable()
return max
}
fun main(args: Array<String>) {
val V = listOf(DVertex('H'), DVertex('A'), DVertex('H'))
val E = setOf(Edge(V[0], V[1], true), Edge(V[1], V[2], true))
val G = Graph(V, E)
println(G.palindrome())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,518 | AlgoKt | MIT License |
src/day13/Code.kt | fcolasuonno | 162,470,286 | false | null | package day13
import MultiMap
import permutations
import java.io.File
fun main(args: Array<String>) {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2(parsed)}")
}
data class Score(val source: String, val dest: String, val score: Int)
private val lineStructure = """(\w+) would (\w+) (\d+) happiness units by sitting next to (\w+)\.""".toRegex()
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val (who, sign, points, whom) = it.toList()
Score(who, whom, (if (sign == "gain") 1 else -1) * points.toInt())
}
}.requireNoNulls().let { scores ->
MultiMap<String, String, Int>().apply {
scores.forEach {
this[it.source][it.dest] = it.score
}
}
}
fun part1(input: MultiMap<String, String, Int>): Any? = input.keys.permutations.map {
it.windowed(2).sumBy { (source, dest) -> input[source][dest] + input[dest][source] } + input[it.last()][it.first()] + input[it.first()][it.last()]
}.max()
fun part2(input: MultiMap<String, String, Int>): Any? = input.apply {
keys.toList().forEach { key ->
this[key]["me"] = 0
this["me"][key] = 0
}
}.let { part1(it) }
| 0 | Kotlin | 0 | 0 | 24f54bf7be4b5d2a91a82a6998f633f353b2afb6 | 1,393 | AOC2015 | MIT License |
src/Day03.kt | f1qwase | 572,888,869 | false | {"Kotlin": 33268} | fun getCommonItems(line: String): Set<Char> {
if (line.length % 2 != 0) {
throw IllegalArgumentException("Input size must be even")
}
val (left, right) = line.chunked(line.length / 2)
return left.toSet() intersect right.toSet()
}
fun Char.priority(): Int = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> throw IllegalArgumentException("Unknown char: $this")
}
fun main() {
fun part1(input: List<String>): Int = input.sumOf { line ->
getCommonItems(line).sumOf(Char::priority)
}
fun part2(input: List<String>): Int = input
.chunked(3)
.sumOf { (line1, line2, line3) ->
(line1.toSet() intersect line2.toSet() intersect line3.toSet())
.single()
.priority()
}
check('a'.priority() == 1)
check('A'.priority() == 27) { 'A'.priority() }
// 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))
check(part2(testInput) == 70) { part2(testInput) }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3fc7b74df8b6595d7cd48915c717905c4d124729 | 1,204 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/pl/jpodeszwik/aoc2023/Day05.kt | jpodeszwik | 729,812,099 | false | {"Kotlin": 55101} | package pl.jpodeszwik.aoc2023
data class Range(
val source: Long,
val target: Long,
val length: Long,
)
data class Category(
val name: String,
val ranges: MutableList<Range>,
)
fun findLocation(seed: Long, almanac: List<Category>): Long {
var current = seed
almanac.forEach { category ->
val matchingRange = category.ranges.firstOrNull {
current >= it.source && current < it.source + it.length
}
if (matchingRange != null) {
val target = matchingRange.target + (current - matchingRange.source)
current = target
}
}
return current
}
fun parseAlmanac(lines: List<String>): List<Category> {
val almanac = ArrayList<Category>()
var currentCategory: Category? = null
lines.forEach {
if (it.contains("map")) {
currentCategory = Category(it.split(" ")[0], ArrayList())
almanac.add(currentCategory!!)
}
if (it.isNotEmpty() && it[0].isDigit()) {
val rangeNumbers = it.split(" ")
.map { java.lang.Long.parseLong(it) }
currentCategory!!.ranges.add(Range(rangeNumbers[1], rangeNumbers[0], rangeNumbers[2]))
}
}
return almanac
}
private fun part1(lines: List<String>, seeds: List<Long>) {
val almanac = parseAlmanac(lines)
val result = seeds.minOf {
findLocation(it, almanac)
}
println(result)
}
private fun part2(lines: List<String>, seeds: List<Long>) {
val almanac = parseAlmanac(lines)
var min = Long.MAX_VALUE
for (i in 0..<seeds.size / 2) {
println("range: $i")
for (j in 0..<seeds[i * 2 + 1]) {
val loc = findLocation(seeds[i * 2] + j, almanac)
if (loc < min) {
min = loc
}
}
}
println(min)
}
fun main() {
val lines = loadFile("/aoc2023/input5")
val seeds = lines[0].split(": ")[1].split(" ")
.map { java.lang.Long.parseLong(it) }
part1(lines, seeds)
measureTimeSeconds { part2(lines, seeds) }
} | 0 | Kotlin | 0 | 0 | 2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63 | 2,069 | advent-of-code | MIT License |
2022/Day21.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | import java.math.BigDecimal
import java.math.RoundingMode
fun main() {
data class Poly(
val coef: List<BigDecimal>
) {
operator fun plus(o: Poly): Poly {
val n = maxOf(coef.size, o.coef.size)
return Poly(Array(n) { i ->
coef.getOrElse(i) { BigDecimal.ZERO } + o.coef.getOrElse(i) { BigDecimal.ZERO }
}.toList())
}
operator fun minus(o: Poly): Poly {
val n = maxOf(coef.size, o.coef.size)
return Poly(Array(n) { i ->
coef.getOrElse(i) { BigDecimal.ZERO } - o.coef.getOrElse(i) { BigDecimal.ZERO }
}.toList())
}
operator fun times(o: Poly): Poly {
val n = coef.size * o.coef.size
val res = Array(n) { BigDecimal.ZERO }
for (i in coef.indices) {
for (j in o.coef.indices) {
res[i+j] += coef[i]*o.coef[j]
}
}
return Poly(res.toList())
}
operator fun div(o: Poly): Poly {
if (o.coef.size == 1) {
return Poly(coef.map { it.divide(o.coef[0], 100, RoundingMode.HALF_UP) })
}
error("complex division")
}
}
data class Monkey(
val name: String,
val children: List<String> = emptyList(),
val op: String = "",
var number: BigDecimal? = null,
var poly: Poly? = null,
)
val monkeys = readInput("Day21").map { line ->
val (name, task) = line.split(": ")
val number = task.toBigDecimalOrNull()
val poly = if (name == "humn") Poly(listOf(BigDecimal.ZERO, BigDecimal.ONE)) else number?.let { Poly(listOf(it)) }
if (number == null) {
val args = task.split(" ")
Monkey(name, children = listOf(args[0], args[2]), op = args[1], poly = poly)
} else {
Monkey(name, number = number, poly = poly)
}
}.associateBy { it.name }
fun calcNumber(name: String): BigDecimal {
val m = monkeys[name]!!
if (m.number != null) return m.number!!
m.number = when (m.op) {
"+" -> calcNumber(m.children[0]) + calcNumber(m.children[1])
"-" -> calcNumber(m.children[0]) - calcNumber(m.children[1])
"*" -> calcNumber(m.children[0]) * calcNumber(m.children[1])
"/" -> calcNumber(m.children[0]) / calcNumber(m.children[1])
else -> error(m.op)
}
return m.number!!
}
println(calcNumber("root"))
fun calcPoly(name: String): Poly {
val m = monkeys[name]!!
if (m.poly != null) return m.poly!!
m.poly = when (m.op) {
"+" -> calcPoly(m.children[0]) + calcPoly(m.children[1])
"-" -> calcPoly(m.children[0]) - calcPoly(m.children[1])
"*" -> calcPoly(m.children[0]) * calcPoly(m.children[1])
"/" -> calcPoly(m.children[0]) / calcPoly(m.children[1])
else -> error(m.op)
}
return m.poly!!
}
val rootArgs = monkeys["root"]!!.children.map { calcPoly(it) }
println(rootArgs)
println((rootArgs[1].coef[0] - rootArgs[0].coef[0]) / rootArgs[0].coef[1])
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 3,215 | advent-of-code-kotlin | Apache License 2.0 |
src/Day18.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} | data class Point3D(
val x: Int,
val y: Int,
val z: Int
) {
val neighbors: Set<Point3D> by lazy {
setOf(
this.copy(x = x - 1),
this.copy(x = x + 1),
this.copy(y = y - 1),
this.copy(y = y + 1),
this.copy(z = z - 1),
this.copy(z = z + 1)
)
}
}
data class BoundingBox(
val xRange: IntRange,
val yRange: IntRange,
val zRange: IntRange
) {
fun contains(point: Point3D) =
point.x in xRange && point.y in yRange && point.z in zRange
}
fun Set<Point3D>.getAirBoundingBox(): BoundingBox {
var minX = Integer.MAX_VALUE
var maxX = Integer.MIN_VALUE
var minY = Integer.MAX_VALUE
var maxY = Integer.MIN_VALUE
var minZ = Integer.MAX_VALUE
var maxZ = Integer.MIN_VALUE
this.forEach {
if (it.x < minX) minX = it.x
if (it.x > maxX) maxX = it.x
if (it.y < minY) minY = it.y
if (it.y > maxY) maxY = it.y
if (it.z < minZ) minZ = it.z
if (it.z > maxZ) maxZ = it.z
}
return BoundingBox(
minX - 1..maxX + 1,
minY - 1..minY + 1,
minZ - 1..maxZ + 1
)
}
fun main() { // ktlint-disable filename
fun part1(input: List<String>): Int {
val points = mutableSetOf<Point3D>()
for (line in input) {
val (x, y, z) = line.split(",").map { it.toInt() }
points.add(Point3D(x, y, z))
}
// unconnected faces are all neighbors not in the point set
return points.flatMap { it.neighbors }.count { it !in points }
}
fun part2(input: List<String>): Int {
val points = mutableSetOf<Point3D>()
for (line in input) {
val (x, y, z) = line.split(",").map { it.toInt() }
points.add(Point3D(x, y, z))
}
val boundingBox = points.getAirBoundingBox()
val queue = ArrayDeque<Point3D>()
val firstSearchPoint = Point3D(boundingBox.xRange.first, boundingBox.yRange.first, boundingBox.zRange.first)
queue.add(firstSearchPoint)
val visited = mutableSetOf<Point3D>()
val exterior = mutableSetOf<Point3D>()
while (queue.isNotEmpty()) {
val point = queue.removeLast()
visited.add(point)
point.neighbors
.filter { boundingBox.contains(it) && it !in visited }
.forEach {
if (it in points) {
exterior.add(it)
} else {
queue.add(it)
}
}
}
return exterior.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
println("Test #Unconnected sides: ${part1(testInput)}")
check(part1(testInput) == 64)
println("Test #Exterior sides: ${part2(testInput)}")
check(part2(testInput) == 58)
val input = readInput("Day18_input")
println("#Unconnected sides: ${part1(input)}")
// println("#Exterior sides: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 3,081 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/solutions/Day18BoilingBoulders.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import models.Coord3d
import utils.Input
import utils.Solution
import java.util.*
import kotlin.math.abs
// run only this day
fun main() {
Day18BoilingBoulders()
}
class Day18BoilingBoulders : Solution() {
init {
begin("Day 18 - Boiling Boulders")
val input = Input.parseToListOf<Coord3d>(filename = "/d18_lava_cubes.txt", delimiter = "\n")
.map { Cube(it) }
val sol1 = mapDroplet(input)
output("Droplet Surface Area", sol1)
val sol2 = mapDropletShell(input.filter { it.openSides != 0 })
output("Outer Surface Area Only", sol2)
}
private fun mapDroplet(cubes: List<Cube>): Int {
val cList = Stack<Cube>().apply { addAll(cubes) }
while (cList.empty().not()) {
// take next cube
val curCube = cList.pop()
cList.forEach { next ->
val cPairs = curCube.c.pairWith(next.c)
.filterNot { it.first - it.second == 0 }
if (cPairs.size == 1 && (abs(cPairs.first().first - cPairs.first().second)) == 1) {
curCube.openSides--
next.openSides--
}
}
// remove proven inner cubes
cList.removeAll { it.openSides == 0 }
}
return cubes.sumOf { it.openSides }
}
private fun mapDropletShell(keyCubes: List<Cube>): Int {
val keyCoords = keyCubes.map { it.c }
var outerSurface = 0
val bounds = Triple(
(keyCoords.minOf { it.x } - 1)..(keyCoords.maxOf { it.x } + 1),
(keyCoords.minOf { it.y } - 1)..(keyCoords.maxOf { it.y } + 1),
(keyCoords.minOf { it.z } - 1)..(keyCoords.maxOf { it.z } + 1),
)
val frontier = Stack<Coord3d>().apply {
add(Coord3d(bounds.first.first, bounds.second.first, bounds.third.first))
}
val visited = mutableListOf<Coord3d>()
while (frontier.isNotEmpty()) {
val cur = frontier.pop()
visited.add(cur)
val neighbors = cur.adjacentNeighbors().filter {
it.x in bounds.first && it.y in bounds.second && it.z in bounds.third
&& it !in visited && it !in frontier
}
neighbors.forEach { n ->
if (n in keyCoords) {
outerSurface++
}
}
frontier.addAll(neighbors.filter { it !in keyCoords })
}
return outerSurface
}
data class Cube(
val c: Coord3d,
var openSides: Int = 6
)
} | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 2,629 | advent-of-code-2022 | MIT License |
day-04/src/main/kotlin/GiantSquid.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | fun main() {
println("Part One Solution: ${partOne()}")
println("Part Two Solution: ${partTwo()}")
}
private fun partOne(): Int {
val numbersToDraw = readNumberToDraw()
val bingoCards = readBingoCards()
numbersToDraw.forEach { number ->
bingoCards.forEach { card ->
card.mark(number)
if (card.isBingo()) {
return card.getWinningScore(number)
}
}
}
return 0
}
private fun partTwo(): Int {
val numbersToDraw = readNumberToDraw()
val bingoCards = readBingoCards().toMutableList()
var lastWinningCardScore = 0
numbersToDraw.forEach { number ->
bingoCards.forEach { card ->
if (!card.hasWon) { // Do not mark cards that already won or else their score will be changed
card.mark(number)
if (card.isBingo()) {
lastWinningCardScore = card.getWinningScore(number)
}
}
}
}
return lastWinningCardScore
}
private fun readBingoCards(): List<BingoCard> {
return readLines()
.drop(1)
.filter { it.isNotBlank() }
.windowed(5, 5, false) {
val card: Array<IntArray> = Array(5) {
IntArray(5)
}
it.forEachIndexed { index, line ->
card[index] = line.split(" ")
.filter { el -> el.isNotBlank() } // handle double spaces of single digit numbers
.map { number -> number.toInt() }
.toIntArray()
}
BingoCard(card)
}
}
private fun readNumberToDraw(): List<Int> {
return readLines()
.first()
.split(",")
.map { it.toInt() }
}
data class BingoCard(
val card: Array<IntArray>,
var hasWon: Boolean = false,
) {
companion object {
private const val MARK = -1
}
fun mark(draw: Int) {
for (row in card.indices) {
for (column in card[0].indices) {
if (card[row][column] == draw) {
card[row][column] = MARK
return
}
}
}
}
fun isBingo(): Boolean {
for (row in card.indices) {
if (card[row].all { it == MARK }) {
this.hasWon = true
return true
}
val columnArray = mutableListOf<Int>()
for (column in card[0].indices) {
columnArray.add(card[column][row])
}
if (columnArray.all { it == MARK }) {
this.hasWon = true
return true
}
}
return false
}
fun getWinningScore(winningDrawNumber: Int): Int {
val sumOfNonMarked = card.sumOf { row ->
row.filter { it != MARK }.sum()
}
return sumOfNonMarked * winningDrawNumber
}
}
private fun readLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")
.readText()
.split("\n")
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 3,068 | aoc-2021 | MIT License |
src/y2016/Day04.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.readInput
object Day04 {
private fun parse(input: List<String>): List<Triple<String, Int, String>> {
return input.map {
Triple(
it.substringBeforeLast('-'),
it.substringAfterLast('-').substringBefore('[').toInt(),
it.substringAfter('[').substring(0 until 5)
)
}
}
fun part1(input: List<String>): Int {
val parsed = parse(input)
return parsed.filter{ validRoom(it.first, it.third) }.sumOf { it.second }
}
private fun validRoom(name: String, check: String): Boolean {
val counts = name.replace("-", "").groupingBy { it }.eachCount()
return counts.entries
.sortedBy { it.key }
.sortedByDescending { it.value }
.take(5)
.joinToString(separator = "") { it.key.toString() } == check
}
fun part2(input: List<String>): Long {
val rooms = parse(input).filter { validRoom(it.first, it.third) }
rooms.forEach { (name, sector, _) ->
println(decode(name, sector) + ": $sector")
}
return 0L
}
private fun decode(name: String, sector: Int): String {
val shift = sector % 26
return name.map {
if (it == '-') {
' '
} else {
(((it.code + shift - 'a'.code) % 26) + 'a'.code).toChar()
}
}.joinToString(separator = "") { it.toString() }
}
}
fun main() {
val testInput = """
aaaaa-bbb-z-y-x-123[abxyz]
a-b-c-d-e-f-g-h-987[abcde]
not-a-real-room-404[oarel]
totally-real-room-200[decoy]
""".trimIndent().split("\n")
println("------Tests------")
println(Day04.part1(testInput))
println(Day04.part2(testInput))
println("------Real------")
val input = readInput("resources/2016/day04")
println(Day04.part1(input))
println(Day04.part2(input))
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,962 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day1.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | private fun tests() {
val measures = """
199
200
208
210
200
207
240
269
260
263
""".trimIndent()
val numbers = measures.lines().map { it.toInt() }
assertEquals(numberOfIncreases(numbers), 7)
assertEquals(numberOfMaskedIncreasings(numbers, 3), 5)
assertEquals(numberOfMaskedIncreasings2(numbers, 3), 5)
assertEquals(
numberOfMaskedIncreasings3(parseInput(readInputFile("input1")), 5),
numberOfMaskedIncreasings(parseInput(readInputFile("input1")), 5),
)
assertEquals(
numberOfMaskedIncreasings3(parseInput(readInputFile("input1")), 5),
numberOfMaskedIncreasings2(parseInput(readInputFile("input1")), 5),
)
}
private fun main() {
tests()
val input = readInputFile("input1")
println(part1(input))
println(part2(input))
// sanity
println("day1")
}
private fun part2(input: String): Int =
numberOfMaskedIncreasings(parseInput(input), 3)
private fun numberOfMaskedIncreasings(numbers: List<Int>, maskSize: Int): Int {
return numbers.windowed(maskSize).map { it.sum() }.zipWithNext().count { (a, b) -> b > a }
}
// solving in a single iteration. since addition is reversible, we could remove the first
// element from the mask, and add a new one
private fun numberOfMaskedIncreasings2(numbers: List<Int>, maskSize: Int): Int {
var increasings = 0
var currentSum = numbers.take(maskSize).sum()
var index = maskSize
while (index < numbers.size) {
val newSum = currentSum - numbers[index - maskSize] + numbers[index]
if (currentSum < newSum) {
increasings++
}
currentSum = newSum
index++
}
return increasings
}
// with the same idea as solution 2, we don't really need the mask. we could just compare the numbers on the edge of
// the mask.
private fun numberOfMaskedIncreasings3(numbers: List<Int>, maskSize: Int): Int {
val maskStartings = numbers.dropLast(maskSize)
val maskEndings = numbers.drop(maskSize)
return maskStartings.zip(maskEndings).count { it.second > it.first }
}
private fun part1(input: String): Int =
numberOfIncreases(parseInput(input))
private fun parseInput(input: String) = input.lines().map { it.toInt() }
private fun numberOfIncreases(numbers: List<Int>): Int =
numberOfMaskedIncreasings(numbers, 1)
| 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 2,407 | AOC-2021 | MIT License |
src/main/kotlin/Day17.kt | bent-lorentzen | 727,619,283 | false | {"Kotlin": 68153} | import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.PriorityQueue
fun main() {
data class CityBlock(
val id: Pair<Int, Int>,
val cost: Int
) {
override fun toString(): String {
return "Node(id=$id, cost=$cost)"
}
}
fun getMap(lines: List<List<Int>>): Map<Pair<Int, Int>, CityBlock> {
return lines.mapIndexed { y, ints ->
ints.mapIndexed { x, i ->
CityBlock(y to x, i)
}
}.flatten().associateBy { it.id }
}
val validDirections = mapOf(
Direction.DOWN to listOf(Direction.DOWN, Direction.RIGHT, Direction.LEFT),
Direction.UP to listOf(Direction.RIGHT, Direction.UP, Direction.LEFT),
Direction.LEFT to listOf(Direction.DOWN, Direction.LEFT, Direction.UP),
Direction.RIGHT to listOf(Direction.RIGHT, Direction.DOWN, Direction.UP)
)
data class Arrival(val cityBlock: CityBlock, val lastDirection: Direction, val steps: Int)
data class Path(val arrival: Arrival, val cost: Int)
fun findShortestPath2(
grid: List<List<Int>>,
minStep: Int = 1,
maxStep: Int = 3
): Int {
val cityMap = getMap(grid)
val first = cityMap[0 to 0]!!
val target = cityMap[grid.first().lastIndex to grid.lastIndex]!!
val queue = PriorityQueue { o1: Path, o2: Path -> o1.cost.compareTo(o2.cost) }
queue.add(Path(Arrival(first, Direction.DOWN, 0), 0))
queue.add(Path(Arrival(first, Direction.RIGHT, 0), 0))
val visits = mutableSetOf<Arrival>()
while (queue.isNotEmpty()) {
val current = queue.poll()
if (current.arrival.cityBlock == target && current.arrival.steps >= minStep) return current.cost
validDirections[current.arrival.lastDirection]!!.filterNot {
current.arrival.steps < minStep && it != current.arrival.lastDirection ||
current.arrival.lastDirection == it && current.arrival.steps == maxStep
}.mapNotNull {
val nextBlock = cityMap[it.action(current.arrival.cityBlock.id)]
if (nextBlock == null) null else Arrival(nextBlock, it, if (it == current.arrival.lastDirection) current.arrival.steps + 1 else 1)
}.forEach {
if (it !in visits) {
queue.add(Path(it, current.cost + it.cityBlock.cost))
visits.add(it)
}
}
}
return Int.MAX_VALUE
}
fun part1(input: List<String>): Int {
val grid = input.map { it.map { c -> c.toString().toInt() } }
return findShortestPath2(grid)
}
fun part2(input: List<String>): Int {
val grid = input.map { it.map { c -> c.toString().toInt() } }
return findShortestPath2(grid, 4, 10)
}
val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()
val input = readLines("day17-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 | 3,215 | aoc-2023-in-kotlin | Apache License 2.0 |
src/year2022/20/Day20.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`20`
import readInput
fun parseInput(input: List<String>): List<Long> {
return input.map { it.toLong() }
}
fun mixList(
repeat: Int,
items: List<Pair<Int, Long>>,
): List<Pair<Int, Long>> {
val mutableItems = items.toMutableList()
repeat(repeat) {
items.forEach {
val indexOfItemToMove = mutableItems.indexOf(it)
val itemToMove = mutableItems[indexOfItemToMove]
val amountOfMovement = itemToMove.second
// Remove item
mutableItems.removeAt(indexOfItemToMove)
// Calculate new item position
val newIndex = (indexOfItemToMove + amountOfMovement % mutableItems.size).toInt()
val finalIndex = when {
newIndex < 0 -> mutableItems.size + newIndex
newIndex != mutableItems.size && newIndex > mutableItems.size -> newIndex - mutableItems.size
newIndex == mutableItems.size -> 0
newIndex == 0 -> mutableItems.size
else -> newIndex
}
// Insert item in new position
mutableItems.add(finalIndex, itemToMove)
}
}
return mutableItems
}
fun calculateFinalValue(mutableItems: List<Pair<Int, Long>>): Long {
val zeroItem = mutableItems.find { it.second == 0L }
val indexOfZero = mutableItems.indexOf(zeroItem)
return listOf(1000, 2000, 3000)
.map { indexOfZero + it }
.map { it % mutableItems.size }
.map { mutableItems[it] }
.sumOf { it.second }
}
fun main() {
fun part1(input: List<String>): Long {
val items = parseInput(input).mapIndexed { index, i -> index to i }
val mixedList = mixList(1, items)
return calculateFinalValue(mixedList)
}
fun part2(input: List<String>): Long {
val items = parseInput(input).mapIndexed { index, i -> index to i * 811589153L }
val mixedList = mixList(10, items)
return calculateFinalValue(mixedList)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 3L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 2,312 | KotlinAdventOfCode | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day13.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val grids = readInput(2023, 13).useLines { sequence ->
val lines = sequence.iterator()
buildList<List<String>> {
var current = arrayListOf<String>()
while (lines.hasNext()) {
val line = lines.next()
if (line.isEmpty()) {
add(current)
current = arrayListOf()
} else current.add(line)
}
add(current)
}
}
part1(grids)
part2(grids)
}
private fun part1(grids: List<List<String>>) {
val sum = grids.sumOf { findMirror(it, 0) }
println(sum)
}
private fun part2(grids: List<List<String>>) {
val sum = grids.sumOf { findMirror(it, 1) }
println(sum)
}
private fun findMirror(grid: List<String>, smudges: Int): Int {
val horizontal = findHorizontal(grid, smudges)
return if (horizontal > 0) horizontal else findVertical(grid, smudges)
}
private fun findHorizontal(grid: List<String>, smudges: Int): Int {
outer@ for (i in 1..grid.lastIndex) {
var miss = 0
var diff = 0
while (diff < minOf(i, grid.size - i)) {
val top = i - diff - 1
val bottom = i + diff
for (x in grid[0].indices) if (grid[top][x] != grid[bottom][x]) miss++
if (miss > smudges) continue@outer
diff++
}
if (miss == smudges) return i * 100
}
return 0
}
private fun findVertical(grid: List<String>, smudges: Int): Int {
outer@ for (i in 1..grid[0].lastIndex) {
var diff = 0
var miss = 0
while (diff < minOf(i, grid[0].length - i)) {
val left = i - diff - 1
val right = i + diff
for (y in grid.indices) if (grid[y][left] != grid[y][right]) miss++
if (miss > smudges) continue@outer
diff++
}
if (miss == smudges) return i
}
return 0
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 2,027 | adventofcode | Apache License 2.0 |
src/Day03.kt | akijowski | 574,262,746 | false | {"Kotlin": 56887, "Shell": 101} | private val priorityList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun main() {
// TODO: This is better
fun priority(groups: List<String>): Int {
val chars = groups.flatMap { it.toSet() }
val sharedItem = chars.groupingBy { it }.eachCount().maxBy { it.value }.key
return if (sharedItem.isUpperCase()) (sharedItem - 'A') + 27 else (sharedItem - 'a') + 1
}
fun part1Other(input: List<String>): Int {
val leftSide = mutableSetOf<Char>()
val rightSide = mutableSetOf<Char>()
var sum = 0
for (ruck in input) {
var left = 0
var right = ruck.length - 1
while (left < right) {
leftSide.add(ruck[left])
rightSide.add(ruck[right])
left++
right--
}
leftSide.retainAll(rightSide)
val match = leftSide.first()
val i = priorityList.indexOfFirst { it == match } + 1
sum += i
leftSide.clear()
rightSide.clear()
}
return sum
}
fun part1(input: List<String>): Int {
return input.map {it.chunked(it.length / 2)}.sumOf { priority(it) }
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { priority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1Other(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 84d86a4bbaee40de72243c25b57e8eaf1d88e6d1 | 1,618 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day3.kt | hughjdavey | 225,440,374 | false | null | package days
import kotlin.math.abs
class Day3 : Day(3) {
private val path1 = inputList[0]
private val path2 = inputList[1]
override fun partOne(): Any {
return closestIntersectionSum(path1, path2)
}
override fun partTwo(): Any {
return fewestSteps(path1, path2)
}
fun closestIntersectionSum(p1: String, p2: String): Int {
return intersections(p1, p2).minBy { it.posSum() }!!.posSum()
}
fun fewestSteps(p1: String, p2: String): Int {
val (one, two) = wirePath(p1) to wirePath(p2)
val intersections = intersections(p1, p2)
return intersections
.map { int -> one.indexOfFirst { it.index == int.index } + two.indexOfFirst { it.index == int.index } }
.min() ?: 0
}
private fun intersections(p1: String, p2: String): List<GridCell> {
val (one, two) = wirePath(p1) to wirePath(p2)
return one.intersect(two).filter { !it.centralPort }
}
private fun wirePath(path: String): List<GridCell> {
val instructions = path.split(',').map { it.trim() }
return instructions.fold(listOf(GridCell(0 to 0, true))) { acc, elem -> acc.plus(acc.last().nexts(GridMove(elem))) }
}
data class GridCell(val index: Pair<Int, Int>, val centralPort: Boolean = false) {
private val x = index.first
private val y = index.second
fun nexts(move: GridMove): List<GridCell> {
return (move.distance downTo 1).fold(listOf(this)) { acc, _ -> acc.plus(acc.last().next(move.direction)) }.drop(1)
}
fun posSum(): Int = abs(x) + abs(y)
private fun next(direction: GridDirection): GridCell {
return when (direction) {
GridDirection.RIGHT -> GridCell(x + 1 to y)
GridDirection.LEFT -> GridCell(x - 1 to y)
GridDirection.UP -> GridCell(x to y + 1)
GridDirection.DOWN -> GridCell(x to y - 1)
}
}
}
data class GridMove(private val move: String) {
val direction = when (move[0]) {
'R' -> GridDirection.RIGHT
'L' -> GridDirection.LEFT
'D' -> GridDirection.DOWN
'U' -> GridDirection.UP
else -> throw IllegalArgumentException()
}
val distance = move.drop(1).toInt()
}
enum class GridDirection { LEFT, RIGHT, UP, DOWN }
}
| 0 | Kotlin | 0 | 1 | 84db818b023668c2bf701cebe7c07f30bc08def0 | 2,412 | aoc-2019 | Creative Commons Zero v1.0 Universal |
src/Day05.kt | bjornchaudron | 574,072,387 | false | {"Kotlin": 18699} | fun main() {
fun part1(input: List<String>): String {
val (stacks, commands) = parseInput(input)
val crane = Crane(stacks, moveMultiple = false)
crane.executeCommands(commands)
return joinTopCrates(stacks)
}
fun part2(input: List<String>): String {
val (stacks, commands) = parseInput(input)
val crane = Crane(stacks, moveMultiple = true)
crane.executeCommands(commands)
return joinTopCrates(stacks)
}
// test if implementation meets criteria from the description, like:
val day = "05"
val testInput = readLines("Day${day}_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readLines("Day$day")
println(part1(input))
println(part2(input))
}
fun parseInput(input: List<String>) = Pair(parseStacks(input), parseCommands(input))
fun parseStacks(lines: List<String>): Map<Int, ArrayDeque<Char>> {
val image = lines.takeWhile { line -> line.isNotBlank() }
val numbersLine = image.last()
val stackLookup = numbersLine.mapIndexed { i, c -> i to c.digitToIntOrNull() }
.associate { pair -> pair }
.filterValues { it != null }
val stacks = (1..stackLookup.size).associateWith { ArrayDeque<Char>() }
image.dropLast(1)
.forEach { line ->
stackLookup.filterKeys { it < line.length }
.forEach { (index, stackNr) ->
val char = line[index]
if (!char.isWhitespace()) stacks[stackNr]?.addFirst(char)
}
}
return stacks.toMap()
}
fun parseCommands(input: List<String>): List<Command> =
input.takeLastWhile { it.isNotBlank() }
.map { line ->
val (times, from, to) = line.split(" ").mapNotNull { it.toIntOrNull() }
Command(times, from, to)
}
fun joinTopCrates(stacks: Map<Int, ArrayDeque<Char>>): String = stacks.entries
.sortedBy { (k, _) -> k }
.map { (_, v) -> v.last() }
.joinToString("")
data class Command(val crates: Int, val from: Int, val to: Int)
class Crane(private val stacks: Map<Int, ArrayDeque<Char>>, private val moveMultiple: Boolean) {
fun executeCommands(commands: List<Command>) = commands.forEach(::executeCommand)
private fun executeCommand(command: Command) = if (moveMultiple) moveStack(command) else moveCrate(command)
private fun moveCrate(command: Command) = with(command) {
val size = stacks[from]?.size ?: 0
val times = minOf(size, crates)
repeat(times) {
val crate = stacks[from]?.removeLast()
if (crate != null) stacks[to]?.addLast(crate)
}
}
private fun moveStack(command: Command)= with(command) {
val stackSize = stacks[from]?.size ?: 0
val size = minOf(stackSize, crates)
val crates = stacks[from]?.takeLast(size) ?: emptyList()
repeat(crates.size) { stacks[from]?.removeLast() }
stacks[to]?.addAll(crates)
}
} | 0 | Kotlin | 0 | 0 | f714364698966450eff7983fb3fda3a300cfdef8 | 3,005 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/day19/Day19.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day19
import check
import readInput
import kotlin.math.max
import kotlin.system.measureTimeMillis
import kotlin.time.Duration.Companion.milliseconds
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day19_test")
check(part1(testInput), 33)
check(part2(testInput), 56 * 62)
val input = readInput("2022", "Day19")
measureTimeMillis { print(part1(input)) }.also { println(" (Part 1 took ${it.milliseconds})") }
measureTimeMillis { print(part2(input)) }.also { println(" (Part 2 took ${it.milliseconds})") }
}
private fun part1(input: List<String>) = input.toCosts()
.mapIndexed { i, cost ->
val blueprintId = i + 1
val highestGeodeCount = getHighestGeodeCount(cost, timeLeft = 24)
blueprintId * highestGeodeCount
}.sum()
private fun part2(input: List<String>) = input.take(3)
.toCosts()
.map { getHighestGeodeCount(it, timeLeft = 32) }
.reduce(Int::times)
private data class CacheKey(
val materials: Materials,
val timeLeft: Int,
val oreRobots: Int,
val clayRobots: Int,
val obsidianRobots: Int,
val geodeRobots: Int,
)
private fun getHighestGeodeCount(
cost: Cost,
timeLeft: Int,
materials: Materials = Materials(),
oreRobots: Int = 1,
clayRobots: Int = 0,
obsidianRobots: Int = 0,
geodeRobots: Int = 0,
cache: MutableMap<CacheKey, Int> = hashMapOf(),
maxGeodeRobotsByTimeLeft: MutableMap<Int, MaxRobots> = hashMapOf(),
): Int {
if (timeLeft == 0) return 0
val (maxOreRobots, maxClayRobots, maxObsidianRobots, maxGeodeRobots) = maxGeodeRobotsByTimeLeft.compute(timeLeft) { _, v ->
MaxRobots(
max(oreRobots, v?.maxOreRobots ?: 0),
max(clayRobots, v?.maxClayRobots ?: 0),
max(obsidianRobots, v?.maxObsidianRobots ?: 0),
max(geodeRobots, v?.maxGeodeRobots ?: 0),
)
}!!
if (geodeRobots < maxGeodeRobots || (geodeRobots == 0 && obsidianRobots < maxObsidianRobots - 1) || (obsidianRobots == 0 && clayRobots < maxClayRobots - 1) || (clayRobots == 0 && oreRobots < maxOreRobots - 1)) return 0
val minTimeToFirstGeodeRobot =
if (geodeRobots == 0) minTimeRequired(cost.geodeRobotObsidianCost - materials.obsidian, obsidianRobots)
else 0
val minTimeToFirstObsidianRobot =
if (obsidianRobots == 0) minTimeRequired(cost.obsidianRobotClayCost - materials.clay, clayRobots)
else 0
val minTimeToFirstClayRobot =
if (clayRobots == 0) minTimeRequired(cost.clayRobotOreCost - materials.ore, oreRobots)
else 0
if (timeLeft <= minTimeToFirstGeodeRobot + minTimeToFirstObsidianRobot + minTimeToFirstClayRobot) return 0
val key = CacheKey(
materials = materials,
timeLeft = timeLeft,
oreRobots = oreRobots,
clayRobots = clayRobots,
obsidianRobots = obsidianRobots,
geodeRobots = geodeRobots,
)
return cache.getOrPut(key) {
val newMaterials = materials.copy()
var newTimeLeft = timeLeft
var buildableRobots = Robot.values().filter { it.canBuild(newMaterials, cost) }
while (buildableRobots.size == 1) {
if (--newTimeLeft == 0) return@getOrPut timeLeft * geodeRobots
newMaterials.addMined(oreRobots, clayRobots, obsidianRobots)
buildableRobots = Robot.values().filter { it.canBuild(newMaterials, cost) }
}
val avoidSkip =
(clayRobots == 0 && buildableRobots.size == 3) || (obsidianRobots == 0 && buildableRobots.size == 4) || buildableRobots.size == 5
if (avoidSkip) {
buildableRobots = buildableRobots - Robot.Skip
}
val minedGeodes = geodeRobots * (1 + timeLeft - newTimeLeft)
val results = arrayListOf<Int>()
for (newRobot in buildableRobots) {
results += (minedGeodes + getHighestGeodeCount(
cost = cost,
materials = newMaterials.copy().minusBuildCost(newRobot, cost)
.addMined(oreRobots, clayRobots, obsidianRobots),
timeLeft = newTimeLeft - 1,
oreRobots = oreRobots + if (newRobot == Robot.OreRobot) 1 else 0,
clayRobots = clayRobots + if (newRobot == Robot.ClayRobot) 1 else 0,
obsidianRobots = obsidianRobots + if (newRobot == Robot.ObsidianRobot) 1 else 0,
geodeRobots = geodeRobots + if (newRobot == Robot.GeodeRobot) 1 else 0,
cache = cache,
maxGeodeRobotsByTimeLeft = maxGeodeRobotsByTimeLeft,
))
}
return@getOrPut results.max()
}
}
private fun List<String>.toCosts() = map { line ->
val nums = line.split(' ').mapNotNull { it.toIntOrNull() }
Cost(
oreRobotOreCost = nums[0],
clayRobotOreCost = nums[1],
obsidianRobotOreCost = nums[2],
obsidianRobotClayCost = nums[3],
geodeRobotOreCost = nums[4],
geodeRobotObsidianCost = nums[5],
)
}
private enum class Robot {
Skip, OreRobot, ClayRobot, ObsidianRobot, GeodeRobot;
fun oreCost(cost: Cost): Int = when (this) {
Skip -> 0
OreRobot -> cost.oreRobotOreCost
ClayRobot -> cost.clayRobotOreCost
ObsidianRobot -> cost.obsidianRobotOreCost
GeodeRobot -> cost.geodeRobotOreCost
}
fun clayCost(cost: Cost): Int = when (this) {
ObsidianRobot -> cost.obsidianRobotClayCost
else -> 0
}
fun obsidianCost(cost: Cost): Int = when (this) {
GeodeRobot -> cost.geodeRobotObsidianCost
else -> 0
}
fun canBuild(materials: Materials, cost: Cost): Boolean = when (this) {
Skip -> true
OreRobot -> materials.ore >= cost.oreRobotOreCost
ClayRobot -> materials.ore >= cost.clayRobotOreCost
ObsidianRobot -> materials.ore >= cost.obsidianRobotOreCost && materials.clay >= cost.obsidianRobotClayCost
GeodeRobot -> materials.ore >= cost.geodeRobotOreCost && materials.obsidian >= cost.geodeRobotObsidianCost
}
}
private data class Cost(
val oreRobotOreCost: Int,
val clayRobotOreCost: Int,
val obsidianRobotOreCost: Int,
val obsidianRobotClayCost: Int,
val geodeRobotOreCost: Int,
val geodeRobotObsidianCost: Int,
)
private data class Materials(
var ore: Int = 0,
var clay: Int = 0,
var obsidian: Int = 0,
) {
fun minusBuildCost(robot: Robot, cost: Cost): Materials {
ore -= robot.oreCost(cost)
clay -= robot.clayCost(cost)
obsidian -= robot.obsidianCost(cost)
return this
}
fun addMined(oreRobots: Int, clayRobots: Int, obsidianRobots: Int): Materials {
ore += oreRobots
clay += clayRobots
obsidian += obsidianRobots
return this
}
}
private fun minTimeRequired(units: Int, robots: Int): Int {
var acc = 0
var r = robots
var n = 1
while (acc < units) {
acc += r++
n++
}
return n
}
private data class MaxRobots(
val maxOreRobots: Int,
val maxClayRobots: Int,
val maxObsidianRobots: Int,
val maxGeodeRobots: Int,
) | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 7,199 | AdventOfCode | Apache License 2.0 |
src/Day16.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private val lineFormat = """Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? (.*)""".toRegex()
private data class Valve(
val name: String,
val flowRate: Int,
val neighbours: List<String>
)
private const val TOTAL_TIME = 30
private fun valves(input: List<String>): List<Valve> {
return input.map { line ->
val matchResult = lineFormat.matchEntire(line)!!
val name = matchResult.groupValues[1]
val flowRate = matchResult.groupValues[2].toInt()
val neighbours = matchResult.groupValues[3].split(", ")
Valve(name, flowRate, neighbours)
}.toList()
}
private fun shortestDistance(map: Map<String, Valve>, from: Valve, to: Valve): Int {
val distanceTable = mutableMapOf(from.name to 0)
val toProcess = ArrayDeque(listOf(from))
do {
val valve = toProcess.removeFirst()
val valveDistance = distanceTable[valve.name]!!
for (neighbour in valve.neighbours) {
if (!distanceTable.containsKey(neighbour)) {
if (neighbour == to.name) {
return valveDistance + 1
} else {
distanceTable[neighbour] = valveDistance + 1
toProcess.addLast(map[neighbour]!!)
}
}
}
} while (toProcess.isNotEmpty())
throw IllegalArgumentException("Map does not lead from ${from.name} to ${to.name}")
}
private fun distanceMap(
map: Map<String, Valve>,
valves: List<Valve>
): Map<Pair<String, String>, Int> {
val distanceMap = mutableMapOf<Pair<String, String>, Int>()
for (i in 0 until valves.size - 1) {
for (j in i + 1 until valves.size) {
val distance = shortestDistance(map, valves[i], valves[j])
distanceMap[Pair(valves[i].name, valves[j].name)] = distance
distanceMap[Pair(valves[j].name, valves[i].name)] = distance
}
}
return distanceMap
}
private fun maxScore(
currentLocation: String,
valvesToVisit: List<Valve>,
distanceMap: Map<Pair<String, String>, Int>,
timeLeft: Int,
currentScore: Int,
currentFlowRate: Int
): Pair<Int, List<String>> {
var maxScore = currentScore
var pathVisited = listOf<String>()
for (valve in valvesToVisit) {
val distance = distanceMap[Pair(currentLocation, valve.name)]!!
val timeElapsed = distance + 1
val newTimeLeft = timeLeft - timeElapsed
if (newTimeLeft > 0) {
val newScore = currentScore + currentFlowRate * timeElapsed
val newFlowRate = currentFlowRate + valve.flowRate
val remainingValves = valvesToVisit - valve
val (remainingMaxScore, remainingPathVisited) = if (remainingValves.isNotEmpty()) {
maxScore(valve.name, remainingValves, distanceMap, newTimeLeft, newScore, newFlowRate)
} else {
// nothing left to visit
Pair(newScore + newFlowRate * newTimeLeft, listOf())
}
if (remainingMaxScore > maxScore) {
maxScore = remainingMaxScore
pathVisited = listOf(valve.name) + remainingPathVisited
}
} else {
// not enough time to move to this valve
}
}
if (pathVisited.isEmpty()) {
// no more valve to visit
maxScore += timeLeft * currentFlowRate
}
return Pair(maxScore, pathVisited)
}
private fun part1(input: List<String>): Int {
val valves = valves(input)
val map = valves.associateBy { it.name }
val usefulValves = valves.filter { it.flowRate > 0 }
val distanceMap = distanceMap(map, (usefulValves + map["AA"]!!).toSet().toList())
val (maxScore, pathVisited) = maxScore("AA", usefulValves, distanceMap, TOTAL_TIME, 0, 0)
println("maxScore = ${maxScore}")
println("pathVisited = ${pathVisited}")
return maxScore
}
private fun generateCombinations(valves: List<Valve>, count: Int): List<List<Valve>> {
return if (count == 1) {
valves.map { listOf(it) }
} else {
val result = mutableListOf<List<Valve>>()
for (i in 0 until valves.size - 1) {
generateCombinations(valves.subList(i + 1, valves.size), count - 1).forEach { combination ->
result.add(listOf(valves[i]) + combination)
}
}
result
}
}
private fun part2(input: List<String>): Int {
val valves = valves(input)
val map = valves.associateBy { it.name }
val usefulValves = valves.filter { it.flowRate > 0 }
val distanceMap = distanceMap(map, (usefulValves + map["AA"]!!).toSet().toList())
val myCombinations = mutableListOf<List<Valve>>()
val halfValvesCount = usefulValves.size / 2
for (x in 1..halfValvesCount) {
// add all combinations with x valves
myCombinations.addAll(generateCombinations(usefulValves, x))
}
var maxScore = Int.MIN_VALUE
var myMaxPath = listOf<String>()
var elephantMaxPath = listOf<String>()
for (myCombination in myCombinations) {
val elephantCombination = usefulValves - myCombination
val (myMaxScore, myPathVisited) = maxScore("AA", myCombination, distanceMap, TOTAL_TIME - 4, 0, 0)
val (elephantMaxScore, elephantPathVisited) = maxScore("AA", elephantCombination, distanceMap, TOTAL_TIME - 4, 0, 0)
val totalScore = myMaxScore + elephantMaxScore
if (totalScore > maxScore) {
maxScore = totalScore
myMaxPath = myPathVisited
elephantMaxPath = elephantPathVisited
}
}
println("maxScore = ${maxScore}")
println("myMaxPath = ${myMaxPath}")
println("elephantMaxPath = ${elephantMaxPath}")
return maxScore
}
fun main() {
val input = readInput("Day16")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 5,909 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class Sensor(val position: Pair<Int, Int>, val beacon: Pair<Int, Int>)
fun main() {
fun List<String>.parse(): List<Sensor> {
val sensorRegex =
"Sensor at x=(?<sx>-?\\d+), y=(?<sy>-?\\d+): closest beacon is at x=(?<bx>-?\\d+), y=(?<by>-?\\d+)".toRegex()
return map {
val groups = sensorRegex.matchEntire(it)?.groups ?: error("Cant parse $it")
val x = groups["sx"]?.value?.toInt() ?: error("Cant parse $it")
val y = groups["sy"]?.value?.toInt() ?: error("Cant parse $it")
val bx = groups["bx"]?.value?.toInt() ?: error("Cant parse $it")
val by = groups["by"]?.value?.toInt() ?: error("Cant parse $it")
Sensor(position = Pair(y, x), beacon = Pair(by, bx))
}
}
fun manhattanDistance(pos1: Pair<Int, Int>, pos2: Pair<Int, Int>): Int {
return abs(pos1.first - pos2.first) + abs(pos1.second - pos2.second)
}
fun part1(input: List<String>, row: Int): Int {
val sensors = input.parse()
val tunnels = HashMap<Pair<Int, Int>, Char>()
for (sensor in sensors) {
val dist = manhattanDistance(sensor.position, sensor.beacon)
val height = manhattanDistance(sensor.position, Pair(row, sensor.position.second))
val horizontal = dist - height
if (horizontal < 0) {
continue
} else {
val d = horizontal
for (x in sensor.position.second - d..sensor.position.second + d) {
tunnels[Pair(row, x)] = '#'
// println("From ${sensor.position} put $x")
}
}
}
for (sensor in sensors) {
tunnels.remove(sensor.beacon)
}
return tunnels.size
}
fun part2(input: List<String>, maxValue: Int): Long {
val minValue = 0
val sensors = input.parse()
fun checkLackingY(): Pair<Int, Int> {
for (y in minValue..maxValue) {
val tunnels = mutableListOf<IntRange>()
for (sensor in sensors) {
val dist = manhattanDistance(sensor.position, sensor.beacon)
val height = manhattanDistance(sensor.position, Pair(y, sensor.position.second))
val horizontal = dist - height
if (horizontal < 0) {
continue
} else {
tunnels.add(
max(sensor.position.second - horizontal, 0)..min(
sensor.position.second + horizontal,
maxValue
)
)
}
}
tunnels.sortBy { it.first }
var maxX = 0
for (tunnel1 in tunnels) {
if (maxX + 1 < tunnel1.first) {
return y to (maxX + 1)
}
maxX = max(maxX, tunnel1.last)
}
}
error("Position y not found")
}
val y = checkLackingY()
return y.second * 4000000L + y.first
}
val testInput = readInput("Day15_test")
val testRow = 10
val row = 2000000
val input = readInput("Day15")
assert(part1(testInput, testRow), 26)
println(part1(input, row))
val testMaxValue = 20
val maxValue = 4000000
assert(part2(testInput, testMaxValue), 56000011)
println(part2(input, maxValue))
}
// Time: 01:20 | 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 3,651 | advent-of-code-2022 | Apache License 2.0 |
kotlin/0014-longest-common-prefix.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | /*
* Solution as per the channel
*/
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
var len = 0
outerloop@ for(i in 0 until strs[0].length){
for(s in strs){
if(i == s.length || s[i] != strs[0][i]){
break@outerloop
}
}
len++
}
return strs[0].substring(0,len)
}
}
/*
* Same solution as above but a little more in an idiomatic Kotlin way
*/
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
var res = ""
strs.minBy { it.length }?.forEachIndexed { i,c ->
if(strs.all { it[i] == c } ) res += c else return res
}
return res
}
}
/*
* Trie solution
*/
class TrieNode() {
val child = arrayOfNulls<TrieNode>(26)
var isEnd = false
fun childCount() = this.child?.filter{it != null}?.count()
}
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
val root: TrieNode? = TrieNode()
for(word in strs) {
var current = root
for(c in word){
if(current?.child?.get(c - 'a') == null){
current?.child?.set(c - 'a', TrieNode())
}
current = current?.child?.get(c - 'a')
}
current?.isEnd = true
}
var current = root
var len = 0
for (c in strs[0]){
println(c)
if (current?.childCount() == 1 && current?.isEnd != true) len++ else break
current = current?.child?.get(c - 'a')
}
println(len)
return strs[0].substring(0,len)
}
}
/*
* Sorting solution
*/
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
var len = 0
strs.sort()
val first = strs[0]
val last = strs[strs.size-1]
val minLen = strs.minBy {it.length}?.length!!
for(i in 0 until minLen){
if(first[i] == last[i]) len++ else break
}
return strs[0].substring(0,len)
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 2,135 | leetcode | MIT License |
src/Day11.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
// Advent of Code 2022, Day 11, Monkey in the Middle
fun main() {
fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim()
data class Monkey(
val items: MutableList<Long>,
val operation: List<String>,
val test: Int,
val monkeyTrue: Int,
val monkeyFalse: Int
)
fun parse(input: String) = input.split("\n\n").map {
val lines = it.split("\n").map { i -> i.trim() }
Monkey(
lines[1].substringAfter(":").split(",").map { j -> j.trim().toLong() }.toMutableList(),
lines[2].substringAfter("Operation: new = old ").split(" "),
lines[3].substringAfter("Test: divisible by ").toInt(),
lines[4].substringAfter("If true: throw to monkey ").toInt(),
lines[5].substringAfter("If false: throw to monkey ").toInt()
)
}
fun applyOp(level: Long, op: List<String>) =
when (op[0]) {
"*" -> level * if (op[1] == "old") level else op[1].toLong()
"+" -> level + if (op[1] == "old") level else op[1].toLong()
else -> {
check(false)
0
}
}
fun solve(monkeys: List<Monkey>, part1: Boolean): Long {
val modVal = monkeys.fold(1L) { acc, monkey -> acc * monkey.test.toLong() }
val rounds = if (part1) 20 else 10_000
val inspections = LongArray(monkeys.size)
repeat(rounds) {
monkeys.forEachIndexed() { i, monkey ->
inspections[i] = inspections[i] + monkey.items.size
while (monkey.items.isNotEmpty()) {
val item = monkey.items.removeFirst()
var newLevel = applyOp(item, monkey.operation)
newLevel = if (part1) newLevel / 3 else newLevel % modVal
val newMonkey = if (newLevel % monkey.test == 0L) monkey.monkeyTrue else monkey.monkeyFalse
monkeys[newMonkey].items.add(newLevel)
}
}
}
// monkeys.forEachIndexed { index, monkey -> println("Monkey $index, ${monkey.inspections} inspections")}
return inspections.sortedDescending().take(2).reduce { acc, l -> acc * l }
}
var testInput = parse(readInputAsOneLine("Day11_test"))
check(solve(testInput.toList(), true) == 10605L)
testInput = parse(readInputAsOneLine("Day11_test"))
check(solve(testInput, false) == 2713310158L)
var input = parse(readInputAsOneLine("Day11"))
println(solve(input, true))
input = parse(readInputAsOneLine("Day11"))
println(solve(input, false))
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 2,654 | AdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | a-glapinski | 572,880,091 | false | {"Kotlin": 26602} | import FilesystemStructure.Directory
import FilesystemStructure.File
import utils.readInputAsText
fun main() {
val input = readInputAsText("day07_input")
val regex = Regex("""\$\s+(\w+)\s+([\s\S]+?)(?=\s+\$|\Z)""")
val commands = regex.findAll(input)
.map { it.groupValues }
.map { (_, command, io) ->
when (command) {
"cd" -> Command.Cd(io)
"ls" -> Command.Ls(io)
else -> error("Unsupported command: $command")
}
}
val filesystem = Filesystem(commands)
val directories = filesystem.rootNode.flatten().filter { it.data is Directory }
val result1 = directories.sumOf { if (it.size <= 100_000) it.size else 0 }
println(result1)
val missingSpace = 30_000_000 - (70_000_000 - filesystem.rootNode.size)
val result2 = directories.mapNotNull { if (it.size >= missingSpace) it.size else null }.min()
println(result2)
}
class Filesystem(commands: Sequence<Command>) {
val rootNode = FilesystemNode(Directory("/"))
private var currentNode = rootNode
init {
commands.forEach { command ->
when (command) {
is Command.Cd ->
currentNode = when (command.input) {
"/" -> rootNode
".." -> currentNode.parent ?: rootNode
else -> currentNode.children.firstOrNull { it.data is Directory && it.data.name == command.input }
?: error("Specified directory: ${command.input} doesn't exist.")
}
is Command.Ls ->
command.structures
.map { FilesystemNode(it, parent = currentNode) }
.let(currentNode.children::addAll)
}
}
}
}
class FilesystemNode(
val data: FilesystemStructure,
val parent: FilesystemNode? = null,
val children: MutableList<FilesystemNode> = mutableListOf(),
) {
val size: Int
get() = when (data) {
is File -> data.size
is Directory -> children.sumOf { it.size }
}
fun flatten(): List<FilesystemNode> = listOf(this) + children.flatMap { it.flatten() }
}
sealed interface FilesystemStructure {
data class Directory(val name: String) : FilesystemStructure
data class File(val name: String, val size: Int) : FilesystemStructure
}
sealed interface Command {
@JvmInline
value class Cd(val input: String) : Command
@JvmInline
value class Ls(val output: String) : Command {
val structures: List<FilesystemStructure>
get() = output.lineSequence()
.map { it.split(' ') }
.map { (size, name) ->
when (size) {
"dir" -> Directory(name)
else -> File(name, size.toInt())
}
}.toList()
}
} | 0 | Kotlin | 0 | 0 | c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8 | 2,952 | advent-of-code-2022 | Apache License 2.0 |
2022/src/test/kotlin/Day11.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
private data class Operation(val op: String, val other: String) {
fun run(level: Long) = when (op) {
"*" -> level * if (other == "old") level else other.toLong()
"+" -> level + if (other == "old") level else other.toLong()
else -> throw IllegalArgumentException()
}
}
private data class Monkey(
val items: MutableList<Long>,
val operation: Operation,
val test: Int,
val ifTrue: Int,
val ifFalse: Int
)
class Day11 : StringSpec({
"puzzle part 01" { chaseMonkeys(20, 3) shouldBe 110220 }
"puzzle part 02" { chaseMonkeys(10000) shouldBe 19457438264 }
})
private fun chaseMonkeys(times: Int, worryLevelDivider: Int = 1): Long {
val monkeys = getMonkeys()
val inspection = MutableList(monkeys.size) { 0L }
val primes = monkeys.map { it.test }.reduce { acc, it -> acc * it }
repeat(times) { _ ->
monkeys.forEachIndexed { index, m ->
m.items.forEach { item ->
inspection[index]++
val level = (m.operation.run(item) / worryLevelDivider) % primes
monkeys[if (level % m.test == 0L) m.ifTrue else m.ifFalse].items += level
}
m.items.clear()
}
}
return inspection.sorted().takeLast(2).reduce { acc, it -> acc * it }
}
private fun getMonkeys() = getPuzzleInput("day11-input.txt", "$eol$eol")
.map {
it.split(eol)
.drop(1)
.let { m ->
Monkey(
m[0].drop(" Starting items: ".length)
.split(", ").map(String::toLong).toMutableList(),
m[1].drop(" Operation: new = old ".length)
.split(" ").let { o -> Operation(o.first(), o.last()) },
m[2].drop(" Test: divisible by ".length).toInt(),
m[3].drop(" If true: throw to monkey ".length).toInt(),
m[4].drop(" If false: throw to monkey ".length).toInt()
)
}
}.toList()
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 2,105 | adventofcode | MIT License |
app/src/y2021/day14/Day14ExtendedPolymerization.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day14
import common.Answers
import common.AocSolution
import common.annotations.AoCPuzzle
typealias PolymerLut = Map<String, List<String>>
typealias PolymerFrequency = Map<String, Long>
fun main(args: Array<String>) {
Day14ExtendedPolymerization().solveThem()
}
@AoCPuzzle(2021, 14)
class Day14ExtendedPolymerization : AocSolution {
override val answers = Answers(samplePart1 = 1588, samplePart2 = 2188189693529, part1 = 2797, part2 = 2926813379532)
override fun solvePart1(input: List<String>): Long {
val (startingPolymer, polymerLut) = input.parse()
return solvePuzzle(startingPolymer, polymerLut, steps = 10)
}
override fun solvePart2(input: List<String>): Long {
val (startingPolymer, polymerLut) = input.parse()
return solvePuzzle(startingPolymer, polymerLut, steps = 40)
}
private fun solvePuzzle(startingPolymer: String, polymerLut: PolymerLut, steps: Int): Long =
startingPolymer
.countPolymerFrequencies()
.proceed(steps, polymerLut)
.getLetterFrequencies(startingPolymer)
.sorted()
.let { it.last() - it.first() }
private fun String.countPolymerFrequencies(): PolymerFrequency = this
.windowed(2)
.groupBy { it }
.mapValues { it.value.size.toLong() }
private fun PolymerFrequency.proceed(steps: Int, lut: PolymerLut): PolymerFrequency {
var mapA: Map<String, Long> = this
repeat(steps) {
val mapB: MutableMap<String, Long> = mutableMapOf()
mapA.forEach { (polymer, amount) ->
lut[polymer]?.forEach {
mapB[it] = mapB.getOrDefault(it, 0) + amount
}
}
mapA = mapB
}
return mapA
}
private fun PolymerFrequency.getLetterFrequencies(startingPolymer: String): List<Long> {
fun Char.isOnEdge(): Boolean =
this == startingPolymer.first() || this == startingPolymer.last()
return keys
.joinToString("")
.toList()
.distinct()
.map { letter ->
this
.filter { it.key.contains(letter) }
.map { (polymer, amount) -> if (polymer == "$letter$letter") 2 * amount else amount }
.sum()
.let {
it / 2 + if (letter.isOnEdge()) 1 else 0
}
}
}
private fun List<String>.parse(): Pair<String, PolymerLut> = Pair(
first(),
subList(2, this.size)
.map { it.split(" -> ") }
.associate { (left, right) ->
Pair(
left,
listOf("${left.first()}$right", "$right${left.last()}")
)
}
)
} | 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 2,850 | advent-of-code-2021 | Apache License 2.0 |
src/Day11.kt | karloti | 573,006,513 | false | {"Kotlin": 25606} | import java.lang.IllegalArgumentException
data class Monkey(
val number: Int,
val worryLevel: MutableList<Long>,
val oppSign: Char,
val oppNumber: Int?,
val div: Int,
val ifTrueMonkeyNum: Int,
val ifFalseMonkeyNum: Int,
var inspectCount: Long = 0,
)
fun List<String>.toMonkey(): Monkey {
val number = get(0).drop(7).dropLast(1).toInt()
val (items, opp, div, t, f) = drop(1)
val worryLevel = items.drop(18).split(", ").map(String::toLong).toMutableList()
val oppSign = opp.drop(23)[0]
val oppNumber = opp.drop(25).toIntOrNull()
val divNumber = div.drop(21).toInt()
val ifTrueMonkeyNum = t.drop(29).toInt()
val ifFalseMonkeyNum = f.drop(30).toInt()
return Monkey(number, worryLevel, oppSign, oppNumber, divNumber, ifTrueMonkeyNum, ifFalseMonkeyNum)
}
fun MutableList<Monkey>.solution(rep: Int, worryDivider: Int): Long {
val mod = map { it.div }.reduce(Int::times)
repeat(rep) {
forEach { monkey: Monkey ->
repeat(monkey.worryLevel.size) {
monkey.inspectCount++
val worry = monkey.worryLevel.removeFirst()
val oppNumber = monkey.oppNumber?.toLong() ?: worry
val result = when (monkey.oppSign) {
'+' -> worry + oppNumber
'-' -> worry - oppNumber
'*' -> worry * oppNumber
'/' -> worry / oppNumber
else -> throw IllegalArgumentException()
} / worryDivider % mod
if (result.rem(monkey.div) == 0L) {
get(monkey.ifTrueMonkeyNum).apply { worryLevel += result }
} else {
get(monkey.ifFalseMonkeyNum).apply { worryLevel += result }
}
}
}
}
return sortedByDescending { it.inspectCount }.take(2).let { (a, b) -> a.inspectCount * b.inspectCount }
}
fun main() {
check(readInput("Day11_test").chunked(7).map { it.toMonkey() }.toMutableList().solution(20, 3) == 10605L)
check(readInput("Day11_test").chunked(7).map { it.toMonkey() }.toMutableList().solution(10000, 1) == 2713310158L)
readInput("Day11").chunked(7).map { it.toMonkey() }.toMutableList().solution(20, 3).let(::println)
readInput("Day11").chunked(7).map { it.toMonkey() }.toMutableList().solution(10000, 1).let(::println)
} | 0 | Kotlin | 1 | 2 | 39ac1df5542d9cb07a2f2d3448066e6e8896fdc1 | 2,383 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day14.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val input = readInput(2023, 14).readLines().map { it.toCharArray() }
part1(input)
part2(input)
}
private fun part1(input: List<CharArray>) {
val sum = tiltVertical(input, north = true, modify = false)
println(sum)
}
private fun part2(input: List<CharArray>) {
val scoreToSpin = hashMapOf<Pair<Int, Int>, Int>() // (hash, score) => spin
val spinToScore = hashMapOf<Int, Int>()
var spin = 0
while (true) {
tiltVertical(input, north = true, modify = true)
tiltHorizontal(input, west = true)
tiltVertical(input, north = false, modify = true)
val sum = tiltHorizontal(input, west = false)
val hash = input.contentHashCode()
val pair = hash to sum
if (pair in scoreToSpin) {
val previousSpin = scoreToSpin.getValue(pair)
val loop = (1_000_000_000 - spin - 1) % (spin - previousSpin)
println(spinToScore[loop + previousSpin])
break
}
scoreToSpin[pair] = spin
spinToScore[spin++] = sum
}
}
private fun tiltVertical(grid: List<CharArray>, north: Boolean, modify: Boolean): Int {
val spaces = IntArray(grid[0].size)
var sum = 0
val progression = grid.indices.run { if (north) this else reversed() }
for (j in progression) {
val row = grid[j]
for (i in row.indices) when (val cell = row[i]) {
'#' -> spaces[i] = 0
'.' -> spaces[i]++
else -> {
val dest = if (north) j - spaces[i] else j + spaces[i]
if (modify && spaces[i] > 0) {
grid[dest][i] = cell
row[i] = '.'
}
sum += grid.size - dest
}
}
}
return sum
}
private fun tiltHorizontal(grid: List<CharArray>, west: Boolean): Int {
val spaces = IntArray(grid.size)
var sum = 0
val progression = grid[0].indices.run { if (west) this else reversed() }
for (i in progression) {
for (j in grid.indices) when (val cell = grid[j][i]) {
'#' -> spaces[j] = 0
'.' -> spaces[j]++
else -> {
if (spaces[j] > 0) {
val dest = if (west) i - spaces[j] else i + spaces[j]
grid[j][dest] = cell
grid[j][i] = '.'
}
sum += grid.size - j
}
}
}
return sum
}
private fun List<CharArray>.contentHashCode(): Int {
var hash = 31
for (c in this) hash += c.contentHashCode() * 31
return hash
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 2,695 | adventofcode | Apache License 2.0 |
src/day11/Day11.kt | treegem | 572,875,670 | false | {"Kotlin": 38876} | package day11
import common.readInput
fun main() {
fun part1(input: List<String>) = solve(input.toSortedMonkeys(), repetitions = 20) { it.div(3) }
fun part2(input: List<String>): Long {
val monkeys = input.toSortedMonkeys()
return solve(monkeys, repetitions = 10_000) { newWorry ->
val multipliedDivisors = monkeys.map { it.testDivisor }.reduce { acc, divisor -> acc * divisor }
newWorry % multipliedDivisors
}
}
val day = "11"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2_713_310_158L)
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
}
private fun solve(monkeys: List<Monkey>, repetitions: Int, handleNewWorries: (Long) -> Long): Long {
repeat(repetitions) {
monkeys.forEach { monkey ->
monkey.inspectReduceWorriesAndThrowItems(monkeys, handleNewWorries)
}
}
return monkeys
.map { it.inspectedItems }
.sortedDescending()
.take(2)
.reduce { acc, inspectionCount -> acc * inspectionCount }
}
| 0 | Kotlin | 0 | 0 | 97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8 | 1,225 | advent_of_code_2022 | Apache License 2.0 |
src/day11.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import kotlin.math.abs
import kotlin.system.exitProcess
private const val DAY = 11
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String -> x.toList() }
val input = loadInput(DAY, false, transformer)
// println(input)
println(solvePart1(input))
println(solvePart2(input))
}
// Part 1
private fun solvePart1(input: List<List<Char>>): Long {
val galaxies = input.mapIndexed { y, row ->
row.mapIndexed { x, cell -> if (cell == '#') Pair(x, y) else null }
}.flatten().filterNotNull()
val emptyCols = (0..input.count()).toSet() - galaxies.map { it.first }.toSet()
val emptyRows = (0..input[0].count()).toSet() - galaxies.map { it.second }.toSet()
return solve(galaxies, emptyCols, emptyRows, 1)
}
fun getCombinations(input: List<Pair<Long, Long>>): List<Pair<Pair<Long, Long>, Pair<Long, Long>>> {
val res = mutableListOf<Pair<Pair<Long, Long>, Pair<Long, Long>>>()
for (i in (0..<input.count())) {
for (c in (i + 1..<input.count())) {
res.add(Pair(input[i], input[c]))
}
}
return res
}
fun solve(input: List<Pair<Int, Int>>, emptyCols: Set<Int>, emptyRows: Set<Int>, expansion: Int): Long {
val galaxies = input.map {
val newC = it.first.toLong() + (emptyCols.count { it2 -> it.first > it2 } * expansion)
val newR = it.second.toLong() + (emptyRows.count { it2 -> it.second > it2 } * expansion)
Pair(newC, newR)
}
val galaxiesCombinations = getCombinations(galaxies)
return galaxiesCombinations.sumOf { abs(it.first.first - it.second.first) + abs(it.first.second - it.second.second) }
}
// Part 2
private fun solvePart2(input: List<List<Char>>): Long {
val galaxies = input.mapIndexed { y, row ->
row.mapIndexed { x, cell -> if (cell == '#') Pair(x, y) else null }
}.flatten().filterNotNull()
val emptyCols = (0..input.count()).toSet() - galaxies.map { it.first }.toSet()
val emptyRows = (0..input[0].count()).toSet() - galaxies.map { it.second }.toSet()
return solve(galaxies, emptyCols, emptyRows, 999999)
} | 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 2,222 | aoc2023 | MIT License |
src/y2023/Day01.kt | a3nv | 574,208,224 | false | {"Kotlin": 34115, "Java": 1914} | package y2023
import utils.readInput
fun main() {
val days: List<Pair<String, Char>> = 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',
).toList()
fun sumCalibrations(input: List<List<Char>>): Int {
return input.sumOf { ("" + it[0] + it[it.size - 1]).toInt() }
}
fun part1(input: List<String>): Int {
return sumCalibrations(input.map { line -> line.filter { char -> char.isDigit() }.toList() })
}
fun part2(input: List<String>): Int {
val digitized: List<List<Char>> = input.map { line ->
line.indices.mapNotNull { index ->
if (line[index].isDigit()) {
line[index]
} else {
days.filter { (dayName, _) -> line.substring(index).startsWith(dayName) }.map { it.second }.firstOrNull()
}
}
}.toList()
return sumCalibrations(digitized)
}
// test if implementation meets criteria from the description, like:
var testInput = readInput("y2023", "Day01_test_part1")
check(part1(testInput) == 142)
println(part1(testInput))
testInput = readInput("y2023", "Day01_test_part2")
check(part2(testInput) == 281)
println(part2(testInput))
val input = readInput("y2023", "Day01")
check(part1(input) == 53651)
println(part1(input))
check(part2(input) == 53894)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ab2206ab5030ace967e08c7051becb4ae44aea39 | 1,570 | advent-of-code-kotlin | Apache License 2.0 |
src/year2022/day14/Day14.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day14
import check
import readInput
import kotlin.math.max
import kotlin.math.min
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day14_test")
check(part1(testInput), 24)
check(part2(testInput), 93)
val input = readInput("2022", "Day14")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val (source, terrain) = parseToSourceAndTerrain(input)
return simulateSandfillAndGetSandCount(source, terrain)
}
private fun part2(input: List<String>): Int {
val (source, terrain) = parseToSourceAndTerrain(input, extraHeight = 2, generateExtraWidth = true)
val bottom = terrain.last()
for (x in bottom.indices) {
bottom[x] = false
}
return simulateSandfillAndGetSandCount(source, terrain)
}
private fun simulateSandfillAndGetSandCount(source: Pos, terrain: Array<Array<Boolean>>): Int {
var sandCount = 0
while (true) {
var sand = source
while (terrain[sand.y][sand.x]) {
val down = terrain.get(sand.down()) ?: return sandCount
if (down) {
sand = sand.down()
continue
}
val downLeft = terrain.get(sand.downLeft()) ?: return sandCount
if (downLeft) {
sand = sand.downLeft()
continue
}
val downRight = terrain.get(sand.downRight()) ?: return sandCount
if (downRight) {
sand = sand.downRight()
continue
}
sandCount++
terrain[sand.y][sand.x] = false
if (sand == source) return sandCount
}
}
}
private data class Pos(val x: Int, val y: Int) {
fun down() = copy(y = y + 1)
fun downLeft() = copy(x = x - 1, y = y + 1)
fun downRight() = copy(x = x + 1, y = y + 1)
}
private fun Array<Array<Boolean>>.get(pos: Pos) = getOrNull(pos.y)?.getOrNull(pos.x)
private fun parseToSourceAndTerrain(
input: List<String>, extraHeight: Int = 0, generateExtraWidth: Boolean = false
): Pair<Pos, Array<Array<Boolean>>> {
var minX = Int.MAX_VALUE
var minY = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
var maxY = Int.MIN_VALUE
val rockPaths = input.map { line ->
line.split(" -> ").map { hint ->
val (x, y) = hint.split(',').map { it.toInt() }
minX = min(minX, x)
minY = min(minY, y)
maxX = max(maxX, x)
maxY = max(maxY, y)
Pos(x, y)
}
}
val extraWidth = if (generateExtraWidth) 2 * (maxY + 1) else 0
val size = Pos(maxX - minX + 1 + extraWidth, maxY + 1 + extraHeight)
val shift = Pos(minX - extraWidth / 2, 0)
val source = Pos(500 - shift.x, 0 - shift.y)
val terrain = Array(size.y) { Array(size.x) { true } }
for (rockPath in rockPaths) {
rockPath.windowed(2) { pair ->
val (pos1, pos2) = pair
if (pos1.x == pos2.x) {
val start = min(pos1.y, pos2.y)
val end = max(pos1.y, pos2.y)
for (y in start..end) {
terrain[y][pos1.x - shift.x] = false
}
} else {
val start = min(pos1.x, pos2.x)
val end = max(pos1.x, pos2.x)
for (x in start..end) {
terrain[pos1.y][x - shift.x] = false
}
}
}
}
return source to terrain
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 3,548 | AdventOfCode | Apache License 2.0 |
src/Day02.kt | toninau | 729,811,683 | false | {"Kotlin": 8423} | fun main() {
val redCubesMax = 12
val greenCubesMax = 13
val blueCubesMax = 14
data class CubeSet(val red: Int, val green: Int, val blue: Int)
data class Game(val gameId: Int, val cubeSets: List<CubeSet>)
fun lineToGame(input: List<String>): List<Game> {
return input.map { line ->
val gameId = line.substring(5, line.indexOf(':')).toInt()
val cubeSets = line.substringAfter(':').split(';')
.map { set ->
val red = "(\\d+) red".toRegex().find(set)?.groupValues?.get(1)?.toInt() ?: 0
val green = "(\\d+) green".toRegex().find(set)?.groupValues?.get(1)?.toInt() ?: 0
val blue = "(\\d+) blue".toRegex().find(set)?.groupValues?.get(1)?.toInt() ?: 0
CubeSet(red, green, blue)
}
Game(gameId, cubeSets)
}
}
fun part1(input: List<String>): Int {
return lineToGame(input)
.filter { line ->
!line.cubeSets.any { it.red > redCubesMax || it.green > greenCubesMax || it.blue > blueCubesMax }
}.sumOf { it.gameId }
}
fun part2(input: List<String>): Int {
return lineToGame(input).sumOf { game ->
val red = game.cubeSets.maxOf { it.red }
val blue = game.cubeSets.maxOf { it.blue }
val green = game.cubeSets.maxOf { it.green }
red * blue * green
}
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b3ce2cf2b4184beb2342dd62233b54351646722b | 1,548 | advent-of-code-2023 | Apache License 2.0 |
src/day05.kt | skuhtic | 572,645,300 | false | {"Kotlin": 36109} | fun main() {
day05.execute(onlyTests = false, forceBothParts = true)
}
val day05 = object : Day<String>(5, "CMZ", "MCD") {
override val testInput: InputData
get() = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent().lines()
override fun part1(input: InputData): String = solution(input, false)
override fun part2(input: InputData): String = solution(input, true)
fun solution(input: InputData, multipleCreatesMove: Boolean): String {
val (stackInput, procedureInput) = input.splitByEmpty()
val stacks = stackInput
.dropLast(1)
.map { line -> line.chunked(4) { it.trim('[', ']', ' ').singleOrNull() } }
.reversed()//.logIt()
.transposedWithNullIfMissing()//.logIt()
.map { ArrayDeque(it.filterNotNull()) }//.logIt()
val procedures = procedureInput
.map { line ->
line.split(' ')
.filterIndexed { i, _ -> i % 2 == 1 }
.map { it.toInt() }
}.map { Triple(it[0], it[1] - 1, it[2] - 1) }//.logIt()
procedures.forEach { (amount, from, to) ->
if (!multipleCreatesMove) repeat(amount) {
stacks[to].addLast(stacks[from].removeLast())
}
else List(amount) { stacks[from].removeLast() }.reversed().forEach {
stacks[to].addLast(it)
}
}
return stacks.fold("") { result, stack -> result + stack.last() }
}
}
fun <T> List<List<T>>.transposed(): List<List<T>> =
List(this.maxOf { it.size }) { j -> List(this.size) { i -> this[i][j] } }
fun <T> List<List<T>>.transposedWithNullIfMissing(): List<List<T?>> =
List(this.maxOf { it.size }) { j -> List(this.size) { i -> this.getOrNull(i)?.getOrNull(j) } }
| 0 | Kotlin | 0 | 0 | 8de2933df90259cf53c9cb190624d1fb18566868 | 2,053 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day13.kt | alex859 | 573,174,372 | false | {"Kotlin": 80552} | fun main() {
val testInput = readInput("Day13_test.txt")
check(testInput.day13Part1() == 13)
check(testInput.day13Part2() == 140)
val input = readInput("Day13.txt")
println(input.day13Part1())
println(input.day13Part2())
}
internal fun String.day13Part1() =
split("\n\n")
.mapIndexed { i, packets ->
(i + 1) to packets
}
.filter { (_, packet) ->
val (leftPacket, rightPacket) = packet.split("\n")
leftPacket.toPacketList() < rightPacket.toPacketList()
}.sumOf { (index, _) -> index }
internal fun String.day13Part2(): Int {
val divider1 = "[[2]]".toPacketList()
val divider2 = "[[6]]".toPacketList()
val all =
replace("\n\n", "\n").lines().map { it.toPacketList() } + listOf(divider1) + listOf(divider2)
val sorted = all.sortedWith { left, right -> (left as List<*>).compareTo(right as List<*> ) }
val filter = sorted.mapIndexed { index, packet -> index + 1 to packet }
.filter { (index, packet) -> packet == divider1 || packet == divider2 }
return filter
.map { (index, _) -> index }
.reduce { a, b -> a * b }
}
internal operator fun List<*>.compareTo(that: List<*>): Int {
return if (isEmpty()) {
if (that.isEmpty()) 0
else -1
} else {
if (that.isEmpty()) 1
else {
val left = this.first()
val right = that.first()
when (isSmaller(left, right)) {
1 -> 1
-1 -> -1
else -> this.drop(1).compareTo(that.drop(1))
}
}
}
}
private fun isSmaller(left: Any?, right: Any?) = when (left) {
is Int -> when (right) {
is Int -> left.compareTo(right)
is List<*> -> listOf(left).compareTo(right)
else -> TODO()
}
is List<*> -> when (right) {
is List<*> -> left.compareTo(right)
is Int -> left.compareTo(listOf(right))
else -> TODO()
}
else -> TODO()
}
internal fun String.toPacketList(): List<Any> {
val stack = mutableListOf<MutableList<Any>>()
val stackN = mutableListOf<Char>()
for (c in this) {
if (c == '[') {
stack.add(0, mutableListOf())
}
if (c.isDigit()) {
stackN.add(c)
}
if (c == ',') {
if (stackN.isNotEmpty()) {
stack.first().add(stackN.joinToString(separator = "").toInt())
stackN.clear()
}
}
if (c == ']') {
if (stackN.isNotEmpty()) {
stack.first().add(stackN.joinToString(separator = "").toInt())
stackN.clear()
}
val current = stack.removeFirst()
if (stack.isEmpty()) stack.add(current)
else stack.first().add(current)
}
}
return stack.first()
} | 0 | Kotlin | 0 | 0 | fbbd1543b5c5d57885e620ede296b9103477f61d | 2,881 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/aoc2022/Day16.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2022
import days.Day
import kotlin.math.max
class Day16 : Day(2022, 16) {
override fun partOne(): Any {
return calculateMaxPressureReliefOverTime(inputList, 30)
}
override fun partTwo(): Any {
return calculateMaxPressureReliefOverTimeWithTwoParticipants(inputList, 26)
}
fun calculateMaxPressureReliefOverTimeWithTwoParticipants(input: List<String>, minutes: Int): Int {
val valves = parseValves(input)
val paths = calculateShortestPathsToEachNonzeroValve(valves)
return calculateHighestScore(
valves.first { it.name == "AA"},
paths,
setOf(),
minutes,
0,
true
)
}
fun calculateMaxPressureReliefOverTime(input: List<String>, minutes: Int): Int {
val valves = parseValves(input)
return calculateHighestScore(
valves.first { it.name == "AA"},
calculateShortestPathsToEachNonzeroValve(valves),
setOf(),
minutes,
0
)
}
private fun calculateHighestScore(current: Valve, shortestPaths: Map<Valve, Map<Valve, Int>>, visited: Set<Valve>, timeLeft: Int, score: Int, isElephantInvolved: Boolean = false): Int {
var max = score
for (next in shortestPaths[current]!!) {
if (next.key !in visited && timeLeft > 1 + next.value) {
max = max(max, calculateHighestScore(
next.key,
shortestPaths,
visited + next.key,
(timeLeft - next.value) - 1,
score + (next.key.flowRate * ((timeLeft - next.value) - 1)),
isElephantInvolved
))
}
}
return if (isElephantInvolved) {
max(max, calculateHighestScore(shortestPaths.keys.first { it.name == "AA" }, shortestPaths, visited, 26, score))
} else {
max
}
}
private fun calculateShortestPathsToEachNonzeroValve(valves: List<Valve>): Map<Valve, Map<Valve, Int>> {
val result = valves.associateWith { valve ->
valve.leadsTo.map { valveName -> valves.first { it.name == valveName } }
.associateWith { 1 }.toMutableMap()
}.toMutableMap()
for (k in valves) {
for (j in valves) {
for (i in valves) {
val ij = result[i]?.get(j) ?: 5000
val ik = result[i]?.get(k) ?: 5000
val kj = result[k]?.get(j) ?: 5000
if (ik + kj < ij) {
result[i]?.set(j, ik + kj)
}
}
}
}
result.forEach { (valve, paths) ->
paths.keys.filter { it.flowRate == 0 }.forEach {
result[valve]!!.remove(it)
}
}
return result
}
// Valve AA has flow rate=0; tunnels lead to valves DD, II, BB
private fun parseValves(input: List<String>): List<Valve> {
return input.map { line ->
Regex("Valve (\\w+) has flow rate=(\\d+); tunnel[s]? lead[s]? to valve[s]? (.*)").matchEntire(line)
?.destructured?.let { (name, flowRate, destinations) ->
val leadsTo = mutableListOf<String>()
destinations.split(", ").forEach { destination ->
leadsTo.add(destination)
}
Valve(name, flowRate.toInt(), leadsTo)
} ?: throw IllegalStateException()
}
}
class Valve(val name: String, val flowRate: Int, val leadsTo: List<String>)
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,724 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
aoc/src/Soil.kt | aragos | 726,211,893 | false | {"Kotlin": 16232} | import java.io.File
import java.lang.IllegalArgumentException
data class Range(val sourceStart: Long, val destinationStart: Long, val rangeLength: Long) {
val sources = LongRange(sourceStart, sourceStart + rangeLength - 1)
override fun toString(): String {
return "$sources -> ${LongRange(destinationStart, destinationStart + rangeLength - 1)}"
}
fun mapId(id: Long) = destinationStart + id - sourceStart
fun invert() = Range(destinationStart, sourceStart, rangeLength)
}
class Mapping(val name: String, ranges: Set<Range>) {
val sortedRanges = ranges.sortedBy { it.sources.start }
fun map(sourceId: Long): Long {
for (range in sortedRanges) {
if (sourceId < range.sources.start) {
return sourceId
} else if (sourceId in range.sources) {
return range.mapId(sourceId)
}
}
return sourceId
}
override fun toString(): String {
return "Mapping:\n" + sortedRanges.joinToString(separator = "\n") { " $it" }
}
}
fun main() {
val lines = File("inputs/soil.txt").readLines()
val rawSeeds = Regex("\\d+").findAll(lines[0].split(":")[1]).map { it.value.toLong() }
val mappings = lines.parseMappings()
// println(calculateMinLocationSimpleSeeds(rawSeeds, mappings))
println(calculateMinLocationSeedRanges(rawSeeds, mappings))
}
fun calculateMinLocationSeedRanges(rawSeeds: Sequence<Long>, forwardMappings: List<Mapping>): Long {
val seedRanges = rawSeeds
.chunked(2)
.map { pair -> LongRange(start = pair[0], endInclusive = pair[0] + pair[1] - 1) }
.sortedBy { range -> range.start }
.toList()
val reverseMappings = forwardMappings.map { mapping ->
Mapping("~${mapping.name}", mapping.sortedRanges.map { it.invert() }.toSet())
}.reversed()
val locations2Humidity = reverseMappings.first()
locations2Humidity.sortedRanges.forEach { range ->
range.sources.forEach { location ->
val seed = reverseMappings.fold(location)
seedRanges.forEach { seedRange ->
if (seed in seedRange) {
return location
}
}
}
}
throw IllegalArgumentException()
}
private fun calculateMinLocationSimpleSeeds(
rawSeeds: Sequence<Long>,
mappings: List<Mapping>,
): Long = rawSeeds.map { value ->
mappings.fold(value)
}.min()
private fun List<Mapping>.fold(value: Long) =
this.fold(value) { acc, mapping ->
mapping.map(acc)
}
private fun List<String>.parseMappings(): List<Mapping> {
val seed2Soil = parseMapping("seed2Soil", startInclusive = 3, endExclusive = 32)
val soil2Fertilizer = parseMapping("soil2Fertilizer", startInclusive = 34, endExclusive = 53)
val fertilizer2Water = parseMapping("fertilizer2Water", startInclusive = 55, endExclusive = 97)
val water2Light = parseMapping("water2Light", startInclusive = 99, endExclusive = 117)
val light2Temperature =
parseMapping("light2Temperature", startInclusive = 119, endExclusive = 132)
val temperature2Humidity =
parseMapping("temperature2Humidity", startInclusive = 135, endExclusive = 144)
val humidity2Location =
parseMapping("humidity2Location", startInclusive = 146, endExclusive = 190)
return listOf(
seed2Soil,
soil2Fertilizer,
fertilizer2Water,
water2Light,
light2Temperature,
temperature2Humidity,
humidity2Location
)
}
private fun List<String>.parseMapping(
name: String,
startInclusive: Int,
endExclusive: Int,
): Mapping =
Mapping(name, subList(startInclusive, endExclusive).map { line ->
val numbers = Regex("\\d+").findAll(line).map { it.value.toLong() }.toList()
Range(sourceStart = numbers[1], destinationStart = numbers[0], rangeLength = numbers[2])
}.toSet())
| 0 | Kotlin | 0 | 0 | 7bca0a857ea42d89435adc658c0ff55207ca374a | 3,670 | aoc2023 | Apache License 2.0 |
src/main/kotlin/day11/day11.kt | corneil | 572,437,852 | false | {"Kotlin": 93311, "Shell": 595} | package day11
import main.utils.*
import utils.readFile
import utils.separator
inline operator fun <T> List<T>.component6(): T {
return get(5)
}
fun main() {
val test = readFile("day11_test")
val input = readFile("day11")
data class Monkey(
val number: Int,
val worriedLevel: Long,
val items: MutableList<Long>,
val boredTarget: Int,
val worriedTarget: Int,
val expression: (Long) -> Long,
) {
var inspected: Int = 0
private set
fun inspect(value: Int = 1) {
inspected += value
}
fun findTarget(boredLevel: Long) = if (boredLevel % worriedLevel != 0L) worriedTarget else boredTarget
override fun toString(): String {
return "Monkey(number=$number, inspected=$inspected, worriedLevel=$worriedLevel, boredTarget=$boredTarget, worriedTarget=$worriedTarget, items=$items)"
}
}
val regexMonkey = listOf(
"Monkey (\\d+):$",
" Starting items:\\s*((\\S+(,\\s)*)*)\$",
" Operation: new =\\s(\\S+)\\s(\\+|\\*)\\s(\\S+)\$",
" Test: divisible by (\\d+)$",
" If true: throw to monkey (\\d+)$",
" If false: throw to monkey (\\d+)$"
).map { it.toRegex() }
fun parseMonkey(lines: List<String>): Monkey {
return lines.let { (number, itemStr, operation, worried, trueTarget, falseTarget) ->
val items = itemStr.scanNumbers().map { it.toLong() }.toMutableList()
val words = operation.substringAfter("new = ").split(" ")
check(words[0] == "old") { "Expected old but found ${words}"}
val isAdd = words[1] == "+"
val constant = words[2].toLongOrNull()
val lambda: (Long) -> Long =
if (isAdd) { old -> old + (constant ?: old) } else { old -> old * (constant ?: old) }
Monkey(
number.scanInt(),
worried.scanNumber()!!.toLong(),
items,
trueTarget.scanInt(),
falseTarget.scanInt(),
lambda
)
}
}
fun processItems(monkeys: Map<Int, Monkey>, rounds: Int, divisor: Long): Map<Int, Monkey> {
// The mod of the total of worriedLevels overcomes the Long overflow
// using all divisors ensure that it is the smallest value that will
// still satisfy all the requirements when using a large number of rounds
val divisors = monkeys.values
.map { monkey -> monkey.worriedLevel }
.reduce { acc, l -> acc * l * divisor }
val sorted = monkeys.values.sortedBy { it.number }
repeat(rounds) {
sorted.forEach { monkey ->
monkey.items.forEach { item ->
val level = monkey.expression(item)
val bored = level / divisor
val targetNumber = monkey.findTarget(bored)
val targetMonkey = monkeys[targetNumber] ?: error("Cannot find target Monkey:$targetNumber")
targetMonkey.items.add(bored % divisors) // mod to ensure smallest valid value
}
monkey.inspect(monkey.items.size)
monkey.items.clear()
}
}
return monkeys
}
fun calcShenanigans1(input: List<String>): Int {
val monkeys = input.chunked(7)
.map { parseMonkey(it) }
.associateBy { it.number }
println("Before: ====")
monkeys.values.forEach { println(it.toString()) }
val result = measureAndPrint("Part 1 Time: ") {
processItems(monkeys, 20, 3)
}
println("After: ====")
result.values.forEach { println(it.toString()) }
return result.values.map { it.inspected }
.sortedDescending()
.take(2)
.reduce { acc, i -> acc * i }
}
fun calcShenanigans2(input: List<String>): Long {
val monkeys = input.chunked(7)
.map {
parseMonkey(it)
}.associateBy { it.number }
println("Before: ====")
monkeys.values.forEach { println(it.toString()) }
val result = measureAndPrint("Part 2 Time: ") {
processItems(monkeys, 10000, 1)
}
println("After: ====")
result.values.forEach { println(it.toString()) }
return result.values.map { it.inspected.toLong() }
.sortedDescending()
.take(2)
.reduce { acc, i -> acc * i }
}
fun part1() {
val testResult = calcShenanigans1(test)
println("Part 1 Answer = $testResult")
check(testResult == 10605)
val result = calcShenanigans1(input)
println("Part 1 Answer = $result")
check(result == 151312)
}
fun part2() {
val testResult = calcShenanigans2(test)
println("Part 2 Answer = $testResult")
check(testResult == 2713310158L)
val result = calcShenanigans2(input)
println("Part 2 Answer = $result")
check(result == 51382025916L)
}
println("Day - 11")
separator()
part1()
separator()
part2()
}
| 0 | Kotlin | 0 | 0 | dd79aed1ecc65654cdaa9bc419d44043aee244b2 | 4,615 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day02/Day02.kt | shiddarthbista | 572,833,784 | false | {"Kotlin": 9985} | package day02
import readInput
fun main() {
fun part1(input: List<String>): Int =
input.sumOf {
calculateScore(it.split(" ").first(), it.split(" ").last(),1)
}
fun part2(input: List<String>): Int =
input.sumOf {
calculateScore(it.split(" ").first(), it.split(" ").last(),2)
}
val testInput = readInput("Day02_test")
val input = readInput("Day02")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
println(part1(input))
println(part2(input))
}
fun calculateScore(opponent: String, player: String, part: Int): Int {
val pointBook = mapOf(
"A" to mapOf("X" to 4, "Y" to 8, "Z" to 3),
"B" to mapOf("X" to 1, "Y" to 5, "Z" to 9),
"C" to mapOf("X" to 7, "Y" to 2, "Z" to 6)
)
val pointBook2 = mapOf(
"A" to mapOf("X" to 3, "Y" to 4, "Z" to 8),
"B" to mapOf("X" to 1, "Y" to 5, "Z" to 9),
"C" to mapOf("X" to 2, "Y" to 6, "Z" to 7)
)
return when(part){
1 -> pointBook.getValue(opponent).getValue(player)
2 -> pointBook2.getValue(opponent).getValue(player)
else -> error("Invalid Input")
}
}
| 0 | Kotlin | 0 | 0 | ed1b6a132e201e98ab46c8df67d4e9dd074801fe | 1,185 | aoc-2022-kotlin | Apache License 2.0 |
src/Day04A.kt | Venkat-juju | 572,834,602 | false | {"Kotlin": 27944} | import kotlin.system.measureNanoTime
data class SectionRangeB(
val startSection : Int,
val endSection: Int
)
infix fun IntRange.contains(other: IntRange): Boolean {
return other.first >= this.first && other.last <= this.last
}
infix fun SectionRangeB.isFullyContainedB(other: SectionRangeB): Boolean {
return this.startSection..this.endSection contains other.startSection .. other.endSection ||
other.startSection .. other.endSection contains this.startSection..this.endSection
}
infix fun SectionRangeB.isAtleastSingleSectionOverlapB(other: SectionRangeB): Boolean {
return this.startSection in other.startSection.. other.endSection || other.startSection in this.startSection .. this.endSection
}
fun String.toSectionRangeB(): List<SectionRangeB> {
val (firstSectionStart, firstSectionEnd, secondSectionStart, secondSectionEnd) = this.split(',', '-').map(String::toInt)
return listOf(SectionRangeB(firstSectionStart, firstSectionEnd), SectionRangeB(secondSectionStart, secondSectionEnd))
}
fun main() {
fun part1(input: List<String>): Int {
return input.map(String::toSectionRangeB).count { it.first() isFullyContainedB it.last() }
}
fun part2(input: List<String>): Int {
return input.map(String::toSectionRangeB).count { it.first() isAtleastSingleSectionOverlapB it.last() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
val timeTake = measureNanoTime {
println(part1(input))
println(part2(input))
}
println("Time taken: $timeTake ns")
}
| 0 | Kotlin | 0 | 0 | 785a737b3dd0d2259ccdcc7de1bb705e302b298f | 1,727 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | fun main() {
data class Operation(val amount: Int, val from: Int, val to: Int)
fun parseStack(input: List<String>): List<ArrayDeque<Char>> {
/*
[D]
[N] [C]
[Z] [M] [P]
1 2 3
*/
val reversed = input.reversed()
val numberOfStacks = (reversed.first().length + 1) / 4
val stacks = (1..numberOfStacks).map { ArrayDeque<Char>() }
reversed.drop(1).forEach {
it.chunked(4).withIndex().forEach { (index, it) ->
val crate = it[1]
if (crate != ' ') {
stacks[index].addLast(crate)
}
}
}
return stacks
}
fun parseOperations(input: List<String>): List<Operation> {
return input.map {
// move AMOUNT from FROM to TO
val parts = it.split(' ')
Operation(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
}
}
fun parseInput(input: List<String>): Pair<List<ArrayDeque<Char>>, List<Operation>> {
val splitAt = input.indexOfFirst { it.isEmpty() }
val stackLines = input.take(splitAt)
val operationLines = input.drop(splitAt + 1)
return parseStack(stackLines) to parseOperations(operationLines)
}
fun part1(input: List<String>): String {
val (stacks, operations) = parseInput(input)
for (operation in operations) {
val from = stacks[operation.from]
val to = stacks[operation.to]
repeat(operation.amount) {
to.addLast(from.removeLast())
}
}
return stacks.map { it.last() }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val (stacks, operations) = parseInput(input)
for (operation in operations) {
val from = stacks[operation.from]
val to = stacks[operation.to]
val removed = mutableListOf<Char>()
repeat(operation.amount) {
removed += from.removeLast()
}
removed.reversed().forEach { to.addLast(it) }
}
return stacks.map { it.last() }.joinToString(separator = "")
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 2,452 | advent-of-code-2022 | Apache License 2.0 |
src/year2015/day20/Day20.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2015.day20
import readInput
import kotlin.math.sqrt
fun main() {
val input = readInput("2015", "Day20")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val minPresents = input.first().toInt()
val pf = PrimeFactors(minPresents / 10)
for (n in 1..minPresents) {
val factors = pf.getFactors(n)
val presents = factors.sum() * 10
if (presents >= minPresents) return n
}
error("!")
}
private fun part2(input: List<String>): Int {
val minPresents = input.first().toInt()
val pf = PrimeFactors(minPresents / 11)
for (n in minPresents / 50..minPresents) {
val factors = pf.getFactors(n).filter { it >= n / 50 }
val presents = factors.sum() * 11
if (presents >= minPresents) return n
}
error("!")
}
private class PrimeFactors(
max: Int
) {
var spf = getSpf(max)
private fun getSpf(max: Int): Array<Int> {
val spf = Array(max) { it }
for (i in 2..sqrt(max.toDouble()).toInt()) {
if (spf[i] == i) {
for (j in i * i until max step i) {
if (spf[j] == j) {
spf[j] = i
}
}
}
}
return spf
}
fun getPrimeFactors(n: Int): List<Int> {
var num = n
val ret = arrayListOf<Int>()
while (num != 1) {
ret.add(spf[num])
num /= spf[num]
}
return ret
}
fun getFactors(n: Int): List<Int> {
val primes = getPrimeFactors(n)
val result = hashSetOf<Int>()
val queue = ArrayDeque(primes)
while (queue.isNotEmpty()) {
val p = queue.removeFirst()
result += result.map { p * it }
result += p
}
result += 1
return result.toList().sorted()
}
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,908 | AdventOfCode | Apache License 2.0 |
src/day15/puzzle15.kt | brendencapps | 572,821,792 | false | {"Kotlin": 70597} | package day15
import Puzzle
import PuzzleInput
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.File
import kotlin.math.abs
fun day15Puzzle() {
Day15PuzzleSolution().solve(Day15PuzzleInput("inputs/day15/example.txt",10, 26))
Day15PuzzleSolution().solve(Day15PuzzleInput("inputs/day15/example.txt",9, 25))
Day15PuzzleSolution().solve(Day15PuzzleInput("inputs/day15/example.txt",11, 28))
Day15PuzzleSolution().solve(Day15PuzzleInput("inputs/day15/input.txt", 2000000, 5525990))
Day15Puzzle2Solution().solve(Day15PuzzleInput("inputs/day15/example.txt", 20, 56000011))
Day15Puzzle2Solution().solve(Day15PuzzleInput("inputs/day15/input.txt", 4000000, 11756174628223))
}
data class RangeOfInterest(val range: IntRange, val hasBeacon: Boolean) : Comparable<RangeOfInterest> {
override fun compareTo(other: RangeOfInterest): Int {
return if(range.first < other.range.first) {
-1
}
else if(range.first == other.range.first) {
if(range.last > other.range.last) {
-1
} else if(other.range.last == range.last) {
0
}
else {
1
}
}
else {
1
}
}
}
data class Beacon(val x: Int, val y: Int)
data class Sensor(val x: Int, val y: Int, val nearestBeacon: Beacon) {
val distance = abs(y - nearestBeacon.y) + abs(x - nearestBeacon.x)
fun pointsOfInterestRange(rowOfInterest: Int ): RangeOfInterest? {
IntRange(y - distance, y + distance).contains(nearestBeacon.y)
if(IntRange(y - distance, y + distance).contains(rowOfInterest)) {
val range = distance - abs(rowOfInterest - y)
val r = IntRange(x - range, x + range)
if(r.contains(nearestBeacon.x) && nearestBeacon.y == rowOfInterest) {
// beacon must be at one of the ends. Trim the range.
if(r.first == r.last) {
return null
}
else if(nearestBeacon.x == r.first) {
return RangeOfInterest(IntRange(r.first + 1, r.last), true)
}
else {
return RangeOfInterest(IntRange(r.first, r.last - 1), true)
}
}
else {
return RangeOfInterest(r, false)
}
}
return null
}
}
class Day15PuzzleInput(val input: String, val rowOfInterest: Int, expectedResult: Long? = null) : PuzzleInput<Long>(expectedResult) {
val sensorList: List<Sensor> =
File(input).readLines().map { line ->
val parser = "Sensor at x=(-?\\d*), y=(-?\\d*): closest beacon is at x=(-?\\d*), y=(-?\\d*)".toRegex()
val matcher = parser.find(line) ?: error("regex issue with $line")
val (sx, sy, bx, by) = matcher.destructured
Sensor(sx.toInt(), sy.toInt(), Beacon(bx.toInt(), by.toInt()))
}
}
class Day15PuzzleSolution : Puzzle<Long, Day15PuzzleInput>() {
override fun solution(input: Day15PuzzleInput): Long {
val ranges = input.sensorList.mapNotNull { sensor ->
sensor.pointsOfInterestRange(input.rowOfInterest)
}.sorted()
var sum = 0
var previousRange: IntRange? = null
for(i in ranges.indices) {
if(previousRange == null) {
sum += ranges[i].range.last - ranges[i].range.first + 1
previousRange = ranges[i].range
}
else {
if(ranges[i].range.last <= ranges[i-1].range.last) {
// Contains, don't add.
}
else if(ranges[i].range.first <= previousRange.last) {
// Overlaps
previousRange = IntRange(previousRange.last + 1, ranges[i].range.last)
sum += previousRange.last - previousRange.first + 1
}
else {
sum += ranges[i].range.last - ranges[i].range.first + 1
previousRange = ranges[i].range
}
}
}
return sum.toLong()
}
}
class Day15Puzzle2Solution : Puzzle<Long, Day15PuzzleInput>() {
override fun solution(input: Day15PuzzleInput): Long {
var answer: Long = 0
runBlocking {
for (y in 0..input.rowOfInterest) {
launch {
val ranges = input.sensorList.mapNotNull { sensor ->
sensor.pointsOfInterestRange(y)
}.sorted()
var range: IntRange? = null
for (i in ranges.indices) {
if (range == null) {
range = ranges[i].range
} else {
if (ranges[i].range.first > range.last) {
for (x in range.last + 1 until ranges[i].range.first) {
if (!input.sensorList.any { (it.x == x && it.y == y) || (it.nearestBeacon.x == x && it.nearestBeacon.y == y) }) {
// We have found a gap.
println("Potential distress at $x $y")
answer = x.toLong() * 4000000 + y.toLong()
println("$answer")
return@launch
}
}
}
if (ranges[i].range.last > range.last) {
range = IntRange(range.first, ranges[i].range.last)
}
}
}
}
}
}
return answer
}
} | 0 | Kotlin | 0 | 0 | 00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3 | 6,049 | aoc_2022 | Apache License 2.0 |
src/day20/a/day20a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day20.a
import readInputLines
import shouldBe
fun main() {
val input = read()
val reordered = ArrayList(input)
rotateOnce(input, reordered)
val j = reordered.indexOfFirst { it.value == 0L }
val answer = (1..3).sumOf { reordered[(j + it * 1000) % reordered.size].value }
shouldBe(7225, answer)
}
fun rotateOnce(order: List<Num>, reordered: ArrayList<Num>) {
order.forEach{ n -> move(reordered, reordered.indexOf(n), n.value) }
}
fun move(list: ArrayList<Num>, idx: Int, dist: Long) {
var d = (dist % (list.size-1)).toInt()
if (d < 0) {
d = -d
val n = list[idx]
if (d <= idx) {
for (i in idx downTo idx - d + 1)
list[i] = list[i - 1]
list[idx - d] = n
} else {
for (i in idx until list.size - d + idx - 1)
list[i] = list[i + 1]
list[list.size - d + idx - 1] = n
}
} else if (d > 0) {
val n = list[idx]
if (idx + d < list.size) {
for (i in idx until idx + d)
list[i] = list[i + 1]
list[idx + d] = n
} else {
for (i in idx downTo idx + d - list.size + 2)
list[i] = list[i - 1]
list[idx + d - list.size + 1] = n
}
}
}
class Num( var value: Long ) {
override fun toString() = value.toString()
}
fun read(): List<Num> {
return readInputLines(20)
.filter { it.isNotBlank() }
.map { line -> line.toInt() }
.map { v -> Num(v.toLong()) }
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 1,553 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | zirman | 572,627,598 | false | {"Kotlin": 89030} | fun main() {
fun ranges(pair: String): List<IntRange> {
return pair.split(',')
.map {
it.split('-')
.let { (start, end) -> start.toInt()..end.toInt() }
}
}
fun part1(input: List<String>): Long {
return input.sumOf { pair ->
ranges(pair)
.let { (range1, range2) ->
val units = range1.intersect(range2).size
units == range1.last + 1 - range1.first ||
units == range2.last + 1 - range2.first
}
.let { if (it) 1L else 0L }
}
}
fun part2(input: List<String>): Long {
return input.sumOf { pair ->
ranges(pair)
.let { (a, b) -> a.intersect(b).isNotEmpty() }
.let { if (it) 1L else 0L }
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2L)
check(part2(testInput) == 4L)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 2ec1c664f6d6c6e3da2641ff5769faa368fafa0f | 1,157 | aoc2022 | Apache License 2.0 |
aoc2016/aoc2016-kotlin/src/main/kotlin/de/havox_design/aoc2016/day24/AirDuctSpelunking.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2016.day24
import de.havox_design.aoc.utils.kotlin.model.positions.Position2d
import java.util.ArrayDeque
class AirDuctSpelunking(private var filename: String) {
fun solvePart1(): Int =
shortestPath(parseInput(), false)
fun solvePart2(): Int =
shortestPath(parseInput(), true)
private fun shortestPath(map: List<List<Position>>, isReturning: Boolean): Int {
val (targets, distances) = mapDistances(map)
.let {
it
.keys
.flatMap { (a, b) -> listOf(a, b) }
.toSet() to it
}
fun move(leftover: Set<Int>, current: Int, steps: Int): Int =
if (leftover.isEmpty()) {
steps + (distances.getValue(current to 0).takeIf { isReturning } ?: 0)
} else {
targets
.filter { it in leftover }
.minOf { move(leftover - it, it, steps + distances.getValue(current to it)) }
}
return move(targets - 0, 0, 0)
}
private fun mapDistances(map: List<List<Position>>): Map<Pair<Int, Int>, Int> {
val targets = map
.flatMap { r -> r.mapNotNull { p -> p.n?.let { it to p } } }
.toMap()
return targets
.flatMap { (target, position) ->
targets
.filter { it.key > target }
.flatMap { (otherTarget, otherPosition) ->
val distance = position.from(otherPosition, map)
listOf(target to otherTarget, otherTarget to target).map { it to distance }
}
}
.toMap()
}
private fun Position.from(other: Position, board: List<List<Position>>): Int {
val seen = mutableMapOf(this to 0)
val queue = ArrayDeque<Position>().also { it.add(this) }
while (queue.isNotEmpty()) {
val current = queue.pop()
val distance = seen.getValue(current)
if (current == other) {
return distance
}
listOf(
board[current.position.y][current.position.x - 1],
board[current.position.y][current.position.x + 1],
board[current.position.y - 1][current.position.x],
board[current.position.y + 1][current.position.x]
)
.filter { it.isValid && !it.isWall && it !in seen }
.let { neighbors ->
seen.putAll(neighbors.map { it to distance + 1 })
queue.addAll(neighbors)
}
}
return 0
}
private fun parseInput(): List<List<Position>> {
val input = getResourceAsText(filename)
return input
.indices
.map { y ->
input[0]
.indices
.map { x -> Position(Position2d(x, y), input[y][x].toString()) }
}
}
private fun getResourceAsText(path: String): List<String> =
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
}
| 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 3,189 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day09.kt | dliszewski | 573,836,961 | false | {"Kotlin": 57757} | import kotlin.math.abs
class Day09 {
fun part1(input: List<String>): Int {
val movement = input.map { it.split(" ") }
.flatMap { (direction, step) -> (1..step.toInt()).map { direction.toDirection() } }
return simulateMoves(movement, 2).size
}
fun part2(input: List<String>): Int {
val movement = input.map { it.split(" ") }
.flatMap { (direction, step) -> (1..step.toInt()).map { direction.toDirection() } }
return simulateMoves(movement, 10).size
}
private fun simulateMoves(moves: List<Direction>, knotsNumber: Int): Set<Point> {
val knots = MutableList(knotsNumber) { Point(0, 0) }
val visitedTail = mutableSetOf<Point>()
visitedTail.add(knots.last())
moves.forEach { direction ->
knots[0] = knots[0].move(direction)
for ((headIndex, tailIndex) in knots.indices.zipWithNext()) {
val head = knots[headIndex]
val tail = knots[tailIndex]
if (!tail.isAdjacentTo(head)) {
knots[tailIndex] = tail.moveTowards(head)
}
}
visitedTail.add(knots.last())
}
return visitedTail
}
private fun Point.move(direction: Direction): Point {
return when (direction) {
Direction.UP -> Point(x, y + 1)
Direction.DOWN -> Point(x, y - 1)
Direction.LEFT -> Point(x - 1, y)
Direction.RIGHT -> Point(x + 1, y)
}
}
private fun Point.isAdjacentTo(other: Point): Boolean {
return abs(x - other.x) <= 1 && abs(y - other.y) <= 1
}
private fun Point.moveTowards(head: Point): Point {
return Point(
x + (head.x - x).coerceIn(-1..1),
y + (head.y - y).coerceIn(-1..1)
)
}
data class Point(val x: Int, val y: Int)
enum class Direction { UP, DOWN, LEFT, RIGHT }
private fun String.toDirection(): Direction {
return when (this) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> error("wrong direction $this")
}
}
}
| 0 | Kotlin | 0 | 0 | 76d5eea8ff0c96392f49f450660220c07a264671 | 2,226 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day19.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 19 - Beacon Scanner
* Problem Description: http://adventofcode.com/2021/day/19
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day19/
*/
package com.ginsberg.advent2021
class Day19(input: String) {
private val scanners: List<Set<Point3d>> = parseInput(input)
fun solvePart1(): Int =
solve().beacons.size
fun solvePart2(): Int =
solve().scanners.pairs().maxOf { it.first distanceTo it.second }
private fun solve(): Solution {
val baseSector = scanners.first().toMutableSet()
val foundScanners = mutableSetOf(Point3d(0,0,0))
val unmappedSectors = ArrayDeque<Set<Point3d>>().apply { addAll(scanners.drop(1)) }
while(unmappedSectors.isNotEmpty()) {
val thisSector = unmappedSectors.removeFirst()
when (val transform = findTransformIfIntersects(baseSector, thisSector)) {
null -> unmappedSectors.add(thisSector)
else -> {
baseSector.addAll(transform.beacons)
foundScanners.add(transform.scanner)
}
}
}
return Solution(foundScanners, baseSector)
}
private fun findTransformIfIntersects(left: Set<Point3d>, right: Set<Point3d>): Transform? =
(0 until 6).firstNotNullOfOrNull { face ->
(0 until 4).firstNotNullOfOrNull { rotation ->
val rightReoriented = right.map { it.face(face).rotate(rotation) }.toSet()
left.firstNotNullOfOrNull { s1 ->
rightReoriented.firstNotNullOfOrNull { s2 ->
val difference = s1 - s2
val moved = rightReoriented.map { it + difference }.toSet()
if (moved.intersect(left).size >= 12) {
Transform(difference, moved)
} else null
}
}
}
}
private class Transform(val scanner: Point3d, val beacons: Set<Point3d>)
private class Solution(val scanners: Set<Point3d>, val beacons: Set<Point3d>)
private fun parseInput(input: String): List<Set<Point3d>> =
input.split("\n\n").map { singleScanner ->
singleScanner
.lines()
.drop(1)
.map { Point3d.of(it) }
.toSet()
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 2,462 | advent-2021-kotlin | Apache License 2.0 |
src/day18/Day18.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day18
import day18.Cube.Companion.normals
import readInput
import kotlin.math.sqrt
fun main() {
val day = 18
val testInput = readInput("day$day/testInput")
// check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("day$day/input")
println(part1(input))
// println(part2(input))
}
fun part1(input: List<String>): Int {
val cubes = input.map {
val (x, y, z) = it.split(',').map { it.toInt() }
Cube(Point3D(x, y, z))
}
val addedCubes = mutableListOf<Cube>()
cubes.forEach { c ->
addedCubes.forEach { added ->
val diff = added.origin - c.origin
if (added.faces.containsKey(diff)) {
added.faces[diff] = true
}
// for second we invert diff
val invertedDiff = Point3D(-diff.x, -diff.y, -diff.z)
if (c.faces.containsKey(invertedDiff)) {
c.faces[invertedDiff] = true
}
}
addedCubes.add(c)
}
val res = addedCubes.map {
it.faces.values.count { isConnected -> !isConnected }
}.sum()
println(res)
return res
}
fun part2(input: List<String>): Int {
val cubes = input.map {
val (x, y, z) = it.split(',').map { it.toInt() }
Cube(Point3D(x, y, z))
}
val addedCubes = mutableSetOf<Cube>()
cubes.forEach { c ->
addedCubes.forEach { added ->
val diff = added.origin - c.origin
if (added.faces.containsKey(diff)) {
added.faces[diff] = true
}
// for second we invert diff
val invertedDiff = Point3D(-diff.x, -diff.y, -diff.z)
if (c.faces.containsKey(invertedDiff)) {
c.faces[invertedDiff] = true
}
}
addedCubes.add(c)
}
addedCubes.forEach { c ->
c.faces.filter { !it.value }.keys.forEach { normal ->
// checking is there cube standing in each direction, if so then it is trap
// don't check opposite to current normal
var isBlocked = true
// it should be air
val checkPoint = c.origin + normal
normals.forEach { n ->
val check = checkPoint + n
if (!addedCubes.contains(Cube(check))) {
isBlocked = false
}
}
if (addedCubes.contains(Cube(checkPoint))) {
isBlocked = true
}
c.faces[normal] = isBlocked
}
}
// additional check for every side
val res = addedCubes.map {
it.faces.values.count { isConnected -> !isConnected }
}.sum()
println(res)
return res}
data class Point3D(val x: Int, val y: Int, val z: Int) {
operator fun minus(p: Point3D): Point3D {
return Point3D(p.x - x, p.y - y, p.z - z)
}
operator fun plus(p: Point3D): Point3D {
return Point3D(p.x + x, p.y + y, p.z + z)
}
}
data class Cube(val origin: Point3D, private val sideSize: Int = 1) {
companion object {
val rightNormal = Point3D(1, 0, 0)
val leftNormal = Point3D(-1, 0, 0)
val frontNormal = Point3D(0, 1, 0)
val backNormal = Point3D(0, -1, 0)
val upNormal = Point3D(0, 0, 1)
val downNormal = Point3D(0, 0, -1)
val normals = listOf(rightNormal, leftNormal, frontNormal, backNormal, upNormal, downNormal)
}
/**
* @param key - normal direction
* @param value - is side, defined by this normal is part of external space
* (not connected with other cubes' size and is not trapped)
*/
val faces: MutableMap<Point3D, Boolean> = closedFacesMap()
// for now only for 1 size cubes
fun distance(cube: Cube): Double {
return sqrt(
(cube.origin.x - origin.x) * (cube.origin.x - origin.x).toDouble() +
(cube.origin.y - origin.y) * (cube.origin.y - origin.y) +
(cube.origin.z - origin.z) * (cube.origin.z - origin.z)
)
}
private fun closedFacesMap(): MutableMap<Point3D, Boolean> {
val res = mutableMapOf<Point3D, Boolean>()
normals.forEach { v ->
res[v] = false
}
return res
}
}
| 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 4,303 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | kmakma | 574,238,598 | false | null | fun main() {
val oneX = Coord2D(1, 0)
val oneY = Coord2D(0, 1)
data class Motion(val dir: Char, val count: Int)
fun mapToMotions(input: List<String>): List<Motion> {
return input.map {
val (d, c) = it.split(" ")
Motion(d.first(), c.toInt())
}
}
fun moveInDir(coor: Coord2D, dir: Char): Coord2D {
return when (dir) {
'L' -> Coord2D(coor.x - 1, coor.y)
'R' -> Coord2D(coor.x + 1, coor.y)
'U' -> Coord2D(coor.x, coor.y + 1)
'D' -> Coord2D(coor.x, coor.y - 1)
else -> error("bad direction $dir")
}
}
fun follow(head: Coord2D, tail: Coord2D): Coord2D {
var newTail = tail
while (head != newTail && !newTail.adjacentTo(head)) {
when {
head.x < newTail.x -> newTail -= oneX
head.x > newTail.x -> newTail += oneX
}
when {
head.y < newTail.y -> newTail -= oneY
head.y > newTail.y -> newTail += oneY
}
}
return newTail
}
fun part1(input: List<Motion>): Int {
val visited = mutableSetOf<Coord2D>()
var head = Coord2D(0, 0)
var tail = Coord2D(0, 0)
visited.add(tail)
input.forEach { m ->
repeat(m.count) {
head = moveInDir(head, m.dir)
tail = follow(head, tail)
visited.add(tail)
}
}
return visited.size
}
fun part2(input: List<Motion>): Int {
val visited = mutableSetOf<Coord2D>()
val rope = MutableList(10) { Coord2D(0, 0) }
visited.add(rope.last())
input.forEach { m ->
repeat(m.count) {
rope[0] = moveInDir(rope[0], m.dir)
for (i in 1..rope.lastIndex) {
rope[i] = follow(rope[i - 1], rope[i])
}
visited.add(rope.last())
}
}
return visited.size
}
val testInput1 = mapToMotions(readInput("Day09test1"))
check(part1(testInput1) == 13)
check(part2(testInput1) == 1)
val testInput2 = mapToMotions(readInput("Day09test2"))
check(part2(testInput2) == 36)
val input = mapToMotions(readInput("Day09"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 950ffbce2149df9a7df3aac9289c9a5b38e29135 | 2,370 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day21.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | private sealed interface MonkeyJob {
val name: String
}
private data class OperationMonkeyJob(
override val name: String,
val left: String,
val operation: Char,
val right: String
) : MonkeyJob {
override fun toString() = "$name: $left $operation $right"
}
private data class ValueMonkeyJob(
override val name: String,
val value: Long
) : MonkeyJob {
override fun toString() = "$name: $value"
}
fun main() {
fun String.toMonkeyJob(): MonkeyJob {
val split = split(' ')
val name = split[0].removeSuffix(":")
return split[1].toLongOrNull()?.let { ValueMonkeyJob(name, it) } ?: OperationMonkeyJob(
name = name,
left = split[1],
operation = split[2].single(),
right = split[3]
)
}
fun List<String>.toMonkeyJobs() = map { it.toMonkeyJob() }.associateBy { it.name }.toMutableMap()
fun MutableMap<String, MonkeyJob>.reduce() {
var didReduce = true
while (didReduce) {
didReduce = false
values.filterIsInstance<OperationMonkeyJob>().forEach {
val left = get(it.left)
val right = get(it.right)
if (left is ValueMonkeyJob && right is ValueMonkeyJob) {
val value = when (it.operation) {
'+' -> left.value + right.value
'-' -> left.value - right.value
'*' -> left.value * right.value
'/' -> left.value / right.value
else -> error("Unkown operation: ${it.operation}")
}
replace(it.name, ValueMonkeyJob(it.name, value))
didReduce = true
}
}
}
}
fun part1(input: List<String>): Long {
val jobs = input.toMonkeyJobs()
jobs.reduce()
val root = jobs["root"] as ValueMonkeyJob
return root.value
}
fun part2(input: List<String>) {
val jobs = input.toMonkeyJobs()
jobs.remove("humn") as ValueMonkeyJob
jobs.reduce()
val root = jobs["root"] as OperationMonkeyJob
val left = jobs[root.left]
val right = jobs[root.right]
val open = left as? OperationMonkeyJob ?: right as OperationMonkeyJob
val solved = left as? ValueMonkeyJob ?: right as ValueMonkeyJob
val equation = buildString {
append(solved.value)
append("=")
fun traverse(job: OperationMonkeyJob) {
append('(')
when (val l = jobs[job.left]) {
is ValueMonkeyJob -> append(l.value)
is OperationMonkeyJob -> traverse(l)
else -> append("x")
}
append(job.operation)
when (val r = jobs[job.right]) {
is ValueMonkeyJob -> append(r.value)
is OperationMonkeyJob -> traverse(r)
else -> append("x")
}
append(')')
}
traverse(open)
}
println(equation)
}
val testInput = readInput("Day21_test")
check(part1(testInput) == 152L)
part2(testInput)
val input = readInput("Day21")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 3,357 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | rafael-ribeiro1 | 572,657,838 | false | {"Kotlin": 15675} | fun main() {
fun part1(input: List<String>): Int {
return input.toPairsWithRanges()
.count { pair ->
pair.first.intersect(pair.second).let {
it.size == pair.first.size || it.size == pair.second.size
}
}
}
fun part2(input: List<String>): Int {
return input.toPairsWithRanges()
.count { it.first.intersect(it.second).isNotEmpty() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun List<String>.toPairsWithRanges(): List<Pair<List<Int>, List<Int>>> {
return this.map { input ->
input.split(",").map { elf ->
elf.split("-").map { it.toInt() }.let {
(it[0]..it[1]).toList()
}
}.let { Pair(it[0], it[1]) }
}
}
| 0 | Kotlin | 0 | 0 | 5cae94a637567e8a1e911316e2adcc1b2a1ee4af | 1,021 | aoc-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | BenHopeITC | 573,352,155 | false | null | fun main() {
val day = "Day04"
fun part1(input: List<String>): Int {
return input.fold(0) { accFullyContains, elfPair ->
val fullyContains = elfPair
.split(",")
.map { elfSectionsStr ->
val nums = elfSectionsStr.split("-")
nums[0].toInt()..nums[1].toInt()
}
.chunked(2)
.all { elfSections ->
val common = elfSections[0].intersect(elfSections[1])
elfSections[0].count() == common.count() || elfSections[1].count() == common.count()
}
val increment = if (fullyContains) 1 else 0
accFullyContains + increment
}
}
fun part2(input: List<String>): Int {
return input.fold(0) { accFullyContains, elfPair ->
val fullyContains = elfPair
.split(",")
.map { elfSectionsStr ->
val nums = elfSectionsStr.split("-")
nums[0].toInt()..nums[1].toInt()
}
.chunked(2)
.all { elfSections ->
elfSections[0].intersect(elfSections[1]).isNotEmpty()
}
val increment = if (fullyContains) 1 else 0
accFullyContains + increment
}
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("${day}_test")
// println(part1(testInput))
// check(part1(testInput) == 2)
// test if implementation meets criteria from the description, like:
// val testInput2 = readInput("${day}_test")
// println(part2(testInput2))
// check(part2(testInput2) == 4)
val input = readInput(day)
println(part1(input))
println(part2(input))
check(part1(input) == 459)
check(part2(input) == 779)
}
| 0 | Kotlin | 0 | 0 | 851b9522d3a64840494b21ff31d83bf8470c9a03 | 1,891 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day09.kt | hijst | 572,885,261 | false | {"Kotlin": 26466} | import Direction.EAST
import Direction.NORTH
import Direction.SOUTH
import Direction.WEST
import kotlin.math.abs
fun main() {
data class Move(val direction: Direction, val amount: Int)
data class Position(val x: Int, val y: Int)
fun String.toDirection() = when (this) {
"U" -> NORTH
"D" -> SOUTH
"L" -> WEST
"R" -> EAST
else -> throw Exception("Not a valid direction in UDLR")
}
fun Position.executeMove(direction: Direction): Position = when (direction) {
NORTH -> Position(x, y + 1)
SOUTH -> Position(x, y - 1)
WEST -> Position(x - 1, y)
EAST -> Position(x + 1, y)
}
fun Position.directNeighbours(): List<Position> = listOf(
Position(x - 1, y),
Position(x + 1, y),
Position(x, y - 1),
Position(x, y + 1)
)
fun Position.diagonalNeighbours(): List<Position> = listOf(
Position(x - 1, y - 1),
Position(x + 1, y - 1),
Position(x - 1, y + 1),
Position(x + 1, y + 1)
)
fun Position.allNeighbours(): List<Position> = diagonalNeighbours() + directNeighbours()
fun Position.follow(other: Position): Position {
// if no move is needed
if (abs(x - other.x) < 2 && abs(y - other.y) < 2) return Position(x, y)
// if the move can be horizontal or vertical
if (directNeighbours().any {
other.directNeighbours().contains(it)
}) return directNeighbours().first { other.directNeighbours().contains(it) }
// else move diagonally
return diagonalNeighbours().first { other.allNeighbours().contains(it) }
}
fun List<List<String>>.toMoves(): List<Move> = map { (direction, amount) ->
Move(direction.toDirection(), amount.toInt())
}
fun part1(input: List<Move>): Int {
val visited = mutableSetOf(Position(0, 0))
var posHead = Position(0, 0)
var posTail = Position(0, 0)
for (move in input) {
for (step in 1..move.amount) {
posHead = posHead.executeMove(move.direction)
posTail = posTail.follow(posHead)
visited.add(posTail)
}
}
return visited.size
}
fun part2(input: List<Move>): Int {
val visited = mutableSetOf(Position(0, 0))
var posHead = Position(0, 0)
val posMiddle = MutableList(8) { Position(0, 0) }
var posTail = Position(0, 0)
for (move in input) {
for (step in 1..move.amount) {
posHead = posHead.executeMove(move.direction)
posMiddle[0] = posMiddle[0].follow(posHead)
for (knot in 1 until posMiddle.size) {
posMiddle[knot] = posMiddle[knot].follow(posMiddle[knot - 1])
}
posTail = posTail.follow(posMiddle.last())
visited.add(posTail)
}
}
return visited.size
}
val testInput = readInputWords("Day09_test").toMoves()
check(part1(testInput) == 13 )
check(part2(testInput) == 1)
val input = readInputWords("Day09_input").toMoves()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2258fd315b8933642964c3ca4848c0658174a0a5 | 3,214 | AoC-2022 | Apache License 2.0 |
src/aoc2022/Day05.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
private typealias StacksMap = Map<Int, ArrayDeque<Char>>
private data class RearrangementProcedure(val movesCount: Int, val sourceStackNo: Int, val desStackNo: Int)
fun main() {
fun List<String>.splitStacksFromProcedures(): Pair<List<String>, List<String>> {
val stacksCrates = this.takeWhile { it.isNotBlank() }
val procedures = this.dropWhile { !it.contains("move") }
return stacksCrates to procedures
}
fun List<String>.readProcedures(): List<RearrangementProcedure> = map { instruction ->
val count = instruction.substringAfter("move ").takeWhile { it.isDigit() }.toInt()
val from = instruction.substringAfter("from ").takeWhile { it.isDigit() }.toInt()
val to = instruction.substringAfter("to ").takeWhile { it.isDigit() }.toInt()
return@map RearrangementProcedure(count, from, to)
}
fun List<String>.loadStacksCrates(): StacksMap =
fold(mutableMapOf()) { stacksMap, line ->
line.chunked(4).forEachIndexed { index, block ->
val crate = block[1].takeIf { it.isLetter() } ?: return@forEachIndexed
val cratesStack = stacksMap[index + 1]
if (cratesStack == null)
stacksMap[index + 1] = ArrayDeque(listOf(crate))
else
cratesStack.addFirst(crate)
}
return@fold stacksMap
}
fun List<String>.loadStacksAndProcedures(): Pair<StacksMap, List<RearrangementProcedure>> {
val (stacks, procedures) = this.splitStacksFromProcedures()
return stacks.loadStacksCrates() to procedures.readProcedures()
}
fun StacksMap.topCratesAsMsg(): String =
(1..this.size).fold("") { msgAcc, i ->
msgAcc + this.getValue(i).last()
}
fun part1(input: List<String>): String {
val (stacksMap, procedures) = input.loadStacksAndProcedures()
for (p in procedures) {
val source = stacksMap.getValue(p.sourceStackNo)
val des = stacksMap.getValue(p.desStackNo)
repeat(p.movesCount) { _ ->
des.addLast(source.removeLast())
}
}
return stacksMap.topCratesAsMsg()
}
fun part2(input: List<String>): String {
val (stacksMap, procedures) = input.loadStacksAndProcedures()
for (p in procedures) {
val source = stacksMap.getValue(p.sourceStackNo)
val des = stacksMap.getValue(p.desStackNo)
val desInputIndex = des.size
repeat(p.movesCount) { _ ->
des.add(desInputIndex, source.removeLast())
}
}
return stacksMap.topCratesAsMsg()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput).also(::println) == "CMZ")
check(part2(testInput).also(::println) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 3,047 | Kotlin-AOC-2023 | Apache License 2.0 |
src/main/kotlin/days/Day14.kt | hughjdavey | 725,972,063 | false | {"Kotlin": 76988} | package days
class Day14 : Day(14) {
override fun partOne(): Any {
return tilt(inputList, Direction.NORTH).reversed()
.mapIndexed { index, s -> (index + 1) * s.count { it == 'O' } }
.sum()
}
override fun partTwo(): Any {
val (indexOfRepeated, indexOfRepeat) = generateSequence(0 to listOf(inputList)) {
it.first + 1 to it.second.plusElement(spinCycle(it.second.last()))
}.mapIndexedNotNull { index, it ->
val spin = spinCycle(it.second.last())
if (it.second.contains(spin)) {
it.second.indexOf(spin) to index + 1
} else null
}.first()
val diff = indexOfRepeat - indexOfRepeated
val stableCycle = generateSequence(1000000000 % diff) { it + diff }.map { (1..it)
.fold(inputList) { a, _ -> spinCycle(a) } }
.windowed(2).first { it[0] == it[1] }.first()
return stableCycle.reversed()
.mapIndexed { index, s -> (index + 1) * s.count { it == 'O' } }
.sum()
}
fun tilt(platform: List<String>, direction: Direction): List<String> {
val lines = if (direction == Direction.WEST || direction == Direction.EAST) platform else {
(0..platform.first().lastIndex).map { x -> platform.map { it[x] }.joinToString("") }
}
val match = when (direction) {
Direction.NORTH, Direction.WEST -> ".O"
Direction.SOUTH, Direction.EAST -> "O."
}
val tilted = lines.map {
var line = it
var nextIndex = line.indexOf(match)
while (nextIndex != -1) {
line = line.substring(0, nextIndex) + match.reversed() + line.substring(nextIndex + 2)
nextIndex = line.indexOf(match)
}
line
}
return if (direction == Direction.WEST || direction == Direction.EAST) tilted else {
(0..platform.lastIndex).map { y -> tilted.map { it[y] }.joinToString("") }
}
}
fun spinCycle(platform: List<String>): List<String> {
return listOf(Direction.NORTH, Direction.WEST, Direction.SOUTH, Direction.EAST).fold(platform) { p, direction -> tilt(p, direction) }
}
enum class Direction {
NORTH, SOUTH, EAST, WEST
}
}
| 0 | Kotlin | 0 | 0 | 330f13d57ef8108f5c605f54b23d04621ed2b3de | 2,313 | aoc-2023 | Creative Commons Zero v1.0 Universal |
src/challenges/Day04.kt | paralleldynamic | 572,256,326 | false | {"Kotlin": 15982} | package challenges
import utils.readInput
private const val LABEL = "Day04"
fun checkContains(sections: List<String>): Boolean {
val (first_lower, first_upper) = sections.first().split("-").map { bound -> bound.toInt() }
val (second_lower, second_upper) = sections.last().split("-").map { bound -> bound.toInt() }
return (first_lower <= second_lower && first_upper >= second_upper)
|| (first_lower >= second_lower && first_upper <= second_upper)
}
fun checkOverlap(sections: List<String>): Boolean {
val (first_lower, first_upper) = sections.first().split("-").map { bound -> bound.toInt() }
val (second_lower, second_upper) = sections.last().split("-").map { bound -> bound.toInt() }
return second_lower <= first_upper && first_lower <= second_upper
}
fun main() {
fun part1(sections: List<String>): Int = sections
.map { pair -> pair.split(",") }
.map { sections -> checkContains(sections) }
.count { it }
fun part2(sections: List<String>): Int = sections
.map { pair -> pair.split(",") }
.map { sections -> checkContains(sections) || checkOverlap(sections) }
.count { it }
// Reading input
val testSections = readInput("${LABEL}_test")
val sections = readInput(LABEL)
// Part 1
check(part1(testSections) == 2)
println(part1(sections))
// Part 2
check(part2(testSections) == 4)
println(part2(sections))
}
| 0 | Kotlin | 0 | 0 | ad32a9609b5ce51ac28225507f77618482710424 | 1,444 | advent-of-code-kotlin-2022 | Apache License 2.0 |
y2019/src/main/kotlin/adventofcode/y2019/Day17.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2019
import adventofcode.io.AdventSolution
import adventofcode.language.intcode.IntCodeProgram
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
fun main() = Day17.solve()
object Day17 : AdventSolution(2019, 17, "Set and Forget") {
override fun solvePartOne(input: String): Int {
val map = readMap(IntCodeProgram.fromData(input))
return (1 until map.lastIndex).sumOf { y ->
y * (1 until map[y].lastIndex)
.filter { x -> map.isCrossing(y, x) }
.sum()
}
}
private fun List<String>.isCrossing(y: Int, x: Int): Boolean =
this[y][x] == '#'
&& this[y - 1][x] == '#'
&& this[y][x - 1] == '#'
&& this[y + 1][x] == '#'
&& this[y][x + 1] == '#'
override fun solvePartTwo(input: String): Long {
val data = "2" + input.drop(1)
val program = IntCodeProgram.fromData(data)
val map: List<String> = readMap(program)
val route = findRoute(map)
.joinToString(",")
val v = CompressedRoute(route).fullCompress("ABC").first { it.fitsInMemory() && it.fullyCompressed() }
val instructions = listOf(v.main) + v.functions + "n"
instructions.joinToString("\n", postfix = "\n").forEach { program.input(it.code.toLong()) }
program.execute()
return generateSequence { program.output() }.last()
}
data class CompressedRoute(val main: String, val functions: List<String>, val compressionTokens: String) {
constructor(route: String) : this(route, emptyList(), "")
fun fullCompress(tokens: String) =
tokens.fold(sequenceOf(this)) { possibleCompressions, token ->
possibleCompressions.flatMap { comp -> comp.greedyCompressionCandidates(token) }
}
private fun greedyCompressionCandidates(compressTo: Char): Sequence<CompressedRoute> =
generateCandidatePrefixes().map { newFunction ->
CompressedRoute(main.replace(newFunction, compressTo.toString()),
functions + newFunction,
compressionTokens + compressTo)
}
private fun generateCandidatePrefixes(): Sequence<String> = main
.splitToSequence(",")
.dropWhile { it in compressionTokens }
.takeWhile { it !in compressionTokens }
.scan(emptyList<String>()) { a, n -> a + n }
.map { it.joinToString(",") }
fun fullyCompressed() = main.all { it in "$compressionTokens," }
fun fitsInMemory() = (functions + main).all { it.length <= 20 }
}
private fun readMap(program: IntCodeProgram): List<String> = program.run {
execute()
generateSequence { output() }.map { it.toInt().toChar() }.joinToString("")
}
.lines().filter { it.isNotBlank() }
private fun findRoute(map: List<String>): List<String> {
operator fun List<String>.get(p: Vec2) = this.getOrNull(p.y)?.getOrNull(p.x)
fun path(v: Vec2) = map[v] == '#'
val y = map.indexOfFirst { '^' in it }
val x = map[y].indexOf('^')
val position = Vec2(x, y)
val direction = Direction.UP
return generateSequence<Pair<Direction?, Vec2>>(direction to position) { (od, op) ->
when {
od == null -> null
path(op + od.vector) -> od to op + od.vector
path(op + od.turnLeft.vector) -> od.turnLeft to op
path(op + od.turnRight.vector) -> od.turnRight to op
else -> null to op
}
}
.zipWithNext { a, b -> a.takeIf { a.second == b.second } }
.filterNotNull()
.zipWithNext { a, b ->
sequenceOf(
if (a.first?.turnLeft == b.first) "L" else "R",
a.second.distance(b.second).toString())
}
.flatten()
.toList()
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 4,229 | advent-of-code | MIT License |
src/day14/Day14_functional.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day14
import Point2D
import readLines
/**
* Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin)
* I'm experimenting with his solutions to better learn functional programming in Kotlin.
* Files without the _functional suffix are my original solutions.
*/
private fun Point2D.down(): Point2D = Point2D(x, y + 1)
private fun Point2D.downLeft(): Point2D = Point2D(x - 1, y + 1)
private fun Point2D.downRight(): Point2D = Point2D(x + 1, y + 1)
private fun parseInput(input: List<String>): MutableSet<Point2D> {
return input.flatMap { row ->
row.split(" -> ") // for each row, split by -> to get a list of coordinates
.map { Point2D.of(it) } // for each coordinate, translate to Point2D
.zipWithNext() // zipWithNext returns a list of pairs of each two adjacent elements, similar to windowed(2,1)
.flatMap { (from, to) -> from.lineTo(to) } // for each zipped pair get the line points between the two
}.toMutableSet()
}
private fun dropSand(cave: MutableSet<Point2D>, voidStartsAt: Int): Int {
val sandSource = Point2D(500, 0)
var start = sandSource
var landed = 0
while (true) {
// if none of those are free, the grain of sand has come to rest, so we’ll return null.
val next = listOf(start.down(), start.downLeft(), start.downRight()).firstOrNull { it !in cave }
start = when {
// case (1) - if next == null and we're back at the source, return landed count
next == null && start == sandSource -> return landed
// case (2) - if next == null and we're NOT back at the source, we know the grain of sand has come to rest
// we add the previous state (start) to the cave, increment the landed counter, and set the start to the
// sandSource so the next time through the loop start dropping a new grain of sand
next == null -> {
cave.add(start)
landed += 1
sandSource
}
// case (3) if we have fallen into the void, return landed count
next.y == voidStartsAt -> return landed
// case (4) set start as next valid point
else -> next
}
}
}
private fun part1(input: List<String>): Int {
val cave: MutableSet<Point2D> = parseInput(input)
val maxY: Int = cave.maxOf { it.y }
return dropSand(cave, maxY + 1)
}
private fun part2(input: List<String>): Int {
val cave: MutableSet<Point2D> = parseInput(input)
val maxY: Int = cave.maxOf { it.y }
val minX: Int = cave.minOf { it.x }
val maxX: Int = cave.maxOf { it.x }
cave.addAll(Point2D(minX - maxY - maxY, maxY + 2).lineTo(Point2D(maxX + maxY + maxY, maxY + 2)))
return dropSand(cave, maxY + 3) + 1
}
fun main() {
println(part1(readLines("day14/test")))
println(part2(readLines("day14/test")))
println(part1(readLines("day14/input")))
println(part2(readLines("day14/input")))
} | 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 2,994 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day8/Day8.kt | gornovah | 573,055,751 | false | {"Kotlin": 20487} | package day8
import load
fun main() {
val loadedData = load("/day-8.txt")
val grid = loadedData.map { line -> line.map { it.digitToInt() } }
println("Solution to Day 7, Part 1 is '${solveDay8PartOne(grid)}'")
println("Solution to Day 7, Part 2 is '${solveDay8PartTwo(grid)}'")
}
fun solveDay8PartOne(grid: List<List<Int>>): Int {
val border = 2 * grid[0].size + 2 * grid.size - 4
val pairs = (1..grid.size - 2).flatMap { i -> (1..grid[0].size - 2).map { i to it } }
val middle = pairs.count { (i, j) -> isVisible(i, j, grid) }
return border + middle
}
fun solveDay8PartTwo(input: List<List<Int>>): Int {
val pairs = (1..input.size - 2).flatMap { i -> (1..input[0].size - 2).map { i to it } }
return pairs.fold(0) { acc, (i, j) -> acc.coerceAtLeast(getCounter(i, j, input)) }
}
fun getCounter(i: Int, j: Int, inp: List<List<Int>>): Int {
val checking = inp[i][j]
val idxBorderUp = inp.map { row -> row[j] }.take(i).reversed().indexOfFirst { it >= checking }
val ctrUp = if (idxBorderUp == -1) (i) else if (idxBorderUp == 0) 1 else idxBorderUp + 1
val numberOfElementsOnLeft = inp.size - 1 - i
val idxBorderDown = inp.map { row -> row[j] }.takeLast(numberOfElementsOnLeft).indexOfFirst { it >= checking }
val ctrDown = if (idxBorderDown == -1) numberOfElementsOnLeft else if (idxBorderDown == 0) 1 else idxBorderDown + 1
val idxBorderLeft = inp[i].take(j).reversed().indexOfFirst { it >= checking }
val ctrLeft = if (idxBorderLeft == -1) (j) else if (idxBorderDown == 0) 1 else idxBorderLeft + 1
val numberOfElementsBelow = inp[0].size - j - 1
val idxBorderRight = inp[i].takeLast(numberOfElementsBelow).indexOfFirst { it >= checking }
val ctrRight = if (idxBorderRight == -1) numberOfElementsBelow else if (idxBorderRight == 0) 1 else idxBorderRight + 1
return ctrUp * ctrDown * ctrLeft * ctrRight
}
fun isVisible(i: Int, j: Int, inp: List<List<Int>>): Boolean {
val checking = inp[i][j]
return inp.map { row -> row[j] }.take(i).none { it >= checking } || inp.map { row -> row[j] }.takeLast(inp.size - 1 - i)
.none { it >= checking } || inp[i].take(j).none { it >= checking } || inp[i].takeLast(inp[0].size - j - 1).none { it >= checking }
} | 0 | Kotlin | 0 | 0 | 181d1094111bd137f70a580ca32a924b582adf70 | 2,255 | advent_of_code_2022 | MIT License |
src/main/kotlin/com/jackchapman/codingchallenges/hackerrank/EmasSupercomputer.kt | crepppy | 381,882,392 | false | null | package com.jackchapman.codingchallenges.hackerrank
typealias Plus = List<Pair<Int, Int>>
/**
* Problem: [Ema's Supercomputer](https://www.hackerrank.com/challenges/two-pluses/)
*
* Given a matrix of good (`G`) cells and bad (`B`) cells, find 2 pluses made of
* good cells whose area has the greatest product
* @param grid A 2D character matrix made of good and bad cells
* @return The product of the 2 largest pluses
*/
fun twoPluses(grid: Array<String>): Int {
val m = grid.map { it.toCharArray() }
return m.maxOf { i, j ->
var firstRadius = 0
var curMax = 0
var firstPlus = cross(i, j, firstRadius)
while (firstPlus.isValid(m)) {
curMax = maxOf(curMax, firstPlus.size * m.maxOf(i, j) { y, x ->
var secondRadius = 0
var secondPlus: Plus
do secondPlus = cross(y, x, secondRadius++)
while (secondPlus.isValid(m) && secondPlus.none { it in firstPlus })
secondPlus.size - 4
})
firstPlus = cross(i, j, ++firstRadius)
}
curMax
}
}
/**
* Returns the largest value among all values produced by selector function applied to each element in the matrix
* @see Iterable.maxOf
*/
private inline fun List<CharArray>.maxOf(startY: Int = 0, startX: Int = 0, receiver: (Int, Int) -> Int) =
(startY until size).maxOf { i -> (startX until first().size).maxOf { j -> receiver(i, j) } }
/**
* Ensures that each index in a list of indices is inside a given matrix and is a 'good' cell
*/
private fun Plus.isValid(matrix: List<CharArray>): Boolean =
none { (y, x) -> y !in matrix.indices || x !in matrix[0].indices } && map { (y, x) -> matrix[y][x] }.none { it != 'G' }
/**
* Given an index of the centre of a plus, determine all the indices of each of the cells in the plus
*/
private fun cross(row: Int, col: Int, n: Int): Plus =
((col - n until col) + (col + 1..col + n)).map { row to it } + (row - n..row + n).map { it to col } | 0 | Kotlin | 0 | 0 | 9bcfed84a9850c3977ccff229948cc31e319da1b | 2,019 | coding-challenges | The Unlicense |
src/main/kotlin/aoc/year2023/Day04.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2023
import aoc.Puzzle
import kotlin.math.pow
/**
* [Day 4 - Advent of Code 2023](https://adventofcode.com/2023/day/4)
*/
object Day04 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int = input.lineSequence().map { it.toCard() }.sumOf { it.points }
override fun solvePartTwo(input: String): Int {
val cards = input.lineSequence().map { it.toCard() }.toList()
val counts = cards.associateTo(hashMapOf()) { it.id to 1 }
cards.forEach { card ->
val nCopies = counts.getValue(card.id)
generateSequence(card.id, Int::inc)
.drop(1)
.take(card.matching)
.forEach { counts.merge(it, nCopies, Int::plus) }
}
return counts.values.sum()
}
private fun String.toCard(): Card {
val (idStr, winningStr, playingStr) = split(':', '|').map { it.trim() }
val id = idStr.removePrefix("Card ").trim().toInt()
val winning = winningStr.splitToSequence(' ').filter { it.isNotEmpty() }.map { it.toInt() }.toSet()
val playing = playingStr.splitToSequence(' ').filter { it.isNotEmpty() }.map { it.toInt() }.toSet()
return Card(id, winning, playing)
}
private data class Card(val id: Int, val winning: Set<Int>, val playing: Set<Int>) {
val matching = playing.count { it in winning }
val points = matching.let { if (it == 0) 0 else 2.0.pow(it - 1.0).toInt() }
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 1,473 | advent-of-code | Apache License 2.0 |
src/Day03.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | fun main() {
fun Char.cost(): Int {
if (isLowerCase()) {
return code - 'a'.code + 1
}
return code - 'A'.code + 27
}
fun intersect(a: Iterable<Char>, b: Iterable<Char>): Collection<Char> {
val res = mutableSetOf<Char>()
for (c in a) {
if (c in b) {
res.add(c)
}
}
return res
}
fun part1(input: List<String>): Int {
val cost = input.map {
val half = it.length / 2
val x = it.substring(0, half)
val y = it.substring(half)
val z = intersect(x.toMutableList(), y.toMutableList())
z.sumOf { it.cost() }
}.sum()
return cost
}
fun part2(input: List<String>): Int {
var s = 0
for (i in input.indices step 3) {
val group = input.subList(i, i + 3)
val inter = intersect(intersect(group[0].toList(), group[1].toList()), group[2].toList())
s += inter.sumOf { it.cost() }
}
return s
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part2(testInput))
// check(part1(testInput) == 24000)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 1,343 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem18/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem18
/**
* LeetCode page: [18. 4Sum](https://leetcode.com/problems/4sum/);
*/
class Solution {
/* Complexity:
* Time O(N^3), Aux_Space O(N) and Space O(N^3) where N is the size of nums;
*/
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val sorted = nums.clone().apply { sort() }
val solver = KSumSolver.newInstance(sorted, 4, target)
return solver.solve()
}
private class KSumSolver private constructor(
private val sorted: IntArray,
private val k: Int,
private val target: Long
) {
fun solve(): List<List<Int>> {
return solveHelper(0, k, target)
}
private fun solveHelper(startIndex: Int, k: Int, target: Long): List<List<Int>> {
if (k == 2) return solveTwoSum(startIndex, target)
val isOutOfRange = isTargetOutOfRange(sorted[startIndex], sorted.last(), target, k)
if (isOutOfRange) return emptyList()
val result = mutableListOf<List<Int>>()
for (index in startIndex..sorted.size - k) {
val shouldSkip = index != startIndex && sorted[index] == sorted[index - 1]
if (shouldSkip) continue
val num = sorted[index]
val complementary = target - num
val complementaryResult = solveHelper(index + 1, k - 1, complementary)
for (list in complementaryResult) {
result.add(list + num)
}
}
return result
}
private fun solveTwoSum(startIndex: Int, target: Long): List<List<Int>> {
val noEnoughElements = sorted.size - startIndex < 2
if (noEnoughElements) return emptyList()
val isOutOfRange = isTargetOutOfRange(sorted[startIndex], sorted.last(), target, 2)
if (isOutOfRange) return emptyList()
val result = mutableListOf<List<Int>>()
var leftIndex = startIndex
var rightIndex = findRightIndex(leftIndex, target)
while (leftIndex < rightIndex) {
val sum = sorted[leftIndex] + sorted[rightIndex]
when {
sum < target -> leftIndex = toNextLeftIndex(leftIndex, rightIndex)
sum > target -> rightIndex = toNextRightIndex(leftIndex, rightIndex)
else -> {
result.add(listOf(sorted[leftIndex], sorted[rightIndex]))
leftIndex = toNextLeftIndex(leftIndex, rightIndex)
rightIndex = toNextRightIndex(leftIndex, rightIndex)
}
}
}
return result
}
private fun isTargetOutOfRange(minNum: Int, maxNum: Int, target: Long, k: Int): Boolean {
val average = target / k
return minNum > average || maxNum < average
}
private fun findRightIndex(leftIndex: Int, target: Long): Int {
val complementary = (target - sorted[leftIndex]).toInt()
return sorted
.binarySearch(complementary, leftIndex + 1)
.let { insertionIndex -> if (insertionIndex < 0) -(insertionIndex + 1) else insertionIndex }
.coerceAtMost(sorted.lastIndex)
}
private fun toNextLeftIndex(leftIndex: Int, rightIndex: Int): Int {
var nextLeftIndex = leftIndex + 1
while (sorted[nextLeftIndex] == sorted[nextLeftIndex - 1] && nextLeftIndex < rightIndex) {
nextLeftIndex++
}
return nextLeftIndex
}
private fun toNextRightIndex(leftIndex: Int, rightIndex: Int): Int {
var nextRightIndex = rightIndex - 1
while (sorted[nextRightIndex] == sorted[nextRightIndex + 1] && nextRightIndex > leftIndex) {
nextRightIndex--
}
return nextRightIndex
}
companion object {
fun newInstance(sorted: IntArray, k: Int, target: Int): KSumSolver {
require(k > 1)
return KSumSolver(sorted, k, target.toLong())
}
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 4,230 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/Day3.kt | lanrete | 244,431,253 | false | null | import kotlin.math.abs
data class Point(val x: Int, val y: Int) {
override fun toString(): String {
return "($x, $y)"
}
}
data class Line(val start: Point, val end: Point) {
override fun toString(): String {
return "[$start -> $end]"
}
}
typealias Wire = List<Line>
fun Line.points(): List<Point> {
return if (start.x == end.x) {
val range = if (start.y < end.y) (start.y..end.y) else start.y.downTo(end.y)
range.map {
Point(start.x, it)
}
} else {
val range = if (start.x < end.x) (start.x..end.x) else start.x.downTo(end.x)
range.map {
Point(it, start.y)
}
}
}
fun Line.overPoint(p: Point): Boolean {
if (p == start) {
return true
}
if (p == end) {
return true
}
if ((p.x != start.x) && (p.x != end.x) &&
(p.y != start.y) && (p.y != end.y)
) {
return false
}
if ((start.x == end.x) && (p.x == start.x)) {
return ((p.y - start.y) * (p.y - end.y) < 0)
}
if ((start.y == end.y) && (p.y == start.y)) {
return ((p.x - start.x) * (p.x - end.x) < 0)
}
return false
}
fun Line.intersect(another: Line): Point? {
return this
.points()
.associateWith { another.overPoint(it) }
.filterValues { it }
.keys
.firstOrNull()
}
fun Wire.intersect(l: Line): List<Point> {
return this.mapNotNull { it.intersect(l) }
}
fun Wire.intersect(another: Wire): List<Point> {
return another
.map { this.intersect(it) }
.flatten()
.filterNot { it == Point(0, 0) }
}
fun Wire.steps(): Map<Point, Long> {
var step: Long = 0
return this
.map { line ->
val tempMap = line
.points().withIndex()
.associate { Pair(it.value, (it.index + step)) }
step += line.points().size
step -= 1
tempMap.toMutableMap()
}
.reduce { cumMap, newMap ->
newMap.forEach { (k, v) ->
run {
if (!cumMap.containsKey(k)) {
cumMap[k] = v
}
}
}
cumMap
}
}
object Day3 : Solver() {
override val day: Int = 3
override val inputs: List<String> = getInput()
private fun generateWire(raw: String): Wire {
var point = Point(0, 0)
return raw.split(',').map {
val dir = it[0]
val step = it.drop(1).toInt()
var xm = 0
var ym = 0
when (dir) {
'R' -> xm = 1
'L' -> xm = -1
'U' -> ym = 1
'D' -> ym = -1
}
val start = point
val end = Point(point.x + step * xm, point.y + step * ym)
point = end
// println("Adding line from $start to $end")
Line(start, end)
}
}
private val wires: List<Wire> = inputs.map { generateWire(it) }
private val intersections = wires[0].intersect(wires[1])
override fun question1(): String {
return intersections
.map { abs(it.x) + abs(it.y) }
.reduce { a, b -> if (a < b) a else b }
.toString()
}
override fun question2(): String {
val steps = wires.map { it.steps() }
return intersections
.map { intersect ->
steps
.map { map -> map.getValue(intersect) }
.reduce { a, b -> a + b }
}
.reduce { a, b -> if (a < b) a else b }
.toString()
}
}
fun main() {
Day3.solve()
}
| 0 | Kotlin | 0 | 1 | 15125c807abe53230e8d0f0b2ca0e98ea72eb8fd | 3,705 | AoC2019-Kotlin | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year16/Day11.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year16
import com.grappenmaker.aoc.*
fun PuzzleSet.day11() = puzzle(day = 11) {
val elementsRegex = """(, (and )?)|( and )""".toRegex()
data class Component(val element: String, val chip: Boolean)
data class State(val floors: List<Set<Component>>, val elevator: Int = 0)
fun Set<Component>.isInvalid(): Boolean {
if (isEmpty()) return false
val (chips, generators) = partition { it.chip }.mapBoth { it.map(Component::element).toSet() }
return chips.any { it !in generators && generators.isNotEmpty() }
}
// TODO: binary representation
fun State.encode(): Pair<Int, List<Set<Int>>> {
var i = 0
val map = mutableMapOf<String, Int>()
return elevator to floors.map { floor ->
floor.map { (if (it.chip) 16 else 0) or map.getOrPut(it.element) { i++ } }.toSet()
}
}
val floors = inputLines.take(3).map { l ->
val (_, relevant) = l.removeSuffix(".").split("contains ")
relevant.replace("a ", "").split(elementsRegex).map { component ->
val (elementPart, typePart) = component.split(" ")
Component(elementPart.substringBefore('-'), typePart == "microchip")
}.toSet()
}.plusElement(emptySet())
fun solve(initialState: State): String {
val totalChips = initialState.floors.sumOf { it.size }
val queue = queueOf(initialState to 0)
val seen = hashSetOf(initialState.encode())
queue.drain { (curr, dist) ->
if (curr.floors.last().size == totalChips) return dist.s()
val currentFloor = curr.floors[curr.elevator]
val poss = (currentFloor.permPairsExclusive { a, b -> setOf(a, b) }
+ currentFloor.map { setOf(it) }).toSet()
listOf(curr.elevator - 1, curr.elevator + 1).filter { it in curr.floors.indices }.forEach { newElevator ->
val nextFloor = curr.floors[newElevator]
poss.forEach a@{ moved ->
val nextCurrent = currentFloor - moved
val nextNext = nextFloor + moved
if (nextCurrent.isInvalid() || nextNext.isInvalid()) return@a
val updated = curr.floors.toMutableList()
updated[curr.elevator] = nextCurrent
updated[newElevator] = nextNext
State(updated, newElevator).let { if (seen.add(it.encode())) queue.addFirst(it to dist + 1) }
}
}
}
error("Impossible")
}
partOne = solve(State(floors))
partTwo = solve(State(floors.toMutableList().also {
it[0] += setOf(
Component("elerium", chip = false),
Component("elerium", chip = true),
Component("dilithium", chip = false),
Component("dilithium", chip = true),
)
}))
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,898 | advent-of-code | The Unlicense |
src/Day05.kt | jalex19100 | 574,686,993 | false | {"Kotlin": 19795} | import java.util.*
import kotlin.collections.ArrayList
class StacksOfCrates() {
private val stacks = HashMap<Int, LinkedList<Char>>()
fun add(stackNumber: Int, crate: Char) {
if (stacks.containsKey(stackNumber)) stacks?.get(stackNumber)?.add(crate)
else {
val stack = LinkedList<Char>()
stack.add(crate)
stacks[stackNumber] = stack
}
}
fun move(numberOfCrates: Int?, fromStackKey: Int?, toStackKey: Int?, multiMove: Boolean) {
if (numberOfCrates != null && fromStackKey != null && toStackKey != null) {
val fromStack = stacks[fromStackKey]
val toStack = stacks[toStackKey]
val crates = Stack<Char>()
if (multiMove) {
repeat(numberOfCrates) {
crates.push(fromStack?.pop())
}
repeat(numberOfCrates) {
toStack?.push(crates?.pop())
}
} else {
repeat(numberOfCrates) {
toStack?.push(fromStack?.pop())
}
}
} else println("Invalid instruction: move $numberOfCrates from $fromStackKey to $toStackKey")
}
fun getTopCrates(): List<Char> {
val topCrates = ArrayList<Char>()
stacks.keys.sorted().forEach { key ->
val crate = stacks[key]?.peek()
if (crate != null) {
topCrates.add(crate)
}
}
return topCrates
}
override fun toString(): String {
var string = StringBuilder()
string.append("${this.stacks.size} stacks\n")
stacks.keys.forEach { index ->
string.append("Stack $index: ${stacks[index]}\n")
}
return string.toString()
}
}
fun main() {
fun part1(input: List<String>, multiMove: Boolean = false): String {
val stacks = StacksOfCrates()
val cratesPattern = ".*\\[[A-Z]\\].*".toRegex()
val instructionPattern = "move\\s(\\d+)\\sfrom\\s(\\d+)\\sto\\s(\\d+)".toRegex()
input.forEach { line ->
if (line.matches(cratesPattern)) {
val chunks = line.chunked(4)
chunks.forEachIndexed { index, chunk ->
if (chunk.isNotBlank() && chunk[0] == '[' && chunk[1].isLetter()) {
stacks.add(index + 1, chunk[1])
}
}
} else if (line.matches(instructionPattern)) {
val matchGroups = instructionPattern.find(line)?.groups
if (matchGroups != null && matchGroups.size == 4) {
stacks.move(matchGroups[1]?.value?.toInt(), matchGroups[2]?.value?.toInt(), matchGroups[3]?.value?.toInt(), multiMove)
}
}
}
return stacks.getTopCrates().toString()
}
fun part2(input: List<String>): String {
return part1(input, true)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "[C, M, Z]")
check(part2(testInput) == "[M, C, D]")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a50639447a2ef3f6fc9548f0d89cc643266c1b74 | 3,310 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | data class Interval(var start: Int, var end: Int)
fun parseInterval(s: String): Interval {
val (start, end) = s.split('-')
return Interval(start.toInt(), end.toInt())
}
fun isFullyOverlap(int1: Interval, int2: Interval): Boolean {
return int1.start <= int2.start && int1.end >= int2.end
}
fun isOverlap(int1: Interval, int2: Interval): Boolean {
return !(int2.end < int1.start || int2.start > int1.end)
}
fun main() {
fun part1(input: List<String>): Int {
var totalOverlaps = 0
for (line in input) {
val (int1, int2) = line.split(',')
val parsedInt1 = parseInterval(int1)
val parsedInt2 = parseInterval(int2)
if (isFullyOverlap(parsedInt1, parsedInt2) || isFullyOverlap(parsedInt2, parsedInt1)) {
totalOverlaps += 1
}
}
return totalOverlaps
}
fun part2(input: List<String>): Int {
var totalOverlaps = 0
for (line in input) {
val (int1, int2) = line.split(',')
val parsedInt1 = parseInterval(int1)
val parsedInt2 = parseInterval(int2)
if (isOverlap(parsedInt1, parsedInt2)) {
totalOverlaps += 1
}
}
return totalOverlaps
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 1,551 | aoc2022 | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day284/day284.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day284
// day284.kt
// By <NAME>, 2020.
typealias Depth = Int
typealias ParentChild = Pair<Int, Int>
typealias Cousins = Pair<Int, Int>
typealias DepthInfo = Map<Depth, List<ParentChild>>
data class BinaryTree(val value: Int, val left: BinaryTree?, val right: BinaryTree?) {
// Find all cousins: cousins are, by definition, on the same level of the tree but have different parents.
fun findAllCousins(): Set<Cousins> {
// Start by collecting all nodes in the tree in a map depth -> (parentvalue -> nodevalue).
// We skip the root node since it cannot have any cousins.
tailrec
fun aux(
nodes: List<Pair<Depth, BinaryTree>> = listOf(1 to this),
depthMap: DepthInfo = emptyMap()
): DepthInfo {
if (nodes.isEmpty())
return depthMap.filter{ it.value.isNotEmpty() }
// Process the first node.
val node = nodes.first()
val (depth, parent) = node
val children = listOfNotNull(parent.left, parent.right)
val newDepthMap = mergeDepthInfo(depthMap, mapOf(depth to children.map { parent.value to it.value }))
return aux(nodes - node + children.map { depth + 1 to it }, newDepthMap)
}
// This results in a map, indexed by depth, of pairs of the form (parent, child).
// We drop the depth since it is no longer necessary to get slices of children from the same generation
// with their parents. We then iterate over each generation and find the cousins.
// We iterate over each depth slice and match together
val depthInfo = aux().values
// Now we process across each layer of the tree,
return depthInfo.flatMap{ findCousins(it) }.toSet()
}
companion object {
/**
* Given two maps whose elements are lists, return the combined map where the elements are the concatenations
* of the lists.
*/
private fun mergeDepthInfo(m1: DepthInfo, m2: DepthInfo): DepthInfo =
(m1.keys + m2.keys).map {
val a1 = m1[it] ?: emptyList()
val a2 = m2[it] ?: emptyList()
it to (a1 + a2)
}.toMap()
/**
* Find all the cousins within a generation, where the generation is represented by a list of entries
* of the form Pair<Parent.value, Child.value>. We return the cousins as pairs in lexicographical order.
*/
private fun findCousins(generation: List<ParentChild>): List<Cousins> =
generation.flatMap { pc1 ->
generation.filter { pc2 -> pc1.first < pc2.first }
.map { pc2 -> if (pc1.second < pc2.second) Pair(pc1.second, pc2.second) else Pair(pc2.second, pc1.second)}}
}
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,824 | daily-coding-problem | MIT License |
src/year2016/day02/Day02.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2016.day02
import check
import readInput
fun main() {
val testInput = readInput("2016", "Day02_test")
check(part1(testInput), 1985)
check(part2(testInput), "5DB3")
val input = readInput("2016", "Day02")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
var pos = Pos(1, 1)
return input.joinToString("") { moves ->
for (dir in moves.chunked(1).map(Dir::valueOf)) {
pos = pos.move(dir).constrainIn(0..2)
}
numPad[pos]
}.toInt()
}
private fun part2(input: List<String>): String {
var pos = Pos(0, 2)
return input.joinToString("") { moves ->
for (dir in moves.chunked(1).map(Dir::valueOf)) {
val nextPos = pos.move(dir)
if (crazyNumPad[nextPos] != null) {
pos = nextPos
}
}
requireNotNull(crazyNumPad[pos])
}
}
private data class Pos(val x: Int, val y: Int) {
fun move(dir: Dir): Pos = when (dir) {
Dir.U -> Pos(x, y - 1)
Dir.D -> Pos(x, y + 1)
Dir.L -> Pos(x - 1, y)
Dir.R -> Pos(x + 1, y)
}
fun constrainIn(range: IntRange): Pos {
return Pos(x.coerceIn(range), y.coerceIn(range))
}
}
private enum class Dir {
U, D, L, R
}
private val numPad = listOf(
listOf("1", "2", "3"),
listOf("4", "5", "6"),
listOf("7", "8", "9"),
)
private val crazyNumPad = listOf(
listOf(null, null, "1", null, null),
listOf(null, "2", "3", "4", null),
listOf("5", "6", "7", "8", "9"),
listOf(null, "A", "B", "C", null),
listOf(null, null, "D", null, null),
)
private operator fun List<List<String>>.get(pos: Pos) = this[pos.y][pos.x]
@JvmName("nullableGet")
private operator fun List<List<String?>>.get(pos: Pos) = getOrNull(pos.y)?.getOrNull(pos.x)
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,842 | AdventOfCode | Apache License 2.0 |
src/Day04.kt | 3n3a-archive | 573,389,832 | false | {"Kotlin": 41221, "Shell": 534} | fun Day04() {
fun preprocess(input: List<String>): List<List<Set<Int>>> {
return input
.map {
it.split(",")
} // to pair of elves
.map {
it.map {
it2 -> it2.split("-")
}
} // each elf gets pair of numbers
.map {
it.map {
it2 -> IntRange(
it2[0].toInt(),
it2[1].toInt()
).toSet()
}
} // each elf gets range of numbers
}
fun part1(input: List<String>): Int {
val processed = preprocess(input)
var fullyContainedSets = 0
for ((elfOne, elfTwo) in processed) {
if (elfOne.containsAll(elfTwo) ||
elfTwo.containsAll(elfOne)) {
fullyContainedSets = fullyContainedSets.inc()
}
}
return fullyContainedSets
}
fun part2(input: List<String>): Int {
val processed = preprocess(input)
var intersectedSets = 0
for ((elfOne, elfTwo) in processed) {
if (elfOne.intersect(elfTwo).isNotEmpty() ||
elfTwo.intersect(elfOne).isNotEmpty()) {
intersectedSets = intersectedSets.inc()
}
}
return intersectedSets
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println("1: " + part1(input))
println("2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | fd25137d2d2df0aa629e56981f18de52b25a2d28 | 1,684 | aoc_kt | Apache License 2.0 |
src/Day05/Day05.kt | Trisiss | 573,815,785 | false | {"Kotlin": 16486} | fun main() {
fun numbersOfStacks(lines: List<String>): Int =
lines
.dropWhile { it.contains("[") }
.first()
.split(" ")
.filter { it.isNotBlank() }
.maxOf { it.toInt() }
fun populateStacks(lines: List<String>, onCharacterAdd: (numberOfStack: Int, element: Char) -> Unit) {
lines
.filter { it.contains("[") }
.forEach { line ->
line.forEachIndexed { index, char ->
if (char.isLetter()) {
onCharacterAdd(index / 4, char)
}
}
}
}
fun executeMoves(moves: List<Move>, stacks: List<ArrayDeque<Char>>) {
moves.forEach { move ->
repeat(move.quantity) { stacks[move.target].addFirst(stacks[move.source].removeFirst()) }
}
}
fun executeMovesGroup(moves: List<Move>, stacks: List<ArrayDeque<Char>>) {
moves.forEach { move ->
val movedElements = stacks[move.source].subList(0, move.quantity)
stacks[move.target].addAll(0, movedElements)
repeat(move.quantity) { stacks[move.source].removeFirst() }
}
}
fun part1(input: List<String>): String {
val numberOfStacks = numbersOfStacks(input)
val stacks = List(numberOfStacks) { ArrayDeque<Char>() }
populateStacks(input) { numberOfStack, element ->
stacks[numberOfStack].addLast(element)
}
val moves = input.filter { it.contains("move") }.map { it.toMove() }
executeMoves(moves, stacks)
return stacks.map { it.first() }.joinToString("")
}
fun part2(input: List<String>): String {
val numberOfStacks = numbersOfStacks(input)
val stacks = List(numberOfStacks) { ArrayDeque<Char>() }
populateStacks(input) { numberOfStack, element ->
stacks[numberOfStack].addLast(element)
}
val moves = input.filter { it.contains("move") }.map { it.toMove() }
executeMovesGroup(moves, stacks)
return stacks.map { it.first() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05/Day05_test")
val p1result = part1(testInput)
println(p1result)
check(p1result == "CMZ")
val p2result = part2(testInput)
println(p2result)
check(p2result == "MCD")
val input = readInput("Day05/Day05")
println(part1(input))
println(part2(input))
}
data class Move(val quantity: Int, val source: Int, val target: Int)
private fun String.toMove(): Move =
this
.split(' ')
.map { it.toIntOrNull() }
.filterNotNull()
.run {
Move(get(0), get(1) - 1, get(2) - 1)
} | 0 | Kotlin | 0 | 0 | cb81a0b8d3aa81a3f47b62962812f25ba34b57db | 2,780 | AOC-2022 | Apache License 2.0 |
src/Day20.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | fun main() {
fun part1(input: List<String>): Int {
val original = input.mapIndexed { idx, element -> Pair(idx, element.toInt()) }
val numbers = original.toMutableList()
val modulo = numbers.size
for (number in original.indices) {
val idx = numbers.indexOfFirst { it.first == number }
val next = (idx + numbers[idx].second).mod(modulo - 1)
numbers.add(next, numbers.removeAt(idx))
}
val zero = numbers.indexOfFirst { it.second == 0 }
val result =
numbers[(zero + 1000).mod(modulo)].second + numbers[(zero + 2000).mod(modulo)].second + numbers[(zero + 3000).mod(
modulo
)].second
return result
}
fun part2(input: List<String>): Long {
val key = 811589153L
val original = input.mapIndexed { idx, element -> Pair(idx, key * element.toLong()) }
val numbers = original.toMutableList()
val modulo = numbers.size
for (i in 1..10) {
for (number in original.indices) {
val idx = numbers.indexOfFirst { it.first == number }
val next = (idx + numbers[idx].second).mod(modulo - 1)
numbers.add(next, numbers.removeAt(idx))
}
}
val zero = numbers.indexOfFirst { it.second == 0L }
val result =
numbers[(zero + 1000).mod(modulo)].second + numbers[(zero + 2000).mod(modulo)].second + numbers[(zero + 3000).mod(
modulo
)].second
return result
}
// test if implementation meets criteria from the description, like:
val testInputExample = readInput("Day20_example")
check(part1(testInputExample) == 3)
check(part2(testInputExample) == 1623178306L)
val testInput = readInput("Day20_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 1,901 | aoc-2022-in-kotlin | Apache License 2.0 |
03/03.kt | Steve2608 | 433,779,296 | false | {"Python": 34592, "Julia": 13999, "Kotlin": 11412, "Shell": 349, "Cython": 211} | import java.io.File
private class Diagnostics(val data: Array<String>) {
val lastIndex: Int
get() = data[0].lastIndex
private val andBitMask: Int
get() = (1 shl (lastIndex + 1)) - 1
val gamma: Int
get() {
val counts = IntArray(data[0].length)
data.forEach { it.forEachIndexed { i, _ -> counts[i] = countBitPosition(data, i) } }
return counts.map { it >= data.size / 2 }.joinToString(separator = "") { if (it) "1" else "0" }.toInt(2)
}
val epsilon: Int
get() = (gamma xor Int.MAX_VALUE) and andBitMask
val oxygen: Int?
get() {
var filterData = data.toList()
for (i in 0..lastIndex) {
filterData = filterData.filter { it[i] == majorityAtBitPosition(filterData, i) }
if (filterData.size == 1) {
return filterData[0].toInt(2)
}
}
return null
}
val co2: Int?
get() {
var filterData = data.toList()
for (i in 0..lastIndex) {
filterData = filterData.filter { it[i] == minorityAtBitPosition(filterData, i) }
if (filterData.size == 1) {
return filterData[0].toInt(2)
}
}
return null
}
private fun countBitPosition(data: Array<String>, position: Int) = data.sumOf { it[position].toString().toInt() }
private fun majorityAtBitPosition(data: List<String>, position: Int): Char {
val counts = data.groupingBy { it[position] }.eachCount()
val comparator = compareByDescending<Map.Entry<Char, Int>> { it.value }.thenByDescending { it.key }
return counts.entries.sortedWith(comparator).first().key
}
private fun minorityAtBitPosition(data: List<String>, position: Int): Char {
val counts = data.groupingBy { it[position] }.eachCount()
val comparator = compareBy<Map.Entry<Char, Int>> { it.value }.thenBy { it.key }
return counts.entries.sortedWith(comparator).first().key
}
}
private fun part1(data: Array<String>): Int {
val diagnostics = Diagnostics(data)
return diagnostics.gamma * diagnostics.epsilon
}
private fun part2(data: Array<String>): Int {
val diagnostics = Diagnostics(data)
return diagnostics.oxygen!! * diagnostics.co2!!
}
fun main() {
fun File.readData() = this.readLines().toTypedArray()
val example: Array<String> = File("example.txt").readData()
assert(198 == part1(example)) { "Expected 22 * 9 = 198 increases" }
assert(230 == part2(example)) { "Expected 23 * 10 = 230 increases" }
val data: Array<String> = File("input.txt").readData()
println(part1(data))
println(part2(data))
} | 0 | Python | 0 | 1 | 2dcad5ecdce5e166eb053593d40b40d3e8e3f9b6 | 2,419 | AoC-2021 | MIT License |
src/main/kotlin/day5/Day5.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day5
import java.io.File
typealias Coordinates = Pair<Int, Int>
typealias Matrix = Map<Coordinates, Int>
private val regex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex()
fun parseLine(line: String): List<Int> =
regex.matchEntire(line)!!
.groupValues.drop(1) // dropping first item because it's the whole line
.map(String::toInt)
private fun expandRange(start: Int, end: Int) = if (start <= end) start.rangeTo(end) else start.downTo(end)
// required for part 1
fun expandSegmentRangeWithoutDiagonals(x1: Int, y1: Int, x2: Int, y2: Int): Iterable<Coordinates> = when {
x1 == x2 -> expandRange(y1, y2).map { x1 to it }
y1 == y2 -> expandRange(x1, x2).map { it to y1 }
else -> emptyList() // ignore
}
fun expandSegmentRange(x1: Int, y1: Int, x2: Int, y2: Int): Iterable<Coordinates> = when {
x1 == x2 -> expandRange(y1, y2).map { x1 to it }
y1 == y2 -> expandRange(x1, x2).map { it to y1 }
else -> expandRange(x1, x2).zip(expandRange(y1, y2)) // diagonal, update both coordinates
}
fun buildMatrix(segments: List<String>): Matrix =
segments
.map { segment -> parseLine(segment) }
.flatMap { (x1, y1, x2, y2) -> expandSegmentRange(x1, y1, x2, y2) }
.groupingBy { it }.eachCount()
fun countCloudSegmentOverlappingPoints(matrix: Matrix): Int = matrix.values.count { it > 1 }
fun main() {
File("./input/day5.txt").useLines { lines ->
val matrix = buildMatrix(lines.toList())
println(countCloudSegmentOverlappingPoints(matrix))
}
}
| 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 1,487 | advent-of-code-2021 | MIT License |
src/Day07.kt | timhillgit | 572,354,733 | false | {"Kotlin": 69577} | import kotlin.math.max
private sealed interface ElfFile
private data class ElfRegularFile(val size: Int): ElfFile
private class ElfPath(segments: List<String>): List<String> by segments {
constructor(vararg segments: String) : this(segments.toList())
override fun toString() = joinToString(separator = SEPARATOR, prefix = SEPARATOR)
operator fun plus(other: ElfPath) = ElfPath(plus(other as List<String>))
companion object {
const val SEPARATOR = "/"
}
}
private class ElfDirectory(val parent: ElfDirectory? = null): ElfFile {
val files = mutableMapOf<String, ElfFile>()
private fun root(): ElfDirectory = parent?.root() ?: this
fun cd(dir: String): ElfDirectory =
when (dir) {
ElfPath.SEPARATOR -> root()
".." -> parent ?: this
else -> files.getOrPut(dir) { ElfDirectory(this) } as ElfDirectory
}
fun putFile(fileName: String, fileInfo: String) {
files[fileName] = if (fileInfo == "dir") {
ElfDirectory(this)
} else {
ElfRegularFile(fileInfo.toInt())
}
}
/**
* Return a list of paths and the diskspace they're taking. The paths are from the perspective
* of the calling directory and the calling directory is always listed first.
*/
fun du(): List<Pair<ElfPath, Int>> = buildList {
val totalSize = files.asIterable().sumOf { (name, file) ->
when (file) {
is ElfRegularFile -> file.size
is ElfDirectory -> {
val children = file.du().map { (path, childSize) ->
(ElfPath(name) + path) to childSize
}
addAll(children)
children.first().second
}
}
}
add(0, ElfPath() to totalSize)
}
}
private fun List<String>.isCommand() = first() == "$"
fun main() {
val instructions = readInput("Day07").map { it.split(" ") }
val root = ElfDirectory()
var pwd = root
val iter = instructions.listIterator()
while (iter.hasNext()) {
var instruction = iter.next()
assert(instruction.isCommand())
val command = instruction[1]
when (command) {
"cd" -> {
val dir = instruction[2]
pwd = pwd.cd(dir)
}
"ls" -> {
while (iter.hasNext()) {
instruction = iter.next()
if (instruction.isCommand()) {
iter.previous()
break
}
val fileInfo = instruction[0]
val fileName = instruction[1]
pwd.putFile(fileName, fileInfo)
}
}
}
}
val diskUsage = root.du()
println("Disk usage:")
diskUsage.forEach { (path, size) ->
println("$path: $size")
}
val directorySizes = diskUsage
.map { it.second }
.sorted()
println(directorySizes.takeWhile { it <= 100000 }.sum())
val usedSpace = directorySizes.last()
val spaceToFree = max(usedSpace - 40000000, 0)
println(directorySizes.first { it >= spaceToFree })
}
| 0 | Kotlin | 0 | 1 | 76c6e8dc7b206fb8bc07d8b85ff18606f5232039 | 3,255 | advent-of-code-2022 | Apache License 2.0 |
src/Day03/Day03.kt | G-lalonde | 574,649,075 | false | {"Kotlin": 39626} | package Day03
import readInput
fun main() {
fun score(char: Char): Int {
if (char.isLowerCase()) {
return char.code - 'a'.code + 1
} else {
return char.code - 'A'.code + 27
}
}
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val firstPart = line.slice(0 until line.length / 2)
val secondPart = line.slice(line.length / 2 until line.length)
val intersection = firstPart
.filter { c -> secondPart.contains(c) }
.take(1)
.map { c -> score(c) }
.take(1)
score += intersection.first()
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
val parts = Array(3) { "" }
for ((i, line) in input.withIndex()) {
parts[i % 3] = line
if (i % 3 == 2) {
val firstPart = parts[0]
val secondPart = parts[1]
val thirdPart = parts[2]
val intersection = firstPart
.filter { c -> secondPart.contains(c) }
.filter { c -> thirdPart.contains(c) }
.take(1)
.map { c -> score(c) }
.take(1)
score += intersection.first()
parts[0] = ""
parts[1] = ""
parts[2] = ""
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03/Day03_test")
check(part1(testInput) == 157) { "Got instead : ${part1(testInput)}" }
check(part2(testInput) == 70) { "Got instead : ${part2(testInput)}" }
val input = readInput("Day03/Day03")
println("Answer for part 1 : ${part1(input)}")
println("Answer for part 2 : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 3463c3228471e7fc08dbe6f89af33199da1ceac9 | 1,950 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day20.kt | tobiasae | 434,034,540 | false | {"Kotlin": 72901} | class Day20 : Solvable("20") {
override fun solveA(input: List<String>): String {
val (enhancement, image) = getImageEnhancement(input)
return solve(image, enhancement, 2).toString()
}
override fun solveB(input: List<String>): String {
val (enhancement, image) = getImageEnhancement(input)
return solve(image, enhancement, 50).toString()
}
private fun getImageEnhancement(input: List<String>): Pair<String, List<List<Char>>> {
val enhancement = input.first()
val image =
mutableListOf<List<Char>>().also {
input.drop(2).forEach { line -> it.add(line.toCharArray().toList()) }
}
return Pair(enhancement, image)
}
private fun solve(image: List<List<Char>>, enhancement: String, num: Int): Int {
var res = image
for (i in 0 until num) {
res =
enhance(
res,
enhancement,
if (enhancement.first() == '#' && i % 2 == 0) enhancement.last()
else enhancement.first()
)
}
return res.map { it.count { it == '#' } }.sum()
}
private fun enhance(
image: List<List<Char>>,
enhancement: String,
default: Char
): List<List<Char>> {
return (-1..image.size).map { j ->
(-1..image.first().size).map { i ->
val number =
getSurroundingPoints(Pair(i, j))
.map { p ->
val c =
if (p.second in image.indices &&
p.first in image[p.second].indices
)
image[p.second][p.first]
else default
if (c == '#') 1 else 0
}
.toInt()
enhancement[number]
}
}
}
private fun getSurroundingPoints(p: Pair<Int, Int>): List<Pair<Int, Int>> {
return listOf(
Pair(p.first - 1, p.second - 1),
Pair(p.first, p.second - 1),
Pair(p.first + 1, p.second - 1),
Pair(p.first - 1, p.second),
Pair(p.first, p.second),
Pair(p.first + 1, p.second),
Pair(p.first - 1, p.second + 1),
Pair(p.first, p.second + 1),
Pair(p.first + 1, p.second + 1)
)
}
}
| 0 | Kotlin | 0 | 0 | 16233aa7c4820db072f35e7b08213d0bd3a5be69 | 2,756 | AdventOfCode | Creative Commons Zero v1.0 Universal |
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day07.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year23
import com.grappenmaker.aoc.*
fun PuzzleSet.day7() = puzzle(day = 7) {
data class Hand(val l: List<Char>, val bid: Long)
val hs = inputLines.map { l ->
val (a, b) = l.split(" ")
Hand(a.toList(), b.toLong())
}
fun solve(partTwo: Boolean, order: String): String {
val o = order.split(", ").map { it.single() }
val jo = o.filter { it != 'J' }
fun List<Char>.type(): Int {
val count = frequencies().values.frequencies()
return when {
5 in count -> 0
4 in count -> 1
3 in count && 2 in count -> 2
3 in count -> 3
(count[2] ?: 0) == 2 -> 4
2 in count -> 5
else -> 6
}
}
fun List<Char>.optimizeJokers() = jo.map { a -> map { if (it == 'J') a else it } }.minBy { it.type() }
val res = hs.sortedWith(compareByDescending<Hand> { h ->
h.l.let { if (partTwo) it.optimizeJokers() else it }.type()
}.thenComparator { a, b ->
a.l.indices.firstNotNullOf { i -> (o.indexOf(b.l[i]) - o.indexOf(a.l[i])).takeIf { it != 0 } }
})
return res.mapIndexed { idx, h -> (h.bid * (idx + 1)) }.sum().s()
}
partOne = solve(false, "A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, 2")
partTwo = solve(true, "A, K, Q, T, 9, 8, 7, 6, 5, 4, 3, 2, J")
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,438 | advent-of-code | The Unlicense |
src/Day16.kt | jstapels | 572,982,488 | false | {"Kotlin": 74335} | import java.util.concurrent.atomic.AtomicInteger
private data class Valve(val id: String, val rate: Int, val tunnels: List<String>)
private val routes = mutableMapOf<Set<String>, Int>()
private fun Map<String, Valve>.calcRouteCost(start: String, end: String): Int {
val nodes = setOf(start, end)
if (nodes in routes) return routes[nodes]!!
val parents = mutableMapOf<String, String>()
val explored = mutableSetOf(start)
val search = mutableListOf(start)
while (search.isNotEmpty()) {
val node = search.removeFirst()
if (node == end) {
var distance = 0
var n = node
while (n != start) {
distance++
n = parents[n]!!
}
routes[nodes] = distance
return distance
}
getValue(node).tunnels.forEach {
if (it !in explored) {
explored.add(it)
search.add(it)
parents[it] = node
}
}
}
throw IllegalStateException()
}
private data class Worker(val name: String, val minutes: Int = 30, val valve: String = "AA")
fun main() {
val day = 16
fun parseValve(line: String): Valve {
val re = """Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? (.*)""".toRegex()
val match = re.matchEntire(line) ?: throw IllegalStateException("No match for $line")
val id = match.groups[1]!!.value
val rate = match.groups[2]!!.value.toInt()
val tunnels = match.groups[3]!!.value.split(", ")
return Valve(id, rate, tunnels)
}
fun parseInput(input: List<String>) =
input.map { parseValve(it) }
.associateBy { it.id }
fun Map<String, Valve>.potential(workers: List<Worker>, remaining: Set<String>): Int {
var potential = workers.sumOf { (it.minutes - 1) * this[it.valve]!!.rate }
remaining.forEach { v ->
val pressure = workers.maxOf { (it.minutes - 1 - calcRouteCost(it.valve, v)) * this[v]!!.rate }
if (pressure > 0) potential += pressure
}
return potential
}
fun Map<String, Valve>.usefulValves() =
values.filter { it.rate >0 }
.map { it.id }
.toSet()
fun Map<String, Valve>.calcPressure(workers: List<Worker>, remaining: Set<String> = usefulValves(), pressureSoFar: Int = 0, best: AtomicInteger = AtomicInteger(0)): Int {
if (workers.isEmpty()) return pressureSoFar
// Pick next worker by minutes left
val worker = workers.maxBy { it.minutes }
val otherWorkers = workers - worker
val name = worker.name
val valve = worker.valve
val minutes = worker.minutes
// No time left
if (minutes <= 1) return pressureSoFar
val myPressure = this[valve]!!.rate * (minutes - 1)
val pressure = myPressure + pressureSoFar
if (remaining.isEmpty()) {
return calcPressure(otherWorkers, remaining, pressure, best)
}
val possiblePressure = pressureSoFar + potential(workers, remaining)
if (possiblePressure < best.get()) {
return pressure
}
val openTime = if (myPressure > 0) 1 else 0
val bestPressure = remaining.sortedByDescending { (minutes - 2 - calcRouteCost(valve, it)) * this[it]!!.rate }
.maxOf {
val timeLeft = minutes - openTime - calcRouteCost(valve, it)
val newWorker = Worker(name, timeLeft, it)
val p = calcPressure(otherWorkers + newWorker, remaining - it, pressure, best)
p
}
if (bestPressure > best.get()) {
best.set(bestPressure)
// println("New best pressure $bestPressure")
}
return bestPressure
}
fun part1(input: List<String>): Int {
val valves = parseInput(input)
val me = Worker("Me")
val out = valves.calcPressure(listOf(me))
return out
}
fun part2(input: List<String>): Int {
val valves = parseInput(input)
val me = Worker("Me", 26)
val elephant = Worker("Elephant", 26)
val out = valves.calcPressure(listOf(me, elephant))
return out
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day.pad(2)}_test")
checkTest(1651) { part1(testInput) }
checkTest(1707) { part2(testInput) }
val input = readInput("Day${day.pad(2)}")
solution { part1(input) }
solution { part2(input) }
}
| 0 | Kotlin | 0 | 0 | 0d71521039231c996e2c4e2d410960d34270e876 | 4,577 | aoc22 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.