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/utils/Graph.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package utils data class Graph<T : Identifiable>( val nodes: Set<T>, val neighbors: Map<Identifier, Set<Identifier>>, val costs: Map<Pair<Identifier, Identifier>, Long>, ) { val edges: Set<Pair<Identifier, Identifier>> by lazy { neighbors.flatMapTo(mutableSetOf()) { (start, destinations) -> destinations.asSequence().map { start to it } } } fun cost(from: T, to: T) = costs.getOrDefault(from.identifier to to.identifier, 0L) } fun <T : Identifiable> Graph<T>.depthFirstSearch(start: T, filterNeighbors: (path: List<T>, neighbors: Set<T>) -> Set<T>): Sequence<List<T>> { return depthFirstSearchInternal(listOf(start), filterNeighbors) } private fun <T : Identifiable> Graph<T>.depthFirstSearchInternal(path: List<T>, filterNeighbors: (path: List<T>, neighbors: Set<T>) -> Set<T>): Sequence<List<T>> { return neighbors[path.last().identifier] .orEmpty() .mapTo(mutableSetOf()) { identifier -> nodes.first { it.identifier == identifier } } .let { filterNeighbors(path, it) } .asSequence() .map { path + it } .flatMap { depthFirstSearchInternal(it, filterNeighbors) } .plus(sequenceOf(path)) } fun <T : Identifiable> Graph<T>.breadthFirstSearch(start: T, filterNeighbors: (path: List<T>, neighbors: Set<T>) -> Set<T>): Sequence<List<T>> { return generateSequence(listOf(listOf(start))) { previousPaths -> previousPaths.flatMap { path -> val neighbors = neighbors[path.last().identifier].orEmpty() if (neighbors.isEmpty()) emptyList() else filterNeighbors( path, neighbors.mapTo(mutableSetOf()) { identifier -> nodes.first { it.identifier == identifier } } ).map { path + it } } }.flatten() }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
1,814
Advent-of-Code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxNumEdgesToRemove.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 /** * 1579. Remove Max Number of Edges to Keep Graph Fully Traversable * @see <a href="https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable"> * Source</a> */ fun interface MaxNumEdgesToRemove { operator fun invoke(n: Int, edges: Array<IntArray>): Int } class MaxNumEdgesToRemoveDSU : MaxNumEdgesToRemove { override operator fun invoke(n: Int, edges: Array<IntArray>): Int { // Different objects for Alice and Bob. val alice = UnionFind(n) val bob = UnionFind(n) var edgesRequired = 0 // Perform union for edges of type = 3, for both Alice and Bob. for (edge in edges) { if (edge[0] == 3) { edgesRequired += alice.performUnion(edge[1], edge[2]) or bob.performUnion(edge[1], edge[2]) } } // Perform union for Alice if type = 1 and for Bob if type = 2. for (edge in edges) { if (edge[0] == 1) { edgesRequired += alice.performUnion(edge[1], edge[2]) } else if (edge[0] == 2) { edgesRequired += bob.performUnion(edge[1], edge[2]) } } // Check if the Graphs for Alice and Bob have n - 1 edges or is a single component. return if (alice.isConnected && bob.isConnected) { edges.size - edgesRequired } else { -1 } } private class UnionFind( // Number of distinct components in the graph. var components: Int, ) { var representative: IntArray = IntArray(components + 1) var componentSize: IntArray = IntArray(components + 1) // Initialize the list representative and componentSize // Each node is representative of itself with size 1. init { for (i in 0..components) { representative[i] = i componentSize[i] = 1 } } // Get the root of a node. fun findRepresentative(x: Int): Int { return if (representative[x] == x) { x } else findRepresentative(representative[x]).also { representative[x] = it } // Path compression. } // Perform the union of two components that belongs to node x and node y. fun performUnion(x: Int, y: Int): Int { var x1 = x var y1 = y x1 = findRepresentative(x1) y1 = findRepresentative(y1) if (x1 == y1) { return 0 } if (componentSize[x1] > componentSize[y1]) { componentSize[x1] += componentSize[y1] representative[y1] = x1 } else { componentSize[y1] += componentSize[x1] representative[x1] = y1 } components-- return 1 } val isConnected: Boolean // Returns true if all nodes get merged to one. get() = components == 1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,662
kotlab
Apache License 2.0
Kotlin/Dijkstra.kt
lprimeroo
41,106,663
false
null
class Dijkstra { // Dijkstra's algorithm to find shortest path from s to all other nodes fun dijkstra(G: WeightedGraph, s: Int): IntArray { val dist = IntArray(G.size()) // shortest known distance from "s" val pred = IntArray(G.size()) // preceeding node in path val visited = BooleanArray(G.size()) // all false initially for (i in dist.indices) { dist[i] = Integer.MAX_VALUE } dist[s] = 0 for (i in dist.indices) { val next = minVertex(dist, visited) visited[next] = true // The shortest path to next is dist[next] and via pred[next]. val n = G.neighbors(next) for (j in n.indices) { val v = n[j] val d = dist[next] + G.getWeight(next, v) if (dist[v] > d) { dist[v] = d pred[v] = next } } } return pred // (ignore pred[s]==0!) } private fun minVertex(dist: IntArray, v: BooleanArray): Int { var x = Integer.MAX_VALUE var y = -1 // graph not connected, or no unvisited vertices for (i in dist.indices) { if (!v[i] && dist[i] < x) { y = i x = dist[i] } } return y } fun printPath(G: WeightedGraph, pred: IntArray, s: Int, e: Int) { val path = java.util.ArrayList() var x = e while (x != s) { path.add(0, G.getLabel(x)) x = pred[x] } path.add(0, G.getLabel(s)) System.out.println(path) } }
56
C++
186
99
16367eb9796b6d4681c5ddf45248e2bcda72de80
1,657
DSA
MIT License
kotlin/src/com/daily/algothrim/leetcode/Trie.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 208. 实现 Trie (前缀树) * * Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。 * * 请你实现 Trie 类: * * Trie() 初始化前缀树对象。 * void insert(String word) 向前缀树中插入字符串 word 。 * boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。 * boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。 */ class Trie { companion object { @JvmStatic fun main(args: Array<String>) { Trie().apply { insert("apple") println(search("apple")) println(search("app")) println(startsWith("app")) insert("app") println(search("app")) } } } /** Initialize your data structure here. */ class TrieNode { var children = Array<TrieNode?>(26) { null } var isEnd = false } private val root = TrieNode() /** Inserts a word into the trie. */ fun insert(word: String) { var p = root word.forEach { val index = it - 'a' if (p.children[index] == null) { p.children[index] = TrieNode() } p = p.children[index]!! } p.isEnd = true } /** Returns if the word is in the trie. */ fun search(word: String): Boolean { var p = root word.forEach { val index = it - 'a' if (p.children[index] == null) return false p = p.children[index]!! } return p.isEnd } /** Returns if there is any word in the trie that starts with the given prefix. */ fun startsWith(prefix: String): Boolean { var p = root prefix.forEach { val index = it - 'a' if (p.children[index] == null) return false p = p.children[index]!! } return true } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,282
daily_algorithm
Apache License 2.0
src/main/kotlin/net/navatwo/adventofcode2023/day7/Day7Solution.kt
Nava2
726,034,626
false
{"Kotlin": 100705, "Python": 2640, "Shell": 28}
package net.navatwo.adventofcode2023.day7 import net.navatwo.adventofcode2023.framework.ComputedResult import net.navatwo.adventofcode2023.framework.Solution sealed class Day7Solution : Solution<Day7Solution.Game> { internal abstract val handComparator: Comparator<Hand> // lazy due to accessing `abstract val` property private val tripleComparator: Comparator<ComputedTriple> by lazy(LazyThreadSafetyMode.NONE) { Comparator .comparing<ComputedTriple, HandType> { it.handType } .thenBy(handComparator) { it.hand } } internal abstract fun computeHandType(hand: Hand): HandType override fun solve(input: Game): ComputedResult { val computeHandTypes = input.handPairs.asSequence() .map { (hand, bid) -> ComputedTriple(hand, computeHandType(hand), bid) } val rankedHands = computeHandTypes.toSortedSet(tripleComparator.reversed()) val rankedBids = rankedHands.asSequence().map { it.bid } val result = rankedBids.withIndex() .fold(0L) { acc, (index, bid) -> acc + (index + 1) * bid.value } return ComputedResult.Simple(result) } data object Part1 : Day7Solution() { internal val cardComparator: Comparator<PlayingCard> = Comparator.comparing { it.ordinal } override val handComparator = Hand.comparator(cardComparator) override fun computeHandType(hand: Hand): HandType { val cardFrequencies = hand.countCards() return HandType.computeFromCardFrequencies(cardFrequencies) } } data object Part2 : Day7Solution() { internal val cardComparator: Comparator<PlayingCard> = Comparator.comparing { card -> if (card == PlayingCard.Jack) { PlayingCard.Two.ordinal + 50 // really after 2 } else { card.ordinal } } override val handComparator = Hand.comparator(cardComparator) override fun computeHandType(hand: Hand): HandType { val cardFrequencies = hand.countCards() val jackCount = cardFrequencies[PlayingCard.Jack] // No jacks => no need to upgrade them ?: return HandType.computeFromCardFrequencies(cardFrequencies) // update most frequent, non-Jack card to add count of jacks or add Ace with jack count otherwise val mostFrequentCard = cardFrequencies.entries.asSequence() .filter { (card, _) -> card != PlayingCard.Jack } .sortedWith { p1, p2 -> val (card1, count1) = p1 val (card2, count2) = p2 val countComparison = count2.compareTo(count1) if (countComparison != 0) return@sortedWith countComparison cardComparator.compare(card1, card2) } .maxByOrNull { (_, count) -> count }?.key ?: PlayingCard.Ace val newFrequencies = cardFrequencies.apply { remove(PlayingCard.Jack) compute(mostFrequentCard) { _, count -> (count ?: 0) + jackCount } } return HandType.computeFromCardFrequencies(newFrequencies) } } override fun parse(lines: Sequence<String>): Game { val handPairs = lines.map { line -> val (hand, bid) = line.split(" ", limit = 2) Hand.parse(hand) to Bid(bid.toLong()) } return Game(handPairs.toList()) } data class ComputedTriple( val hand: Hand, val handType: HandType, val bid: Bid, ) { companion object } @JvmInline value class Hand(val cards: List<PlayingCard>) { fun countCards(): MutableMap<PlayingCard, Int> = cards.fold(mutableMapOf()) { acc, card -> acc.compute(card) { _, count -> (count ?: 0) + 1 } acc } override fun toString(): String = cards.joinToString(separator = "") { it.shortName.toString() } companion object { fun comparator(cardComparator: Comparator<PlayingCard>): Comparator<Hand> = Comparator { h1, h2 -> for ((c1, c2) in h1.cards.asSequence().zip(h2.cards.asSequence())) { val cardComparison = cardComparator.compare(c1, c2) if (cardComparison != 0) return@Comparator cardComparison } 0 } fun parse(line: CharSequence): Hand { val cards = line.map { PlayingCard.byShortName(it) } return Hand(cards) } } } @JvmInline value class Bid(val value: Long) @JvmInline value class Game(val handPairs: List<Pair<Hand, Bid>>) enum class PlayingCard(val shortName: Char) : Comparable<PlayingCard> { Ace('A'), King('K'), Queen('Q'), Jack('J'), Ten('T'), Nine('9'), Eight('8'), Seven('7'), Six('6'), Five('5'), Four('4'), Three('3'), Two('2'), ; companion object { private val byShortName = entries.associateBy { it.shortName } fun byShortName(shortName: Char): PlayingCard { return byShortName.getValue(shortName) } } } enum class HandType { FiveOfAKind, FourOfAKind, FullHouse, ThreeOfAKind, TwoPair, OnePair, HighCard, ; companion object { fun computeFromCardFrequencies(cardFrequencies: Map<PlayingCard, Int>): HandType { val (highestCountCard, highestCount) = cardFrequencies.entries.maxBy { (_, count) -> count } return when { cardFrequencies.size == 1 -> FiveOfAKind cardFrequencies.size == 2 -> { if (highestCount in 2..3) { FullHouse } else { FourOfAKind } } cardFrequencies.size == 3 && highestCount == 3 -> ThreeOfAKind cardFrequencies.size == 3 && highestCount == 2 -> TwoPair cardFrequencies.size == 4 -> OnePair else -> HighCard } } } } }
0
Kotlin
0
0
4b45e663120ad7beabdd1a0f304023cc0b236255
5,667
advent-of-code-2023
MIT License
src/aoc2018/kot/Day04.kt
Tandrial
47,354,790
false
null
package aoc2018.kot import getNumbers import java.io.File object Day04 { data class Guard(val id: Int, val sleeps: MutableList<List<Int>> = mutableListOf()) fun partOne(input: List<String>): Int { val guards = parse(input) val maxSleeper = guards.maxBy { it.sleeps.sumBy { it.last() - it.first() } }!! val sleepTime = maxSleeper.sleeps.flatten().groupingBy { it }.eachCount().maxBy { it.value }!!.key return sleepTime * maxSleeper.id } fun partTwo(input: List<String>): Int { val guards = parse(input) val (gId, min) = guards.map { Pair(it.id, it.sleeps.flatten().groupingBy { it }.eachCount().maxBy { it.value }!!) }.maxBy { (_, count) -> count.value }!! return gId * min.key } fun parse(inputs: List<String>): Collection<Guard> { val guards = mutableMapOf<Int, Guard>() var guardID = -1 var startSleep = 0 for (line in inputs.sorted()) { val nums = line.getNumbers() when { "Guard" in line -> guardID = nums[5] "falls" in line -> startSleep = nums[4] else -> guards.computeIfAbsent(guardID) { Guard(guardID) }.sleeps.add((startSleep..nums[4]).toList()) } } return guards.values.filter { it.sleeps.isNotEmpty() } } } fun main(args: Array<String>) { val input = File("./input/2018/Day04_input.txt").readLines() println("Part One = ${Day04.partOne(input)}") println("Part Two = ${Day04.partTwo(input)}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,436
Advent_of_Code
MIT License
2022/Day07.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
sealed class Node(val size: Long) { class Dir(val children: MutableMap<String, Node> = mutableMapOf(), size: Long = 0) : Node(size) class File(size: Long) : Node(size) } fun main() { val input = readInput("Day07") val root = Node.Dir() val stack = ArrayDeque(listOf(root)) for (s in input) { when { s.startsWith("$ cd ") -> { when (val dir = s.removePrefix("$ cd ")) { "/" -> { stack.clear() stack.addLast(root) } ".." -> stack.removeLast() else -> stack.addLast(stack.last().children[dir] as Node.Dir) } } s.startsWith("$ ls") -> continue else -> { val (size, name) = s.split(' ') if (size == "dir") { stack.last().children[name] = Node.Dir() } else { stack.last().children[name] = Node.File(size.toLong()) } } } } val dirs = mutableListOf<Node.Dir>() fun calcSize(n: Node): Node = when (n) { is Node.Dir -> { val children = n.children.mapValues { calcSize(it.value) } val size = children.values.sumOf { it.size } Node.Dir(children.toMutableMap(), size).also { dirs.add(it) } } is Node.File -> n } val newRoot = calcSize(root) println(dirs.filter { it.size <= 100_000 }.sumOf { it.size }) val freeSpace = 70000000L - newRoot.size val spaceNeed = 30000000 println(dirs.map { it.size }.filter { freeSpace + it >= spaceNeed }.min()) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,722
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day02.kt
EmRe-One
568,569,073
false
{"Kotlin": 166986}
package tr.emreone.adventofcode.days object Day02 { /* * Score is calculated by adding the score of shape with the score for the round * * 1 for Rock * 2 for Paper, and * 3 for Scissors * * plus * * 0 if you lost * 3 if the round was a draw, and * 6 if you won */ enum class HandShape( val score: Int ) { ROCK(1), PAPER(2), SCISSORS(3); fun getShapeForWin(): HandShape { return when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } } fun getShapeForLoose(): HandShape { return when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } } companion object { fun parseFrom(char: Char): HandShape { return when (char) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw IllegalArgumentException("Shape must be A, B, C or X, Y, Z") } } } } private fun parseRounds(input: List<String>) = input.map { round -> val (player1, player2) = round.split(" ").map { HandShape.parseFrom(it.first()) } player1 to player2 } fun part1(input: List<String>): Int { val rounds = parseRounds(input) return rounds.sumOf { round -> // return score of your shape plus score of the round round.second.score + when (round.second) { round.first.getShapeForWin() -> 6 round.first -> 3 else -> 0 } } } fun part2(input: List<String>): Int { val rounds = parseRounds(input) return rounds.sumOf { round -> when (round.second) { HandShape.ROCK -> 0 + round.first.getShapeForLoose().score // needs a lose HandShape.PAPER -> 3 + round.first.score // needs a draw HandShape.SCISSORS -> 6 + round.first.getShapeForWin().score // needs a win } } } }
0
Kotlin
0
0
a951d2660145d3bf52db5cd6d6a07998dbfcb316
2,318
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day2.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days import days.Day2.SubmarineDirection.DOWN import days.Day2.SubmarineDirection.FORWARD import days.Day2.SubmarineDirection.UP class Day2 : Day(2) { private val submarine = Submarine(SubmarinePosition(), inputList) override fun partOne(): Any { return submarine.move( { position, amount -> position.copy(d = position.d - amount) }, { position, amount -> position.copy(d = position.d + amount) }, { position, amount -> position.copy(h = position.h + amount) } ) } override fun partTwo(): Any { return submarine.move( { position, amount -> position.copy(a = position.a - amount) }, { position, amount -> position.copy(a = position.a + amount) }, { position, amount -> position.copy(h = position.h + amount, d = position.d + (position.a * amount)) } ) } data class Submarine(val initialPosition: SubmarinePosition, val commands: List<String>) { fun move(onUp: SubmarineMovement, onDown: SubmarineMovement, onForward: SubmarineMovement): Int { return commands.map { SubmarineCommand(it) }.fold(initialPosition) { position, (direction, amount) -> when (direction) { FORWARD -> onForward(position, amount) DOWN -> onDown(position, amount) UP -> onUp(position, amount) } }.getPosition() } } data class SubmarineCommand(val direction: SubmarineDirection, val amount: Int) { constructor(command: String) : this( SubmarineDirection.valueOf(command.takeWhile { it != ' ' }.uppercase()), command.takeLastWhile { it != ' ' }.toInt() ) } enum class SubmarineDirection { FORWARD, DOWN, UP } data class SubmarinePosition(val h: Int = 0, val d: Int = 0, val a: Int = 0) { fun getPosition(): Int = h * d } } typealias SubmarineMovement = (p: Day2.SubmarinePosition, a: Int) -> Day2.SubmarinePosition
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
2,037
aoc-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day21.kt
clechasseur
568,233,589
false
{"Kotlin": 242914}
package io.github.clechasseur.adventofcode.y2015 import kotlin.math.max object Day21 { private val input = Protagonist(hp = 100, damage = 8, armor = 2, equipment = emptyList()) fun part1(): Int = playerLayouts().sortedBy { it.totalCost }.filter { `fight!`(it) }.first().totalCost fun part2(): Int = playerLayouts().sortedByDescending { it.totalCost }.filter { !`fight!`(it) }.first().totalCost private data class Equipment(val cost: Int, val damage: Int, val armor: Int) private data class Protagonist(val hp: Int, val damage: Int, val armor: Int, val equipment: List<Equipment>) { val totalDamage: Int get() = damage + equipment.sumOf { it.damage } val totalArmor: Int get() = armor + equipment.sumOf { it.armor } val totalCost: Int get() = equipment.sumOf { it.cost } val dead: Boolean get() = hp <= 0 fun afterAttack(by: Protagonist): Protagonist = Protagonist( hp = hp - max(by.totalDamage - totalArmor, 1), damage = damage, armor = armor, equipment = equipment, ) } private fun `fight!`(startingPlayer: Protagonist): Boolean { var player = startingPlayer var boss = input while (true) { boss = boss.afterAttack(player) if (boss.dead) { return true } player = player.afterAttack(boss) if (player.dead) { return false } } } private val weapons = listOf( Equipment(cost = 8, damage = 4, armor = 0), Equipment(cost = 10, damage = 5, armor = 0), Equipment(cost = 25, damage = 6, armor = 0), Equipment(cost = 40, damage = 7, armor = 0), Equipment(cost = 74, damage = 8, armor = 0), ) private val armors = listOf( Equipment(cost = 0, damage = 0, armor = 0), Equipment(cost = 13, damage = 0, armor = 1), Equipment(cost = 31, damage = 0, armor = 2), Equipment(cost = 53, damage = 0, armor = 3), Equipment(cost = 75, damage = 0, armor = 4), Equipment(cost = 102, damage = 0, armor = 5), ) private val rings = listOf( Equipment(cost = 0, damage = 0, armor = 0), Equipment(cost = 25, damage = 1, armor = 0), Equipment(cost = 50, damage = 2, armor = 0), Equipment(cost = 100, damage = 3, armor = 0), Equipment(cost = 20, damage = 0, armor = 1), Equipment(cost = 40, damage = 0, armor = 2), Equipment(cost = 80, damage = 0, armor = 3), ) private fun weaponLayouts(): Sequence<List<Equipment>> = weapons.asSequence().map { listOf(it) } private fun armorLayouts(): Sequence<List<Equipment>> = armors.asSequence().map { listOf(it) } private fun ringLayouts(): Sequence<List<Equipment>> = rings.indices.asSequence().flatMap { i -> rings.indices.asSequence().mapNotNull { j -> if (i != j || i == 0) listOf(rings[i], rings[j]) else null } } private fun playerLayouts(): Sequence<Protagonist> = weaponLayouts().flatMap { weps -> armorLayouts().flatMap { arms -> ringLayouts().map { rngs -> weps + arms + rngs } } }.map { Protagonist(hp = 100, damage = 0, armor = 0, equipment = it) } }
0
Kotlin
0
0
e5a83093156cd7cd4afa41c93967a5181fd6ab80
3,375
adventofcode2015
MIT License
src/day11/Day11.kt
robin-schoch
572,718,550
false
{"Kotlin": 26220}
package day11 import AdventOfCodeSolution fun main() { Day11.run() } var supermodulo = 1L sealed class Operation { abstract val value: Long? fun execute(item: Long): Long = item.execute(value ?: item) abstract fun Long.execute(change: Long): Long companion object { fun fromString(ops: String): Operation { ops.split(" ").let { val n = if (it[2] == "old") null else it[2].toLong() return when (it[1]) { "*" -> Multiply(n) "+" -> Addition(n) else -> error("invalid ops") } } } } } class Addition(override val value: Long?) : Operation() { override fun Long.execute(change: Long) = this + change } class Multiply(override val value: Long?) : Operation() { override fun Long.execute(change: Long) = this * change } class TestCondition(private val divisbleBy: Long, private val then: Int, private val otherwise: Int) { fun test(value: Long) = if (value % divisbleBy == 0L) then else otherwise companion object { fun fromLines(lines: List<String>): TestCondition { val divisbleBy = lines[0].split(" by ")[1].toLong() supermodulo *= divisbleBy val thenMonkeyId = lines[1].split(" monkey ")[1].toInt() val otherwiseMonkeyId = lines[2].split(" monkey ")[1].toInt() return TestCondition(divisbleBy, thenMonkeyId, otherwiseMonkeyId) } } } class Monkey(val id: Int, val items: ArrayDeque<Long>, val ops: Operation, val test: TestCondition, val reliever: (Long) -> Long) { var inspectionCount = 0 infix fun playTurn(monkeies: Array<Monkey>) { inspectItems() monkeies.throwItems() } private fun Array<Monkey>.throwItems() { for (i in items.indices) { items.removeFirst().also { val nextMonkey = test.test(it) get(nextMonkey).items.addLast(it) } } } private fun inspectItems() { inspectionCount += items.size items.forEachIndexed { index, i -> items[index] = reliever(ops.execute(i)) % supermodulo } } override fun toString(): String { return "Monkey $id inspected items $inspectionCount times" } companion object { fun fromInput(input: List<String>, reliever: (Long) -> Long ): Monkey { val id = input[0].split(" ")[1].dropLast(1).toInt() val items = ArrayDeque(input[1].split(": ")[1].split(", ").map { it.toLong() }) val operation = Operation.fromString(input[2].split(" = ")[1]) val condition = TestCondition.fromLines(input.drop(3)) return Monkey(id, items, operation, condition, reliever) } } } object Day11 : AdventOfCodeSolution<Long, Long> { override val testSolution1 = 10605L override val testSolution2 = 2713310158L private fun Array<Monkey>.playRound() = forEach { it playTurn this } private fun parseMonkeys(input: List<String>, reliever: (Long) -> Long = {it / 3L}) = input.chunked(7).map { Monkey.fromInput(it, reliever) }.toTypedArray() override fun part1(input: List<String>): Long { supermodulo = 1 val monkeys = parseMonkeys(input) repeat(20) { monkeys.playRound() } return monkeys .toList() .sortedByDescending { it.inspectionCount } .take(2) .fold(1) { acc, monkey -> acc * monkey.inspectionCount } } override fun part2(input: List<String>): Long { supermodulo = 1 val monkeys = parseMonkeys(input) { it} repeat(10000) { monkeys.playRound()} return monkeys .toList() .sortedByDescending { it.inspectionCount } .take(2) .fold(1) { acc, monkey -> acc * monkey.inspectionCount } } }
0
Kotlin
0
0
fa993787cbeee21ab103d2ce7a02033561e3fac3
3,900
aoc-2022
Apache License 2.0
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day07/Day07.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pietromaggi.aoc2021.day07 import com.pietromaggi.aoc2021.readInput import kotlin.math.abs fun part1(input: List<String>): Int { val crabList = input[0].split(",").map(String::toInt).sorted() // We use the median val median = crabList[crabList.size / 2] val resultList = mutableListOf<Int>() for (candidate in (median - 1)..(median + 1)) { resultList.add(crabList.fold(0) { sum, element -> sum + abs(element - candidate) }) } return resultList.reduce { a: Int, b: Int -> a.coerceAtMost(b) } } fun movesToFuel(moves: Int) = (1..moves).sum() fun part2(input: List<String>): Int { val crabList = input[0].split(",").map(String::toInt).sorted() // We use the average val average = (0.5 + crabList.average()).toInt() val resultList = mutableListOf<Int>() for (candidate in (average - 1)..(average + 1)) { resultList.add(crabList.fold(0) { sum, element -> sum + movesToFuel(abs(element - candidate)) }) } return resultList.reduce { a: Int, b: Int -> a.coerceAtMost(b) } } fun main() { val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
1,758
AdventOfCode
Apache License 2.0
src/year2022/21/Day21.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2022.`21` import readInput @JvmInline value class NodeTitle(val value: String) enum class OperationType { PLUS, MINUS, MUL, DIV; companion object { fun from(string: String): OperationType { return when (string) { "*" -> MUL "/" -> DIV "+" -> PLUS "-" -> MINUS else -> error("!!!") } } } } sealed class Command { data class Value(val amount: Long) : Command() data class Operation( val leftNode: NodeTitle, val rightNode: NodeTitle, val type: OperationType ) : Command() } fun parseInput(input: List<String>): Map<NodeTitle, Command> { return input .map { val res = it.split(": ") val nodeTitle = NodeTitle(res[0]) val split = res[1].split(" ") val rightSide = if (split.size == 1) { Command.Value(split.first().toLong()) } else { val (left, operation, right) = split Command.Operation( leftNode = NodeTitle(left), rightNode = NodeTitle(right), type = OperationType.from(operation) ) } nodeTitle to rightSide } .associate { it } } fun evalCommand( command: Command, nodeMap: Map<NodeTitle, Command> ): Long { return when (command) { is Command.Operation -> { val left = nodeMap[command.leftNode]!! val right = nodeMap[command.rightNode]!! when (command.type) { OperationType.PLUS -> evalCommand(left, nodeMap) + evalCommand(right, nodeMap) OperationType.MINUS -> evalCommand(left, nodeMap) - evalCommand(right, nodeMap) OperationType.MUL -> evalCommand(left, nodeMap) * evalCommand(right, nodeMap) OperationType.DIV -> evalCommand(left, nodeMap) / evalCommand(right, nodeMap) } } is Command.Value -> command.amount } } fun buildExpression( command: Command, stringBuilder: StringBuilder, map: Map<NodeTitle, Command> ) { when (command) { is Command.Operation -> { val left = map[command.leftNode]!! val right = map[command.rightNode]!! stringBuilder.append("(") buildExpression(left, stringBuilder, map) when (command.type) { OperationType.PLUS -> stringBuilder.append("+") OperationType.MINUS -> stringBuilder.append("-") OperationType.MUL -> stringBuilder.append("*") OperationType.DIV -> stringBuilder.append("/") } buildExpression(right, stringBuilder, map) stringBuilder.append(")") } is Command.Value -> { if (command.amount == 0L) { stringBuilder.append("x") } else { stringBuilder.append(command.amount) } } } } fun main() { fun part1(input: List<String>): Long { val root = NodeTitle("root") val map = parseInput(input) val rootNode = map[root]!! return evalCommand(rootNode, map) } /** * Lazy solution - just build string and put it into online solver */ fun part2(input: List<String>): String { val root = NodeTitle("root") val humn = NodeTitle("humn") val map = parseInput(input) .mapValues { (nodeTitle, command) -> if (nodeTitle == humn) { Command.Value(0) } else { command } } val expressionString = StringBuilder().also { stringBuilder -> val rootNode = map[root]!! as Command.Operation /** * Build left side of expression */ buildExpression(map[rootNode.leftNode]!!, stringBuilder, map) stringBuilder.append("=") /** * Calculate and build right side of expression */ val rightResult = evalCommand(map[rootNode.rightNode]!!, map) stringBuilder.append(rightResult.toString()) stringBuilder.appendLine() }.toString() /** * Just Copy-paste result of expression and put in here: * https://www.mathpapa.com/equation-solver/ */ return expressionString } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 152L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
4,828
KotlinAdventOfCode
Apache License 2.0
grind-75-kotlin/src/main/kotlin/BestTimeToBuyAndSellStock.kt
Codextor
484,602,390
false
{"Kotlin": 27206}
/** * You are given an array prices where prices[i] is the price of a given stock on the ith day. * * You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. * * Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. * * * * Example 1: * * Input: prices = [7,1,5,3,6,4] * Output: 5 * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. * Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. * Example 2: * * Input: prices = [7,6,4,3,1] * Output: 0 * Explanation: In this case, no transactions are done and the max profit = 0. * * * Constraints: * * 1 <= prices.length <= 10^5 * 0 <= prices[i] <= 10^4 * @see <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">LeetCode</a> */ fun maxProfit(prices: IntArray): Int { if (prices.size == 1) { return 0 } var lowestPriceSeenSoFar = prices[0] var potentialSellingPrice = prices[0] var maxProfit = 0 for (day in prices.indices) { val priceToday = prices[day] if (priceToday > potentialSellingPrice) { potentialSellingPrice = priceToday maxProfit = maxOf((potentialSellingPrice - lowestPriceSeenSoFar), maxProfit) } else if (priceToday < lowestPriceSeenSoFar) { lowestPriceSeenSoFar = priceToday potentialSellingPrice = priceToday } } return maxProfit }
0
Kotlin
0
0
87aa60c2bf5f6a672de5a9e6800452321172b289
1,582
grind-75
Apache License 2.0
src/Day23.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
import kotlin.math.max typealias Grid = MutableInput<Char> fun main() { fun Grid.next(curr: RowCol): List<RowCol> { return when (this.get(curr)) { '>' -> listOf(curr.right()) '<' -> listOf(curr.left()) '^' -> listOf(curr.up()) 'v' -> listOf(curr.down()) else -> this.adjacent(curr).filter { this.get(it) != '#' } } } fun Grid.next2(curr: RowCol, prev: RowCol? = null): List<RowCol> { when (this.get(curr)) { '>' -> if (prev != null && prev != curr.right()) return listOf(curr.right()) '<' -> if (prev != null && prev != curr.left()) return listOf(curr.left()) '^' -> if (prev != null && prev != curr.up()) return listOf(curr.up()) 'v' -> if (prev != null && prev != curr.down()) return listOf(curr.down()) } return this.adjacent(curr).filter { this.get(it) != '#' } } // For debugging fun Grid.print(visited: MutableSet<RowCol>) { for (i in this.indices) { this[i].mapIndexed { j, c -> if (visited.contains(i to j)) 'O' else this.get(i to j) }.joinToString("").println() } println(visited.size) } fun part1(input: List<String>): Int { val grid = input.toMutableInput { it } val start = 0 to 1 val end = grid.size - 1 to grid[0].size - 2 var maxPath = 0 fun Grid.hike(curr: RowCol, visited: MutableSet<RowCol>, steps: Int) { if (curr == end) { maxPath = max(maxPath, steps) // this.print(visited) return } val next = this.next(curr).filterNot { visited.contains(it) } if (next.isEmpty()) return for (n in next) { visited.add(n) this.hike(n, visited, steps + 1) visited.remove(n) } } grid.set(start, 'O') grid.hike(start, mutableSetOf(start), 0) return maxPath } fun part2(input: List<String>): Int { val grid = input.toMutableInput { it } val start = 0 to 1 val end = grid.size - 1 to grid[0].size - 2 var maxPath = 0 fun Grid.hike(curr: RowCol, visited: MutableSet<RowCol>, steps: Int, prev:RowCol?=null) { if (curr == end) { maxPath = max(maxPath, steps) // I'm not going to let this run forever.. // Just start entering the current observed max every 5(?) mins.. println("$maxPath : $steps") return } val next = this.next2(curr, prev).filterNot { visited.contains(it) } if (next.isEmpty()) return for (n in next) { visited.add(n) this.hike(n, visited, steps + 1, curr) visited.remove(n) } } grid.set(start, 'O') grid.hike(start, mutableSetOf(start), 0, null) return maxPath } val input = readInput("Day23") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
3,167
aoc-2023
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2022/Day11.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2022 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.mul import com.s13g.aoc.resultFrom /** * --- Day 11: Monkey in the Middle --- * https://adventofcode.com/2022/day/11 */ class Day11 : Solver { override fun solve(lines: List<String>): Result { return resultFrom( solveFor(parse(lines), false), solveFor(parse(lines), true) ) } private fun solveFor(monkeys: List<Monkey>, partB: Boolean): Long { val monkeyDivs = monkeys.map { it.divBy }.toList() for (i in 1..if (partB) 10_000 else 20) { for (monkey in monkeys) { for (item in monkey.items.toList()) { var worry = if (monkey.op.operator == "*") item * monkey.opNumOr(item) else item + monkey.opNumOr(item) monkey.numInspections++ worry = if (partB) worry % monkeyDivs.mul() else worry / 3 // Throw to other monkey. monkeys[if (worry % monkey.divBy == 0L) monkey.decisionMonkeys.first else monkey.decisionMonkeys.second].items.add(worry) } monkey.items.clear() } } return monkeys.map { it.numInspections } .sortedDescending().subList(0, 2).mul() } private fun parse(lines: List<String>): List<Monkey> { val result = mutableListOf<Monkey>() for ((id, mLines) in lines.windowed(6, 7).withIndex()) { val oSplit = mLines[2].substring(23).split(" ") val oNum = if (oSplit[1] == "old") Long.MAX_VALUE else oSplit[1].toLong() result.add( Monkey( id, mLines[1].substring(18).split(", ").map { it.toLong() } .toMutableList(), Op(oSplit[0], oNum), mLines[3].substring(21).toLong(), Pair(mLines[4].substring(29).toInt(), mLines[5].substring(30).toInt()) ) ) } return result } data class Monkey( val id: Int, var items: MutableList<Long>, val op: Op, val divBy: Long, val decisionMonkeys: Pair<Int, Int>, var numInspections: Long = 0 ) { fun opNumOr(other: Long) = op.num.takeIf { it != Long.MAX_VALUE } ?: other } data class Op(val operator: String, val num: Long) }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,179
euler
Apache License 2.0
src/Day04.kt
NatoNathan
572,672,396
false
{"Kotlin": 6460}
typealias AssignmentsPair = Pair<IntRange, IntRange> fun getPair(input:String): AssignmentsPair { val (one, two) = input.split(",").map { getAssignments(it) } return Pair(one, two) } fun getAssignments(input:String): IntRange { val (lower, upper) = input.split('-').map { it.toInt() } return lower..upper } fun doesFullyOverlap(pair: AssignmentsPair): Boolean { val (first,second ) = pair val firstOverlaps = (first.first <= second.first && second.last <= first.last ) val secondOverlaps = (second.first <= first.first && first.last <= second.last) return firstOverlaps || secondOverlaps } fun doesOverlap(pair: AssignmentsPair): Boolean = pair.first.any { pair.second.contains(it) } fun main() { val day = "Day04" val testOutputPart1 = 2 fun part1(input: List<String>): Int = input.map { getPair(it) }.count { doesFullyOverlap(it) } val testOutputPart2 = 4 fun part2(input: List<String>): Int = input.map { getPair(it) }.count { doesOverlap(it) } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") check(part1(testInput) == testOutputPart1) check(part2(testInput) == testOutputPart2) val input = readInput(day) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c0c9e2a2d0ca2503afe33684a3fbba1f9eefb2b0
1,308
advent-of-code-kt
Apache License 2.0
src/main/kotlin/oct_challenge2021/wordSearchII/WordSearchII.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package oct_challenge2021.wordSearchII fun main() { val matrix = arrayOf( charArrayOf('o', 'a', 'a', 'n'), charArrayOf('e', 't', 'a', 'e'), charArrayOf('i', 'h', 'k', 'r'), charArrayOf('i', 'f', 'l', 'v'), ) val words = arrayOf("oath", "pea", "eat", "rain") val result = WordSearchII().findWords(matrix, words) println(result) // expected "oath", "eat" } class WordSearchII { private val hashResult = hashSetOf<String>() private lateinit var board: Array<CharArray> private val trie = Trie() fun findWords(board: Array<CharArray>, words: Array<String>): List<String> { this.board = board for (word in words) trie.insert(word) for (i in board.indices) { for (j in board[0].indices) { traverse(i, j, "") } } return hashResult.toList() } private fun traverse(i: Int, j: Int, prev: String) { if (i < 0 || i >= board.size || j < 0 || j >= board[0].size || board[i][j] == '#') return val current = prev + board[i][j] if (!trie.startsWith(current)) return if (trie.search(current)) hashResult.add(current) val temp = board[i][j] board[i][j] = '#' traverse(i + 1, j, current) traverse(i, j + 1, current) traverse(i - 1, j, current) traverse(i, j - 1, current) board[i][j] = temp } } private class Trie { private val root: TrieNode? = TrieNode() fun insert(word: String) { var node = root for (currChar in word) { if (!node!!.containsKey(currChar)) { node.put(currChar, TrieNode()) } node = node.get(currChar) } node!!.isEnd = true } fun search(word: String): Boolean { val node = searchPrefix(word) return node != null && node.isEnd } fun startsWith(prefix: String): Boolean { val node = searchPrefix(prefix) return node != null } private fun searchPrefix(word: String): TrieNode? { var node = root for (currChar in word) { if (node!!.containsKey(currChar)) { node = node.get(currChar) } else { return null } } return node } } private class TrieNode { private val numberOfAlphabet = 26 private var links: Array<TrieNode?> = arrayOfNulls(numberOfAlphabet) var isEnd = false fun containsKey(char: Char): Boolean { return links[char - 'a'] != null } fun get(char: Char): TrieNode? { return links[char - 'a'] } fun put(char: Char, node: TrieNode) { links[char - 'a'] = node } }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
2,740
leetcode-kotlin
MIT License
src/Day07.kt
allisonjoycarter
574,207,005
false
{"Kotlin": 22303}
fun main() { class File(val name: String, val size: Int) class Directory(val name: String) { var parent: Directory? = null val directories: MutableList<Directory> = mutableListOf() val files: MutableList<File> = mutableListOf() val size: Int get() = files.sumOf { it.size } + directories.sumOf { it.size } fun getAllDirectories(dirs: List<Directory>): List<Directory> { if (directories.isEmpty()) { return (dirs + listOf(this)).distinctBy { it.name } } return (directories + directories.flatMap { it.getAllDirectories(it.directories) }).distinctBy { it.name } } val root: Directory get() { if (parent == null) { return this } return parent!!.root } fun addDirectory(child: Directory): Directory { child.parent = this directories.add(child) return child } fun addFile(file: File) { files.add(file) } fun setFile(name: String, value: Int) { val index = files.indexOfFirst { it.name == name } if (index != -1) { files[index] = File(name, value) } else { directories.forEach { it.setFile(name, value) } } } fun containsDir(key: String): Boolean { if (directories.isEmpty()) { return key == name } return directories.any { it.containsDir(key) } } fun containsFile(key: String): Boolean { if (directories.isEmpty()) { return files.any { it.name == key } } return directories.any { files.any { file -> file.name == key } || it.containsFile(key) } } fun findChild(key: String): Directory? { if (directories.any { it.name == key }) { return directories.firstOrNull { it.name == key } } return directories.firstOrNull { it.findChild(key) != null } } override fun toString(): String { return printTree(0) } private fun printTree(level: Int): String { val indent = (0..level).joinToString("") {" "} var result = "$indent-> $name (dir)" directories.forEach { result += "\n" + it.printTree(level + 1) } if (files.isNotEmpty()) { result += " $indent${files.joinToString("") { "\n $indent-> ${it.name} = ${it.size}" }}" } return result } } fun part1(input: List<String>): Int { var location = Directory("/") var lineIndex = 0 while (lineIndex < input.size) { println("$lineIndex: processing " + input[lineIndex]) val pieces = input[lineIndex].split(" ") if (input[lineIndex].startsWith("$")) { when (pieces[1]) { "cd" -> { val argument = pieces[2] location = if (argument == "..") { location.parent ?: location.root } else { if (argument == "/") { location.root } else if (!location.containsDir(argument)) { location.addDirectory(Directory(argument)) } else { location.findChild(argument) ?: location.root } } } "ls" -> { lineIndex++ val sublist = input.subList(lineIndex, input.size) var endIndex = sublist.indexOfFirst { it.startsWith("$") } if (endIndex == - 1) { endIndex = sublist.size } for (i in 0 until endIndex) { println("${lineIndex + i}: adding to file structure: ${sublist[i]}") val (dirOrSize, name) = sublist[i].split(" ") if (dirOrSize == "dir") { if (!location.root.containsDir(name)) { println("adding directory $name to ${location.name}") location.addDirectory(Directory(name)) } else { println("using directory $name") location.findChild(name) } } else if (!location.containsFile(name)) { println("adding file $name to ${location.name}") location.addFile(File(name, dirOrSize.toInt())) } else { println("updating file $name within ${location.name}") location.setFile(name, dirOrSize.toInt()) } } lineIndex += endIndex - 1 } } } lineIndex++ } println("---------- Current Tree --------------") println(location.root.toString()) val max = 100000 val countedDirs = location.root.getAllDirectories(emptyList()).filter { println("directory ${it.name} = ${it.size}") it.size <= max }.distinctBy { it.name } println("result = ${countedDirs.sumOf { it.size }}") println(location.root.getAllDirectories(emptyList()).joinToString { it.name }) return countedDirs.sumOf { it.size } } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) // check(part2(testInput) == 19) val input = readInput("Day07") println("Part 1:") println(part1(input)) // println("Part 2:") // println(part2(input)) }
0
Kotlin
0
0
86306ee6f4e90c1cab7c2743eb437fa86d4238e5
6,325
adventofcode2022
Apache License 2.0
advent-of-code-2023/src/test/kotlin/Day3Test.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test /** [Day 3: Gear Ratios](https://adventofcode.com/2023/day/3) */ class Day3Test { data class EnginePart( private val start: Point, val value: Char, val strings: List<String>, ) { val numbers: List<Int> get() = strings.map { it.toInt() } } private val testInput = """467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. """ .trimIndent() @Test fun `silver test (example)`() { val map = parseMap(testInput) val parts = findParts(map) parts.sumOf { label -> label.numbers.sum() } shouldBe 4361 } @Test fun `silver test`() { val map = parseMap(loadResource("Day3")) val parts = findParts(map) parts.sumOf { label -> label.numbers.sum() } shouldBe 544433 } @Test fun `gold test (example)`() { val map = parseMap(testInput) val parts = findParts(map) parts .filter { it.value == '*' && it.numbers.size == 2 } .sumOf { it.numbers.first() * it.numbers.last() } .shouldBe(467835) } @Test fun `gold test`() { val map = parseMap(loadResource("Day3")) val parts = findParts(map) parts .filter { it.value == '*' && it.numbers.size == 2 } .sumOf { it.numbers.first() * it.numbers.last() } .shouldBe(76314915) } private fun findParts(map: Map<Point, Char>): List<EnginePart> { val special: Map<Point, Char> = map.filter { (key, value) -> value != '.' && !value.isDigit() } val engineParts = special.map { (key, value) -> val starts: List<Point> = key.surroundings() .mapNotNull { surroundingPoint -> generateSequence(surroundingPoint) { it.left() } .takeWhile { map[it]?.isDigit() == true } .lastOrNull() } .distinct() val labels = starts.map { start -> generateSequence(start) { it.right() } .takeWhile { map[it]?.isDigit() == true } .joinToString("") { "${map.getValue(it)}" } } EnginePart(key, value, labels) } return engineParts } private fun Point.surroundings(): List<Point> { return listOf( up(), down(), left(), right(), up().left(), up().right(), down().left(), down().right()) } }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
2,483
advent-of-code
MIT License
aoc-2023/src/main/kotlin/aoc/aoc13.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.CharGrid import aoc.util.getDayInput val testInput = """ #.##..##. ..#.##.#. ##......# ##......# ..#.##.#. ..##..##. #.#.##.#. #...##..# #....#..# ..##..### #####.##. #####.##. ..##..### #....#..# """.parselines fun List<String>.parse(): List<CharGrid> = joinToString("\n").split("\n\n") .map { it.split("\n") } fun CharGrid.reflectionHorizontal(smudge: Boolean): Int { for (x in 1..size-1) { val list1 = take(x) val list2 = takeLast(size-x) val size = minOf(list1.size, list2.size) if (equal(list1.takeLast(size), list2.take(size).reversed(), smudge)) { return x } } return 0 } fun equal(list1: List<String>, list2: List<String>, smudge: Boolean): Boolean { return if (!smudge) { list1 == list2 } else { list1.joinToString("\n").zip(list2.joinToString("\n")) .count { it.first != it.second } == 1 } } fun CharGrid.reflectionVertical(smudge: Boolean): Int { val grid = map { it.toList() } val gridTransposed = grid[0].indices.map { grid.map { row -> row[it] }.joinToString("") } return gridTransposed.reflectionHorizontal(smudge) } // part 1 fun List<String>.part1(): Int = parse().sumOf { val rv = it.reflectionVertical(smudge = false) val rh = it.reflectionHorizontal(smudge = false) println(it.joinToString("\n")) println("col=$rv, row=$rh") println("-".repeat(30)) rv + 100*rh } // part 2 fun List<String>.part2(): Int = parse().sumOf { val rv = it.reflectionVertical(smudge = true) val rh = it.reflectionHorizontal(smudge = true) println(it.joinToString("\n")) println("col=$rv, row=$rh") println("-".repeat(30)) rv + 100*rh } // calculate answers val day = 13 val input = getDayInput(day, 2023) val testResult = testInput.part1() val testResult2 = testInput.part2() val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
2,162
advent-of-code
Apache License 2.0
kotlin/1930-unique-length-3-palindromic-subsequences.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}
/* * Time complexity 0(N * 26) ~ O(N) * * Space complexity O(26 + 26 + 26*26) or 0(A^2) where A is the alphabet which technically is O(1) */ class Solution { fun countPalindromicSubsequence(s: String): Int { val left = HashSet<Char>() val right = IntArray(26) var res = HashSet<Pair<Char, Char>>() // inner to outer pair, where they form the palindrome outer-inner-outer for(c in s) right[c - 'a']++ for(i in s.indices) { if(right[s[i] - 'a'] > 0 ) right[s[i] - 'a']-- for(j in 0 until 26) { val c = 'a'.plus(j) if(c in left && right[c - 'a'] > 0) { res.add(s[i] to c) } } left.add(s[i]) } return res.size } } /* * Time complexity 0(26*N+N*M) where M is the length of the substring between first and last character ~O(N*M) * I see many posts claiming O(N) for the time complexity of this algorithm, but for Java/Kotlin, time complexity should be O(M*N) * since according to https://stackoverflow.com/questions/4679746/time-complexity-of-javas-substring , substring() time complexity is Linear. * * Space complexity O(2*26) ~O(1) */ class Solution { fun countPalindromicSubsequence(s: String): Int { val first = IntArray(26) {Integer.MAX_VALUE} val second = IntArray(26) var res = 0 for(i in s.indices) { first[s[i] - 'a'] = minOf(first[s[i] - 'a'], i) second[s[i] - 'a'] = i } for(i in 0 until 26) { if(first[i] < second[i]) res += s.substring(first[i]+1, second[i]).toCharArray().distinct().count() } return res } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,732
leetcode
MIT License
src/day23/Day23.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day23 import readInput fun Pair<Int, Int>.surrounding() = listOf( first to second + 1, first to second - 1, first + 1 to second, first + 1 to second + 1, first + 1 to second - 1, first - 1 to second, first - 1 to second + 1, first - 1 to second - 1, ) fun Pair<Int, Int>.north() = listOf( first - 1 to second, first - 1 to second + 1, first - 1 to second - 1, ) fun Pair<Int, Int>.south() = listOf( first + 1 to second, first + 1 to second + 1, first + 1 to second - 1, ) fun Pair<Int, Int>.west() = listOf( first to second - 1, first + 1 to second - 1, first - 1 to second - 1, ) fun Pair<Int, Int>.east() = listOf( first to second + 1, first + 1 to second + 1, first - 1 to second + 1, ) fun Pair<Int, Int>.toCheckOrder(round: Int): List<Pair<List<Pair<Int, Int>>, Pair<Int, Int>>> { val check = mutableListOf( north() to Pair(first - 1, second), south() to Pair(first + 1, second), west() to Pair(first, second - 1), east() to Pair(first, second + 1), ) repeat(round % 4) { check.add(check.removeFirst()) } check.add(0, surrounding() to this) check.add(listOf<Pair<Int, Int>>() to this) return check } fun main() { fun simulate(input: Set<Pair<Int, Int>>, round: Int): Pair<Set<Pair<Int, Int>>, Boolean> { val moves = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() val count = mutableMapOf<Pair<Int, Int>, Int>() input.forEach { elf -> val check = elf.toCheckOrder(round) for ((toCheck, target) in check) { if (toCheck.all { !input.contains(it) }) { moves[elf] = target count[target] = (count[target] ?: 0) + 1 break } } } var changed = false val positions = mutableSetOf<Pair<Int, Int>>() moves.forEach { (source, target) -> if ((count[target] ?: 0) >= 2) { positions.add(source) } else { positions.add(target) if (source != target) { changed = true } } } return positions to changed } fun part1(input: Set<Pair<Int, Int>>): Int { var positions = input repeat(10) { positions = simulate(positions, it).first } val sizeX = positions.maxOf { it.first } - positions.minOf { it.first } + 1 val sizeY = positions.maxOf { it.second } - positions.minOf { it.second } + 1 return sizeX * sizeY - positions.size } fun part2(input: Set<Pair<Int, Int>>): Int { var positions = input var round = 0 while (true) { val changed = simulate(positions, round).also { positions = it.first }.second round++ if (!changed) { return round } } } fun preprocess(input: List<String>): Set<Pair<Int, Int>> { val res = mutableSetOf<Pair<Int, Int>>() input.forEachIndexed { x, row -> row.forEachIndexed { y, c -> if (c == '#') { res.add(x to y) } } } return res } // test if implementation meets criteria from the description, like: val testInput = readInput(23, true) check(part1(preprocess(testInput)) == 110) val input = readInput(23) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 20) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
3,649
advent-of-code-2022
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day19.kt
jntakpe
572,853,785
false
{"Kotlin": 72329, "Rust": 15876}
package com.github.jntakpe.aoc2022.days import com.github.jntakpe.aoc2022.days.Day19.Resource.* import com.github.jntakpe.aoc2022.shared.Day import com.github.jntakpe.aoc2022.shared.readInputLines import java.util.* object Day19 : Day { override val input = readInputLines(19).map { Blueprint.from(it) } override fun part1() = input.sumOf { dfs(it, 24) * it.index } override fun part2() = if (isTest()) TODO("Understand why it takes so long") else input.take(3).map { dfs(it, 32) }.reduce(Int::times) private fun dfs(blueprint: Blueprint, time: Int): Int { var result = 0 val initialState = State(Resources(), Resources(ore = 1), time) val queue = LinkedList<State>() queue.add(initialState) val cache = mutableSetOf<State>() while (queue.isNotEmpty()) { var state = queue.poll() val remainingTime = state.time - 1 result = maxOf(result, state.resources.geode) if (state.time == 0) continue val bots = state.robots.copy( ore = minOf(state.robots.ore, blueprint.recipes.maxSpend.ore), clay = minOf(state.robots.clay, blueprint.recipes.maxSpend.clay), obsidian = minOf(state.robots.obsidian, blueprint.recipes.maxSpend.obsidian) ) val res = state.resources.copy( ore = minOf( state.resources.ore, blueprint.recipes.maxSpend.ore * state.time - bots.ore * remainingTime ), clay = minOf( state.resources.clay, blueprint.recipes.obsidian.cost.clay * state.time - bots.clay * remainingTime ), obsidian = minOf( state.resources.obsidian, blueprint.recipes.geode.cost.obsidian * state.time - bots.obsidian * remainingTime ) ) state = State(res, bots, state.time) if (state in cache) continue cache += state val allResources = res + bots queue.add(State(allResources, bots, remainingTime)) val nextSteps = blueprint.recipes.asList .filter { res >= it.cost } .map { State(allResources - it.cost, bots + it.gain, remainingTime) } queue.addAll(nextSteps) } return result } //TODO understand why it so slow with test data private fun isTest() = input.size <= 2 data class State(val resources: Resources, val robots: Resources, val time: Int) data class Blueprint(val index: Int, val recipes: Recipes) { companion object { fun from(input: String): Blueprint { return Blueprint( index(input), recipes(input) ) } private fun index(input: String) = input.lines().first().substringAfter(' ').substringBefore(':').toInt() private fun recipes(input: String): Recipes { return input.split('.') .filter { it.isNotEmpty() } .associate { resource(it) to costs(it) } .let { Recipes( Recipe(it.getValue(ORE), Resources(ore = 1)), Recipe(it.getValue(CLAY), Resources(clay = 1)), Recipe(it.getValue(OBSIDIAN), Resources(obsidian = 1)), Recipe(it.getValue(GEODE), Resources(geode = 1)), ) } } private fun resource(input: String): Resource { return Resource.valueOf(input.substringAfter("Each").substringBefore("robot").trim().uppercase()) } private fun costs(input: String): Resources { return input.substringAfter("costs") .substringBefore('.') .split("and") .associate { val (cost, resource) = it.trim().split(' ') Resource.valueOf(resource.uppercase()) to cost.toInt() }.let { Resources(it[ORE] ?: 0, it[CLAY] ?: 0, it[OBSIDIAN] ?: 0, it[GEODE] ?: 0) } } } } enum class Resource { ORE, CLAY, OBSIDIAN, GEODE } data class Recipe(val cost: Resources, val gain: Resources) data class Recipes(val ore: Recipe, val clay: Recipe, val obsidian: Recipe, val geode: Recipe) { val asList = listOf(ore, clay, obsidian, geode) val maxSpend = asList .map { it.cost } .run { Resources(maxOf { it.ore }, maxOf { it.clay }, maxOf { it.obsidian }, maxOf { it.geode }) } } data class Resources( val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0 ) : Comparable<Resources> { private val asList = listOf(ore, clay, obsidian, geode) operator fun plus(other: Resources): Resources { return Resources(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode) } operator fun minus(other: Resources): Resources { return Resources(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode) } override fun compareTo(other: Resources): Int { val zip = asList.zip(other.asList) return when { zip.any { (a, b) -> a < b } -> -1 zip.all { (a, b) -> a == b } -> 0 else -> 1 } } } }
1
Kotlin
0
0
63f48d4790f17104311b3873f321368934060e06
5,726
aoc2022
MIT License
src/Day09.kt
rbraeunlich
573,282,138
false
{"Kotlin": 63724}
fun main() { fun parseMoves(input: List<String>): List<HeadMove> { return input.map { val split = it.split(" ") HeadMove(Direction.valueOf(split[0]), split[1].toInt()) } } fun part1(input: List<String>): Int { val moves = parseMoves(input) val head = BridgeHead(0 to 0) val tail = BridgeTail(0 to 0, mutableSetOf(0 to 0)) moves.forEach { move -> for (i in 0 until move.steps) { head.applyMove(move.direction) tail.followHead(head.currentPosition) } } return tail.visitedPositions.size } fun part2(input: List<String>): Int { val moves = parseMoves(input) val head = BridgeHead(0 to 0) val knots = (1 until 9).map { BridgeTail(0 to 0, mutableSetOf(0 to 0)) } val tail = BridgeTail(0 to 0, mutableSetOf(0 to 0)) moves.forEach { move -> for (i in 0 until move.steps) { head.applyMove(move.direction) knots.first().followHead(head.currentPosition) knots.forEachIndexed { index, knot -> if(index != 0) { knots[index].followHead(knots[index - 1].currentPosition) } } tail.followHead(knots.last().currentPosition) } } return tail.visitedPositions.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) } data class BridgeHead(var currentPosition: Pair<Int, Int>) { fun applyMove(direction: Direction) { currentPosition = when (direction) { Direction.R -> (currentPosition.first + 1) to currentPosition.second Direction.L -> (currentPosition.first - 1) to currentPosition.second Direction.U -> currentPosition.first to (currentPosition.second + 1) Direction.D -> currentPosition.first to (currentPosition.second - 1) } } } data class BridgeTail(var currentPosition: Pair<Int, Int>, val visitedPositions: MutableSet<Pair<Int, Int>>) { fun followHead(headPosition: Pair<Int, Int>) { if (isAdjacentToHead(headPosition)) { // do nothing } else { // same row if (currentPosition.first == headPosition.first) { // update y val moveUp = headPosition.second > currentPosition.second if (moveUp) { currentPosition = currentPosition.first to (currentPosition.second + 1) } else { currentPosition = currentPosition.first to (currentPosition.second - 1) } } // same column else if (currentPosition.second == headPosition.second) { // update x val moveRight = headPosition.first > currentPosition.first if (moveRight) { currentPosition = (currentPosition.first + 1) to (currentPosition.second) } else { currentPosition = (currentPosition.first - 1) to (currentPosition.second) } } else { // diagonally different val moveUp = headPosition.second > currentPosition.second if (moveUp) { currentPosition = currentPosition.first to (currentPosition.second + 1) } else { currentPosition = currentPosition.first to (currentPosition.second - 1) } val moveRight = headPosition.first > currentPosition.first if (moveRight) { currentPosition = (currentPosition.first + 1) to (currentPosition.second) } else { currentPosition = (currentPosition.first - 1) to (currentPosition.second) } } visitedPositions.add(currentPosition) } } private fun isAdjacentToHead(headPosition: Pair<Int, Int>): Boolean { val isCovered = headPosition == currentPosition val topLeft = (currentPosition.first - 1) to (currentPosition.second + 1) val top = currentPosition.first to (currentPosition.second + 1) val topRight = (currentPosition.first + 1) to (currentPosition.second + 1) val left = (currentPosition.first - 1) to currentPosition.second val right = (currentPosition.first + 1) to currentPosition.second val bottomLeft = (currentPosition.first - 1) to (currentPosition.second - 1) val bottom = currentPosition.first to (currentPosition.second - 1) val bottomRight = (currentPosition.first + 1) to (currentPosition.second - 1) return isCovered || setOf(topLeft, top, topRight, left, right, bottomLeft, bottom, bottomRight).contains( headPosition ) } } data class HeadMove(val direction: Direction, val steps: Int) enum class Direction { R, L, U, D }
0
Kotlin
0
1
3c7e46ddfb933281be34e58933b84870c6607acd
5,287
advent-of-code-2022
Apache License 2.0
day16/src/main/kotlin/de/havox_design/aoc2023/day16/Day16.kt
Gentleman1983
715,778,541
false
{"Kotlin": 163912, "Python": 1048}
package de.havox_design.aoc2023.day16 import de.havox_design.aoc2023.day10.Direction class Day16(private var filename: String) { fun solvePart1(): Long = getEnergy(parseTiles(getResourceAsText(filename)), Direction.EAST, Pair(0, 0)) .toLong() fun solvePart2(): Long { val input = getResourceAsText(filename) val startPoints = input .flatMapIndexed { row, s -> s .withIndex() .filter { row == 0 || row == input.size - 1 || it.index == 0 || it.index == s.length - 1 } .map { iv -> Pair(row, iv.index) } } val maxRow = startPoints .maxOf { it.first } val maxColumn = startPoints .maxOf { it.second } val results = startPoints .flatMap { when { it.first == 0 && it.second == 0 -> { listOf( Pair(it, getEnergy(parseTiles(input), Direction.EAST, it)), Pair(it, getEnergy(parseTiles(input), Direction.SOUTH, it)) ) } it.first == maxRow && it.second == maxColumn -> { listOf( Pair(it, getEnergy(parseTiles(input), Direction.WEST, it)), Pair(it, getEnergy(parseTiles(input), Direction.NORTH, it)) ) } it.first == 0 -> { listOf(Pair(it, getEnergy(parseTiles(input), Direction.SOUTH, it))) } it.second == 0 -> { listOf(Pair(it, getEnergy(parseTiles(input), Direction.EAST, it))) } it.first == maxRow -> { listOf(Pair(it, getEnergy(parseTiles(input), Direction.NORTH, it))) } it.second == maxColumn -> { listOf(Pair(it, getEnergy(parseTiles(input), Direction.WEST, it))) } else -> { emptyList() } } } return results .maxOf { it.second } .toLong() } private fun getEnergy(contraption: List<List<Tile>>, enteredDirection: Direction, startPoint: Pair<Int, Int>): Int { traceBeam(contraption, enteredDirection, contraption[startPoint.first][startPoint.second]) return contraption .flatten() .count { it.isEnergized() } } private fun traceBeam(contraption: List<List<Tile>>, enteredDirection: Direction, startTile: Tile) { val nextDirections = startTile .getNextDirections(enteredDirection) val nextLocations = nextDirections .map { nextLocation(startTile.row, startTile.column, it) } for (location in nextLocations.withIndex()) { when { ( location.value.first !in contraption.indices || location.value.second !in contraption[startTile.row].indices || nextDirections[location.index] == Direction.NONE ) -> continue } traceBeam( contraption, nextDirections[location.index], contraption[location.value.first][location.value.second] ) } } private fun nextLocation(row: Int, column: Int, direction: Direction): Pair<Int, Int> { return when (direction) { Direction.NORTH -> Pair(row - 1, column) Direction.SOUTH -> Pair(row + 1, column) Direction.EAST -> Pair(row, column + 1) Direction.WEST -> Pair(row, column - 1) else -> Pair(row, column) } } private fun parseTiles(input: List<String>) = input.mapIndexed { row, line -> line.mapIndexed { column, c -> Tile(row, column, c) } } private fun getResourceAsText(path: String): List<String> = this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines() }
1
Kotlin
0
0
eac8ff77420f061f5cef0fd4b8d05e7805c4cc5a
4,396
aoc2023
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem45/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem45 /** * LeetCode page: [45. Jump Game II](https://leetcode.com/problems/jump-game-ii/); */ class Solution2 { /* Algorithm: (By Dynamic Programming) * 1. SubProblem: * let X(i) be the minimum jumps if start at index i. Use array Dp to store the result * of each sub problem, i.e. Dp[i] = X(i); * 2. Relation: * X(i) = 1 + min { Dp[k] | k = i+1, i+2, .., i+nums[i] } for i = 0, 1, .., nums.lastIndex - 1; * 3. Topological Order: * Solve X(i) from last to first index; * 4. Base case: * X(nums.lastIndex) = 0 * 5. Original Problem: * X(0) * 6. Time complexity: * There are |nums| sub problems, each has complexity O(K) where K is the maximum possible jump length, * thus O(|nums| * K); */ /* Complexity: * Time O(|nums| * K) and Space O(|nums|) where K is the maximum possible jump length; */ fun jump(nums: IntArray): Int { val dp = IntArray(nums.size) val valueWhenCannotReach = nums.size // Special value if the last index can not be reached for (i in dp.lastIndex - 1 downTo 0) { val jumpLength = nums[i] if (jumpLength == 0) { dp[i] = valueWhenCannotReach continue } val furthest = (i + jumpLength).coerceAtMost(nums.lastIndex) val subResult = 1 + dp.min(i + 1..furthest) dp[i] = subResult } check(dp[0] < nums.size) { "Cannot reach last index although is guaranteed in the problem statement." } return dp[0] } private fun IntArray.min(indexRange: IntRange): Int { var min = this[indexRange.first] for (index in indexRange) { if (this[index] < min) { min = this[index] } } return min } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,913
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2023/day24/HailstoneMap.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day24 import com.github.michaelbull.advent2023.iteration.combinationPairs fun Sequence<String>.toHailstoneMap(): HailstoneMap { return HailstoneMap(map(String::toHailstone).toList()) } data class HailstoneMap( val hailstones: List<Hailstone>, ) { fun intersections(range: ClosedFloatingPointRange<Double>): Int { return hailstones.combinationPairs().count { it in range } } private operator fun ClosedFloatingPointRange<Double>.contains(pair: Pair<Hailstone, Hailstone>): Boolean { val (a, b) = pair val slopeDelta = b.slope - a.slope return if (slopeDelta == 0.0) { false } else { val cx = ((((b.slope * b.px) - (a.slope * a.px)) + a.py) - b.py) / slopeDelta val cy = (a.slope * (cx - a.px)) + a.py if (cx in this && cy in this) { a.isValid(cx, cy) && b.isValid(cx, cy) } else { false } } } private fun Hailstone.isValid(cx: Double, cy: Double): Boolean { val belowX = vx < 0 && px < cx val aboveX = vx > 0 && px > cx val belowY = vy < 0 && py < cy val aboveY = vy > 0 && py > cy return !(belowX || aboveX || belowY || aboveY) } }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
1,327
advent-2023
ISC License
src/main/kotlin/com/dmc/advent2022/Day09.kt
dorienmc
576,916,728
false
{"Kotlin": 86239}
package com.dmc.advent2022 import kotlin.math.absoluteValue import kotlin.math.sign //--- Day 9: Rope Bridge --- class Day09 : Day<Int> { override val index = 9 override fun part1(input: List<String>): Int { var head = Point() var tail = Point() val tailPositions = mutableSetOf(Point()) for (line in input) { val (direction, num) = line.split(" ") // Move head and tail repeat(num.toInt()) { head = head.move(direction) if (!head.touches(tail)) { tail = tail.moveTowards(head) } tailPositions += tail } } return tailPositions.size } override fun part2(input: List<String>): Int { val rope = (0..9).map{ Point()}.toMutableList() val tailPositions = mutableListOf(rope.last()) for (line in input) { val (direction, num) = line.split(" ") // Move head, knots and tail repeat(num.toInt()) { // Move head rope[0] = rope[0].move(direction) // Move the rest rope.indices.windowed(2){ (prev, current) -> val prevKnot = rope.get(prev) var knot = rope.get(current) if (!knot.touches(prevKnot)) { knot = knot.moveTowards(prevKnot) } check(knot.touches(prevKnot)) rope[current] = knot } // Store tail position tailPositions += rope.last() } } // println(tailPositions) return tailPositions.toSet().size } } data class Point(val x: Int = 0, val y: Int = 0) { // y | // |___ // x fun move(direction: String): Point = when(direction) { "U" -> copy(y = y + 1) "D" -> copy(y = y - 1) "R" -> copy(x= x + 1) "L" -> copy(x = x - 1) else -> this } fun touches(other: Point): Boolean { // diagonally adjacent and even overlapping both count as touching val diffX = (x - other.x).absoluteValue val diffY = (y - other.y).absoluteValue return diffX <= 1 && diffY <= 1 } fun moveTowards(other: Point) : Point { return Point(x + (other.x - x).sign, y + (other.y - y).sign) } override fun toString(): String { return "($x, $y)" } } fun main() { val day = Day09() // test if implementation meets criteria from the description, like: val testInput = readInput(day.index, true) check(day.part1(testInput) == 13) val input = readInput(day.index) day.part1(input).println() val testInput2 = readInput("Day09_test2","src/test/resources") check(day.part2(testInput2) == 36) day.part2(input).println() }
0
Kotlin
0
0
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
2,951
aoc-2022-kotlin
Apache License 2.0
src/Day08.kt
li-xin-yi
573,617,763
false
{"Kotlin": 23422}
import java.util.* fun main() { fun parseInput(input: List<String>): List<List<Int>> { return input.map { line -> line.map { it - '0' } } } fun solvePart1(input: List<String>): Int { val grid = parseInput(input) val seen = mutableSetOf<Pair<Int, Int>>() var maxSoFar: Int for (i in grid.indices) { maxSoFar = -1 for (j in grid[i].indices) { if (grid[i][j] > maxSoFar) { seen.add((i to j)) maxSoFar = grid[i][j] } } maxSoFar = -1 for (j in grid[i].indices.reversed()) { if (grid[i][j] > maxSoFar) { seen.add((i to j)) maxSoFar = grid[i][j] } } } for (j in grid[0].indices) { maxSoFar = -1 for (i in grid.indices) { if (grid[i][j] > maxSoFar) { seen.add((i to j)) maxSoFar = grid[i][j] } } maxSoFar = -1 for (i in grid.indices.reversed()) { if (grid[i][j] > maxSoFar) { seen.add((i to j)) maxSoFar = grid[i][j] } } } return seen.size } fun solvePart2(input: List<String>): Int { val grid = parseInput(input) val score = Array(grid.size) { IntArray(grid[0].size) { 1 } } val stack = Stack<Int>() for (i in grid.indices) { stack.clear() for (j in grid[i].indices) { while (stack.isNotEmpty() && grid[i][stack.peek()] < grid[i][j]) { stack.pop() } score[i][j] *= j - (if (stack.isNotEmpty()) stack.peek() else 0) stack.push(j) } stack.clear() for (j in grid[i].indices.reversed()) { while (stack.isNotEmpty() && grid[i][stack.peek()] < grid[i][j]) { stack.pop() } score[i][j] *= (if (stack.isNotEmpty()) stack.peek() else grid[i].size - 1) - j stack.push(j) } } for (j in grid[0].indices) { stack.clear() for (i in grid.indices) { while (stack.isNotEmpty() && grid[stack.peek()][j] < grid[i][j]) { stack.pop() } score[i][j] *= i - (if (stack.isNotEmpty()) stack.peek() else 0) stack.push(i) } stack.clear() for (i in grid.indices.reversed()) { while (stack.isNotEmpty() && grid[stack.peek()][j] < grid[i][j]) { stack.pop() } score[i][j] *= (if (stack.isNotEmpty()) stack.peek() else grid.size - 1) - i stack.push(i) } } return score.maxOf { it.maxOrNull()!! } } val testInput = readInput("input/Day08_test") check(solvePart1(testInput) == 21) check(solvePart2(testInput) == 8) val input = readInput("input/Day08_input") println(solvePart1(input)) println(solvePart2(input)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
3,296
AoC-2022-kotlin
Apache License 2.0
string-similarity/src/commonMain/kotlin/com/aallam/similarity/Levenshtein.kt
aallam
597,692,521
false
null
package com.aallam.similarity import kotlin.math.min /** * The Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or * substitutions) required to change one string into the other. * * This implementation uses dynamic programming (Wagner–Fischer algorithm). * * [Levenshtein Distance](https://en.wikipedia.org/wiki/Levenshtein_distance) */ public class Levenshtein { /** * The Levenshtein distance, or edit distance, between two words is the minimum number of single-character edits * (insertions, deletions or substitutions) required to change one word into the other. * * It is always at least the difference of the sizes of the two strings. * It is at most the length of the longer string. * It is `0` if and only if the strings are equal. * * @param first first string to compare. * @param second second string to compare. * @param limit the maximum result to compute before stopping, terminating calculation early. * @return the computed Levenshtein distance. */ public fun distance(first: CharSequence, second: CharSequence, limit: Int = Int.MAX_VALUE): Int { if (first == second) return 0 if (first.isEmpty()) return second.length if (second.isEmpty()) return first.length // initial costs is the edit distance from an empty string, which corresponds to the characters to inserts. // the array size is : length + 1 (empty string) var cost = IntArray(first.length + 1) { it } var newCost = IntArray(first.length + 1) for (i in 1..second.length) { // calculate new costs from the previous row. // the first element of the new row is the edit distance (deletes) to match empty string newCost[0] = i var minCost = i // fill in the rest of the row for (j in 1..first.length) { // if it's the same char at the same position, no edit cost. val edit = if (first[j - 1] == second[i - 1]) 0 else 1 val replace = cost[j - 1] + edit val insert = cost[j] + 1 val delete = newCost[j - 1] + 1 newCost[j] = minOf(insert, delete, replace) minCost = min(minCost, newCost[j]) } if (minCost >= limit) return limit // flip references of current and previous row val swap = cost cost = newCost newCost = swap } return cost.last() } }
0
Kotlin
0
1
40cd4eb7543b776c283147e05d12bb840202b6f7
2,605
string-similarity-kotlin
MIT License
src/main/kotlin/com/kishor/kotlin/algo/problems/arrayandstrings/LengthOfLongestSubString.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.problems.arrayandstrings import kotlin.math.max fun main() { // lengthOfLongestSubstring("abcabcbb") println("${findLongestSubstringLength("abcabcbb")}") println("${longestSubstringLength("abcabcbb")}") } fun lengthOfLongestSubstring(s: String): Int { var count = 0 if (s.length == 0) return count val set = hashSetOf<Char>() var i = 0 var j = 0 while (i < s.length && j < s.length) { println("$i and $j") println(set.size) if (!set.contains(s[j])) { set.add(s[j++]) count = max(j - i, count) } else { set.remove(s[i++]) } } return count } fun findLongestSubstringLength(s: String) : Int { val n = s.length val map = hashMapOf<Char, Int>() var ans = 0 var i = 0 for (j in 0 until n) { if(map.contains(s[j])) { i = max(i, map[s[j]] as Int) } ans = max(ans, j - i + 1) map[s[j]] = j + 1 } return ans } fun longestSubstringLength(s: String): Int { val n = s.length val index = IntArray(128) {0} var ans = 0 var i = 0 for (j in s.indices) { i = Math.max(index[s[j].toInt()], i) ans = Math.max(ans, j - i + 1) index[s[j].toInt()] = j + 1 } return ans }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,334
DS_Algo_Kotlin
MIT License
src/main/kotlin/day04.kt
mgellert
572,594,052
false
{"Kotlin": 19842}
object CampCleanup : Solution { fun countFullyContainedAssignments(assignments: List<Pair<Assignment, Assignment>>): Int = count(assignments) { it.first.contains(it.second) || it.second.contains(it.first) } fun countOverlappedAssignments(assignments: List<Pair<Assignment, Assignment>>): Int = count(assignments) { it.first.overlaps(it.second) || it.second.overlaps(it.first) } fun readAssignments(): List<Pair<Assignment, Assignment>> = readInput("day04").readLines() .map { it.split("-", ",") } .flatten() .map { it.toInt() } .chunked(4) .map { Pair(Assignment(it[0], it[1]), Assignment(it[2], it[3])) } private fun count( assignments: List<Pair<Assignment, Assignment>>, function: (Pair<Assignment, Assignment>) -> Boolean ) = assignments.map { function(it) }.count { it } private fun Assignment.contains(other: Assignment): Boolean = this.first <= other.first && this.second >= other.second private fun Assignment.overlaps(other: Assignment): Boolean = (other.first <= this.first && this.first <= other.second) || (other.first <= this.second && this.second <= other.second) } typealias Assignment = Pair<Int, Int>
0
Kotlin
0
0
4224c762ad4961b28e47cd3db35e5bc73587a118
1,250
advent-of-code-2022-kotlin
The Unlicense
kotlin/src/katas/kotlin/hackerrank/MatrixLayerRotation.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.hackerrank import datsok.shouldEqual import org.junit.Test import java.util.* import kotlin.collections.ArrayList /** * https://www.hackerrank.com/challenges/matrix-rotation-algo */ fun main() { val scanner = Scanner(System.`in`) val i = generateSequence { scanner.nextLine() }.iterator() main({ i.next() }) } private fun main(readLine: () -> String, writeLine: (Any?) -> Unit = { println(it) }) { val (rows, columns, rotations) = readLine().trim().split(" ").map { it.toInt() } val matrix = Array(rows, { Array(columns, { 0 }) }) 0.until(rows).forEach { row -> matrix[row] = readLine().trim().split(" ").map { it.toInt() }.toTypedArray() } matrixRotation(matrix, rotations) matrix.forEach { row -> writeLine(row.joinToString(" ")) } } fun matrixRotation(matrix: Array<Array<Int>>, rotations: Int) { matrix.listClockwiseSwaps().forEach { swaps -> 0.until(rotations.rem(swaps.size + 1)).forEach { swaps.forEach { swap -> matrix.apply(swap) } } } } private fun Array<Array<Int>>.listClockwiseSwaps( fromColumn: Int = 0, toColumn: Int = first().size - 1, fromRow: Int = 0, toRow: Int = size - 1 ): List<List<Swap>> { val points = ArrayList<Point>() IntRange(fromColumn, toColumn - 1).forEach { points.add(Point(fromRow, it)) } IntRange(fromRow, toRow - 1).forEach { points.add(Point(it, toColumn)) } IntRange(fromColumn + 1, toColumn).reversed().forEach { points.add(Point(toRow, it)) } IntRange(fromRow + 1, toRow).reversed().forEach { points.add(Point(it, fromColumn)) } val swaps = points.windowed(2).map { Swap(it[0], it[1]) } return if (toColumn - fromColumn > 1 && toRow - fromRow > 1) { listOf(swaps) + listClockwiseSwaps(fromColumn + 1, toColumn - 1, fromRow + 1, toRow - 1) } else { listOf(swaps) } } private fun Array<Array<Int>>.toPrintableString() = this.indices.joinToString("\n") { row -> this[row].indices.joinToString(" ") { column -> this[row][column].toString() } } private operator fun Array<Array<Int>>.get(point: Point) = this[point.row][point.column] private operator fun Array<Array<Int>>.set(point: Point, value: Int) { this[point.row][point.column] = value } private fun Array<Array<Int>>.apply(swap: Swap) { val tmp = this[swap.p1] this[swap.p1] = this[swap.p2] this[swap.p2] = tmp } private data class Point(val row: Int, val column: Int) { override fun toString() = "[$row,$column]" } private data class Swap(val p1: Point, val p2: Point) { override fun toString() = "Swap($p1,$p2)" } class MatrixLayerRotationTests { @Test fun `2x2 array clockwise swaps`() { val array = arrayOf( arrayOf(1, 2), arrayOf(4, 3) ) array.listClockwiseSwaps() shouldEqual listOf( listOf( Swap(Point(0, 0), Point(0, 1)), Swap(Point(0, 1), Point(1, 1)), Swap(Point(1, 1), Point(1, 0)) ) ) matrixRotation(array, 1) array.toPrintableString() shouldEqual """ |2 3 |1 4 """.trimMargin() } @Test fun `2x2 array full cycle rotation`() { val array = arrayOf( arrayOf(1, 2), arrayOf(4, 3) ) matrixRotation(array, 5) array.toPrintableString() shouldEqual """ |2 3 |1 4 """.trimMargin() } @Test fun `4x4 array clockwise swaps`() { val array = arrayOf( arrayOf(1, 2, 3, 4), arrayOf(5, 6, 7, 8), arrayOf(9, 10, 11, 12), arrayOf(13, 14, 15, 16) ) array.listClockwiseSwaps() shouldEqual listOf( // swaps for outer layer listOf( Swap(Point(0, 0), Point(0, 1)), Swap(Point(0, 1), Point(0, 2)), Swap(Point(0, 2), Point(0, 3)), Swap(Point(0, 3), Point(1, 3)), Swap(Point(1, 3), Point(2, 3)), Swap(Point(2, 3), Point(3, 3)), Swap(Point(3, 3), Point(3, 2)), Swap(Point(3, 2), Point(3, 1)), Swap(Point(3, 1), Point(3, 0)), Swap(Point(3, 0), Point(2, 0)), Swap(Point(2, 0), Point(1, 0)) ), // swaps for inner layer listOf( Swap(Point(1, 1), Point(1, 2)), Swap(Point(1, 2), Point(2, 2)), Swap(Point(2, 2), Point(2, 1)) ) ) matrixRotation(array, 1) array.toPrintableString() shouldEqual """ |2 3 4 8 |1 7 11 12 |5 6 10 16 |9 13 14 15 """.trimMargin() } @Test fun `no rotations`() { """|2 2 0 |1 2 |4 3 """ shouldOutput """ |1 2 |4 3 """ } @Test fun `single rotation`() { """|2 2 1 |1 2 |4 3 """ shouldOutput """ |2 3 |1 4 """ } @Test fun `sample input 1`() { """|4 4 2 |1 2 3 4 |5 6 7 8 |9 10 11 12 |13 14 15 16 """ shouldOutput """ |3 4 8 12 |2 11 10 16 |1 7 6 15 |5 9 13 14 """ } @Test fun `sample input 2`() { """|5 4 7 |1 2 3 4 |7 8 9 10 |13 14 15 16 |19 20 21 22 |25 26 27 28 """ shouldOutput """ |28 27 26 25 |22 9 15 19 |16 8 21 13 |10 14 20 7 |4 3 2 1 """ } @Test fun `sample input 3`() { """|2 2 3 |1 1 |1 1 """ shouldOutput """ |1 1 |1 1 """ } private infix fun String.shouldOutput(expectedOutput: String) { val outputRecorder = OutputRecorder() main(toReadLineFunction(), outputRecorder) outputRecorder.text shouldEqual expectedOutput.trimMargin() + "\n" } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
6,075
katas
The Unlicense
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day09.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2022 import kotlin.math.abs import kotlin.math.max enum class Motion { R, U, L, D } fun main() { fun List<List<Int>>.printMotion() = println( (10 downTo -10).joinToString(separator = "\n") { i -> (-10..10).joinToString(separator = " ") { j -> when { i !in -9..9 -> "% 3d".format(j) j == 10 -> "% 3d".format(i) this.contains(listOf(i, j)) -> " ${this.indexOf(listOf(i, j))}" i == 0 && j == 0 -> " s" else -> " ." } } } + "\n\n" ) fun List<Int>.distanceRow(other: List<Int>) = abs(this[0] - other[0]) fun List<Int>.distanceCol(other: List<Int>) = abs(this[1] - other[1]) fun List<Int>.directionRow(other: List<Int>) = if (this[0] == other[0]) 0 else if (this[0] - other[0] > 0) -1 else 1 fun List<Int>.directionCol(other: List<Int>) = if (this[1] == other[1]) 0 else if (this[1] - other[1] > 0) -1 else 1 fun List<Int>.distance(other: List<Int>) = max(distanceRow(other), distanceCol(other)) fun MutableList<Int>.follow(other: List<Int>) { if (distance(other) > 1) { if (distanceRow(other) > 0 && distanceCol(other) > 0) { this[0] += directionRow(other) this[1] += directionCol(other) } else if (distanceRow(other) > 0) { this[0] = if (other[0] > this[0]) this[0] + 1 else this[0] - 1 } else { this[1] = if (other[1] > this[1]) this[1] + 1 else this[1] - 1 } } } fun part1(input: List<String>): Int = input.map { it.split(" ") } .map { (motion, step) -> Motion.valueOf(motion) to step.toInt() } .fold( Triple( mutableListOf(0, 0), mutableListOf(0, 0), mutableSetOf(listOf(0, 0)) ) ) { (head, tail, tailVisited), (motion, step) -> repeat(step) { when (motion) { Motion.R -> head[1] += 1 Motion.U -> head[0] += 1 Motion.L -> head[1] -= 1 Motion.D -> head[0] -= 1 } tail.follow(head) tailVisited.add(tail.toList()) } Triple(head, tail, tailVisited) } .third.size fun part2(input: List<String>): Int = input.map { it.split(" ") } .map { (motion, step) -> Motion.valueOf(motion) to step.toInt() } .fold( List(10) { mutableListOf(0, 0) }.let { knots -> Triple( knots[0], knots, mutableSetOf(listOf(0, 0)) ) } ) { (head, knots, tailVisited), (motion, step) -> repeat(step) { when (motion) { Motion.R -> head[1] += 1 Motion.U -> head[0] += 1 Motion.L -> head[1] -= 1 Motion.D -> head[0] -= 1 } (1 until 10).forEach { knots[it].follow(knots[it - 1]) if (it == 9) tailVisited.add(knots[it].toList()) } } Triple(knots[0], knots, tailVisited) } .third.size val testInput1 = readInputLines("Day09_test") val testInput2 = readInputLines("Day09_test2") check(part1(testInput1) == 13) check(part2(testInput2) == 36) val input = readInputLines("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
3,688
advent-of-code
Apache License 2.0
src/Day07.kt
WhatDo
572,393,865
false
{"Kotlin": 24776}
fun main() { val input = readInput("Day07") val root = Dir("/", null, emptyList()) var shell = ShellState(FileSystem(root), root) var currentInput = input while (currentInput.isNotEmpty()) { val nextCmdItemCount = (currentInput.subList(1, currentInput.size) .indexOfFirst { it.startsWith("$") } + 1) .takeIf { it > 0 } ?: currentInput.size val cmdWithOutput = currentInput.subList(0, nextCmdItemCount) val cmd = parseCmd(cmdWithOutput[0]) val cmdOutput = cmdWithOutput.subList(1, cmdWithOutput.size) shell = cmd.run(shell, cmdOutput) currentInput = currentInput.subList(cmdWithOutput.size, currentInput.size) } val smallDirs = findDirsUnder100000(root) println("Found small dirs $smallDirs") println("Found small dirs sum ${smallDirs.sumOf { it.size }}") val toDelete = findSmallestDirToDelete(root) println("Found smallest dir to delete ${toDelete.name} with size ${toDelete.size}") } private fun findSmallestDirToDelete(root: Dir): Dir { val rootSize = root.size val availableSize = 70000000 - rootSize val minDirSize = 30000000 - availableSize println("Missing $minDirSize") var smallestDir = root treeWalk(root) { node -> val size = node.size if (size < smallestDir.size && size > minDirSize) { smallestDir = node } } return smallestDir } private fun findDirsUnder100000(root: Dir): List<Dir> { val result = mutableListOf<Dir>() treeWalk(root) { node -> if (node.size < 100000) { result.add(node) } } return result } private fun treeWalk(root: Dir, onEach: (Dir) -> Unit) { val deque = ArrayDeque<Dir>() deque.add(root) while (deque.isNotEmpty()) { val node = deque.removeLast() node.files.forEach { if (it is Dir) deque.addLast(it) } onEach(node) } } data class ShellState( val fileSystem: FileSystem, val currentDir: Dir ) class FileSystem( val root: Dir ) sealed class FileSystemNode( val name: String, val parent: Dir? ) { abstract val size: Long } class File(name: String, parent: Dir, override val size: Long) : FileSystemNode(name, parent) { override fun toString(): String { return "File(name=$name)" } } class Dir(name: String, parent: Dir?, var files: List<FileSystemNode>) : FileSystemNode(name, parent) { override val size: Long get() = files.sumOf(FileSystemNode::size) override fun toString(): String { return "Dir(name=$name, files=$files)" } } sealed interface Cmd { fun run(state: ShellState, output: List<String>): ShellState } object Ls : Cmd { override fun run(state: ShellState, output: List<String>): ShellState { println("ls") println(output.toString()) val currentDir = state.currentDir currentDir.files = output.map { parseFile(it, currentDir) } return state } } class Cd(private val dir: String) : Cmd { override fun run(state: ShellState, output: List<String>): ShellState { println("cd") if (dir == "/") { return state.copy(currentDir = state.fileSystem.root) } if (dir == "..") { return state.copy(currentDir = state.currentDir.parent ?: state.currentDir) // can't go up from root } val newDir = state.currentDir.files.find { it.name == dir } if (newDir is Dir) { return state.copy(currentDir = newDir) } TODO("Unknown argument $dir") } } private fun parseFile(file: String, dir: Dir) = file.split(" ").let { (type, name) -> when { type == "dir" -> Dir(name, dir, emptyList()) numberRegex.matches(type) -> File(name, dir, type.toLong()) else -> TODO("Unknown output type $type") } } private fun parseCmd(cmd: String): Cmd = cmd.split(" ").let { line -> when (val cmd = line[1]) { "cd" -> Cd(line[2]) "ls" -> Ls else -> TODO("Unknown cmd $cmd") } } private val numberRegex = "^[0-9]+$".toRegex()
0
Kotlin
0
0
94abea885a59d0aa3873645d4c5cefc2d36d27cf
4,126
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/day14.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package day14 import aoc.utils.* import java.lang.Integer.max import java.lang.Integer.min fun main() { part2() } fun part2(): Int { val sandSource = Cursor(500, 0) var rockLinEnds = readInput("day14-input.txt") .map { it.findInts().windowed(2, 2).map { Cursor(it[0], it[1]) } } val large = rockLinEnds.map { it.maxOf { max(it.y, sandSource.y) } }.maxOrNull()!! val small = rockLinEnds.map { it.minOf { min(it.x, sandSource.x) } }.minOrNull()!! rockLinEnds = rockLinEnds .plus(element = listOf(Cursor(small-10000,large+2),Cursor(small+10000,large+2))) val smallestX = rockLinEnds.map { it.minOf { min(it.x, sandSource.x) } }.minOrNull()!! val smallestY = rockLinEnds.map { it.minOf { min(it.y, sandSource.y) } }.minOrNull()!! val offset = Cursor(smallestX, smallestY) val offsettedEnds = rockLinEnds.map { it.map { it.minus(offset) } } val largestOffsetX = offsettedEnds.map { it.maxOf { it.x } }.maxOrNull()!! val largestOffsetY = offsettedEnds.map { it.maxOf { it.y } }.maxOrNull()!! val cave = Matrix(largestOffsetX.toLong() + 1, largestOffsetY.toLong() + 1) { i: Int, i2: Int -> '.' } cave.replace(Cursor(500, 0).minus(offset)) { entry -> '+' } val rockLines = offsettedEnds .flatMap { it.windowed(2, 1).map { it[0] to it[1] } } rockLines.forEach { drawRockLine(cave, it) } for (i in 1..930000) { var sand: Cursor? = sandSource.minus(offset) while(sand != null) { val down = Cursor(0, 1) val downLeft = Cursor(-1, 1) val downRight = Cursor(1, 1) if (cave.getRelative(sand, down) == null || cave.getRelative(sand, down)?.value == '.') { sand = sand.plus(down) } else if (cave.getRelative(sand, downLeft) == null || cave.getRelative(sand, downLeft)?.value == '.') { sand = sand.plus(downLeft) } else if (cave.getRelative(sand, downRight) == null || cave.getRelative(sand, downRight)?.value == '.') { sand = sand.plus(downRight) } else if(cave.isInBounds(sand)){ if(sand==sandSource.minus(offset)) { throw Error("full at ${i}") } cave.replace(sand) { 'o' } sand = null } // if(sand != null && !cave.isInBounds(sand)) { // throw Error("Out of bounds on round ${i-1}") // } } } // println(cave.visualize("")) // 874 your answer is too high. // 873 correct... return 1; } fun part1(): Int { val sandSource = Cursor(500, 0) val rockLinEnds = readInput("day14-input.txt") .map { it.findInts().windowed(2, 2).map { Cursor(it[0], it[1]) } } val smallestX = rockLinEnds.map { it.minOf { min(it.x, sandSource.x) } }.minOrNull()!! val smallestY = rockLinEnds.map { it.minOf { min(it.y, sandSource.y) } }.minOrNull()!! val offset = Cursor(smallestX, smallestY) val offsettedEnds = rockLinEnds.map { it.map { it.minus(offset) } } val largestX = offsettedEnds.map { it.maxOf { it.x } }.maxOrNull()!! val largestY = offsettedEnds.map { it.maxOf { it.y } }.maxOrNull()!! val cave = Matrix(largestX.toLong() + 1, largestY.toLong() + 1) { i: Int, i2: Int -> '.' } cave.replace(Cursor(500, 0).minus(offset)) { entry -> '+' } val rockLines = offsettedEnds .flatMap { it.windowed(2, 1).map { it[0] to it[1] } } rockLines.forEach { drawRockLine(cave, it) } for (i in 1..10000) { var sand: Cursor? = sandSource.minus(offset) while(sand != null) { val down = Cursor(0, 1) val downLeft = Cursor(-1, 1) val downRight = Cursor(1, 1) if (cave.getRelative(sand, down) == null || cave.getRelative(sand, down)?.value == '.') { sand = sand.plus(down) } else if (cave.getRelative(sand, downLeft) == null || cave.getRelative(sand, downLeft)?.value == '.') { sand = sand.plus(downLeft) } else if (cave.getRelative(sand, downRight) == null || cave.getRelative(sand, downRight)?.value == '.') { sand = sand.plus(downRight) } else if(cave.isInBounds(sand)){ cave.replace(sand) { 'o' } sand = null } if(sand != null && !cave.isInBounds(sand)) { throw Error("Out of bounds on round ${i-1}") } } } println(cave.visualize("")) // 874 your answer is too high. // 873 correct... return 1; } fun drawRockLine(cave: Matrix<Char>, line: Pair<Cursor, Cursor>) { val start = line.first var end = line.second val line = Line(Point(start.x.toLong(), start.y.toLong(), 0), Point(end.x.toLong(), end.y.toLong(), 0)) val points = pointsInLine(line) .map { Cursor(it.x.toInt(), it.y.toInt()) } points.forEach { cave.replace(it) { '#' } } }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
5,017
adventOfCode2022
Apache License 2.0
src/main/kotlin/pl/bizarre/day2_1.kt
gosak
572,644,357
false
{"Kotlin": 26456}
package pl.bizarre import pl.bizarre.Day2Move.Companion.findMove import pl.bizarre.common.loadInput import java.util.regex.Pattern fun main() { val input = loadInput(2) println("result ${day2_1(input)}") } fun day2_1(input: List<String>): Int { val whitespace = Pattern.compile("\\s+") return input.sumOf { line -> val (opponent, my) = whitespace.split(line).map { findMove(it) } matchResult(opponent, my) } } enum class Day2Move( val keys: Collection<String>, val score: Int, ) { Rock(setOf("A", "X"), 1), Paper(setOf("B", "Y"), 2), Scissors(setOf("C", "Z"), 3); // 0 - draw, 1 - win, -1 - lose fun result(opponent: Day2Move): Int = when { opponent == this -> 0 opponent == Rock && this == Paper -> 1 opponent == Rock && this == Scissors -> -1 opponent == Paper && this == Scissors -> 1 else -> -opponent.result(this) } companion object { fun findMove(value: String) = values().find { value in it.keys } ?: error("Invalid key $value") } } fun matchResult(opponentMove: Day2Move, myMove: Day2Move) = 3 + myMove.result(opponentMove) * 3 + myMove.score
0
Kotlin
0
0
aaabc56532c4a5b12a9ce23d54c76a2316b933a6
1,230
adventofcode2022
Apache License 2.0
src/Day03.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
fun main() { fun List<List<Int>>.intersection(): Int { return map { it.toSet() }.reduce { a, b -> a intersect b }.sum() } fun parseInput(input: String): List<Int> { return input.toCharArray().asList().map { if (it.isUpperCase()) it - 'A' + 27 else it - 'a' + 1 } } fun part1(input: List<String>): Int { return input .map(::parseInput) .map { l -> l.chunked(l.size / 2) } .sumOf { it.intersection() } } fun part2(input: List<String>): Int { return input .map(::parseInput) .chunked(3) .sumOf { it.intersection() } } val testInput = readInputLines("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInputLines(3) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
782
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/Day03.kt
KarinaCher
572,657,240
false
{"Kotlin": 21749}
fun main() { fun part1(input: List<String>): Int { var result = 0 for (rucksack in input) { val rp = rucksack.toList() val chunked = rp.chunked(rp.size / 2) val ic = findIncorrect(chunked) result += getPriority(ic) } return result } fun part2(input: List<String>): Int { var result = 0 val chunked = input.chunked(3) for (chunk in chunked) { val bagdeCh = findBadge(chunk) result += getPriority(bagdeCh) } return result } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun findIncorrect(chunked: List<List<Char>>): Char { for (it in chunked[0]) { if (chunked[1].contains(it)) { return it } } return '-' } fun findBadge(chunk: List<String>): Char { val intersect = chunk[0].toCharArray().intersect(chunk[1].toList()) return intersect.intersect(chunk[2].toList()).first() } fun getPriority(ch: Char): Int = if (ch in 'a'..'z') ch.minus(96).code else ch.minus(38).code
0
Kotlin
0
0
17d5fc87e1bcb2a65764067610778141110284b6
1,239
KotlinAdvent
Apache License 2.0
src/com/ncorti/aoc2023/Day11.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 import kotlin.math.abs import kotlin.math.min fun main() { fun part(factor : Long = 2): Long { val map = getInputAsText("11") { split("\n").filter(String::isNotBlank).map { it.toCharArray().toMutableList() } }.toMutableList() var i = 0 while (i < map.size) { if (map[i].all { it == '.' }) { map.removeAt(i) map.add(i, map[i].toList().map { '$' }.toMutableList()) } i++ } i = 0 while (i < map[0].size) { if (map.all { it[i] == '.' || it[i] == '$' }) { map.forEach { it.removeAt(i) it.add(i, '$') } } i++ } val galaxies = mutableListOf<Pair<Int, Int>>() map.forEachIndexed { i, line -> line.forEachIndexed { j, char -> if (char == '#') { galaxies.add(i to j) } } } var sum = 0L val seen = mutableSetOf<Pair<Pair<Int,Int>,Pair<Int,Int>>>() for (i in galaxies.indices) { for (j in i .. galaxies.lastIndex) { if (galaxies[i] to galaxies[j] !in seen && galaxies[j] to galaxies[i] !in seen && i != j) { seen.add(galaxies[i] to galaxies[j]) var localSum = 1L val upMost = min(galaxies[i].first, galaxies[j].first) val leftMost = min(galaxies[i].second, galaxies[j].second) for(col in upMost+1 until upMost+abs(galaxies[i].first - galaxies[j].first)) { localSum += if (map[col][galaxies[i].second] == '$') { factor } else { 1L } } for(row in leftMost+1 until leftMost+abs(galaxies[i].second - galaxies[j].second)) { localSum += if (map[galaxies[i].first][row] == '$') { factor } else { 1L } } if (galaxies[i].first != galaxies[j].first && galaxies[i].second != galaxies[j].second) { localSum++ } sum += localSum } } } return sum } println(part(factor = 2L)) println(part(factor = 1_000_000L)) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
2,581
adventofcode-2023
MIT License
day09/Kotlin/day09.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* fun print_day_9() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 9" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Smoke Basin -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_9() Day9().part_1() Day9().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day9 { data class Point(val x:Int, val y:Int) { fun neighbours(xBoundary: Int, yBoundary: Int): List<Point> = listOf(Point(x-1, y), Point(x+1, y), Point(x, y-1), Point(x, y+1) ).filter { it.x in 0 until xBoundary && it.y in 0 until yBoundary } } val heightmap = File("../Input/day9.txt").readLines().map { it.toCharArray().map { c -> c.digitToInt() } } fun part_1() { val total = heightmap.foldIndexed(0) { yIndex, acc, list -> list.foldIndexed(acc) { xIndex, sum, height -> if (Point(xIndex, yIndex).neighbours(heightmap[0].size, heightmap.size).count { heightmap[it.y][it.x] <= height } == 0) sum + heightmap[yIndex][xIndex] + 1 else sum } } println("Puzzle 1: $total") } fun part_2() { fun getLowPoints() = heightmap.flatMapIndexed { yIndex, list -> list.mapIndexed { xIndex, height -> val smallerNeighbours = Point(xIndex, yIndex).neighbours(heightmap[0].size, heightmap.size).count { heightmap[it.y][it.x] <= height } if (smallerNeighbours == 0) Point(xIndex, yIndex) else null }.filterNotNull() } fun getBasinSize(p: Point): Int { val visited = mutableSetOf(p) val queue = mutableListOf(p) while (queue.isNotEmpty()) { val newNeighbors = queue.removeFirst() .neighbours(heightmap[0].size, heightmap.size) .filter { it !in visited } .filter { heightmap[it.y][it.x] != 9 } visited.addAll(newNeighbors) queue.addAll(newNeighbors) } return visited.size } val answer = getLowPoints().map { getBasinSize(it) } .sortedDescending() .take(3) .reduce { total, next -> total * next } println("Puzzle 2: $answer") } }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
2,682
AOC2021
Apache License 2.0
LeetCode/0128. Longest Consecutive Sequence/Solution.kt
InnoFang
86,413,001
false
{"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410}
/** * Created by <NAME> on 2018/3/13. */ /** * 68 / 68 test cases passed. * Status: Accepted * Runtime: 328 ms */ class Solution { fun longestConsecutive(nums: IntArray): Int { val uf = UnionFind(nums) val store = HashMap<Int, Int>() nums.forEach { i -> if (!store.containsKey(i)) { store[i] = i store[i + 1]?.let { uf.union(i, it) } store[i - 1]?.let { uf.union(i, it) } } } return uf.max() } class UnionFind(array: IntArray) { val map = HashMap<Int, Int>() init { array.forEach { map[it] = it } } private fun find(idx: Int): Int { if (idx != map[idx]) map[idx] = find(map[idx]!!) return map[idx]!! } fun isConnected(p: Int, q: Int): Boolean = find(p) == find(q) fun union(p: Int, q: Int) { val i = find(p) val j = find(q) map[i] = j } fun max(): Int = map.map { it.value }.groupBy(this::find).map { it.value.size }.max() ?: 0 } } /** * 68 / 68 test cases passed. * Status: Accepted * Runtime: 264 ms */ class Solution2 { val map = HashMap<Int, Int>() private fun find(idx: Int): Int { var i = idx while (map[i] != i) { map[i] = map[map[i]!!]!! i = map[i]!! } return i } fun longestConsecutive(nums: IntArray): Int { var res = 0 nums.forEach { i -> if (!map.containsKey(i)) { map[i] = i map[i - 1]?.let { map[i] = find(i - 1) } map[i + 1]?.let { map[i + 1] = find(i) } } } nums.forEach { res = maxOf(res, it - find(it) + 1) } return res } } /** * 68 / 68 test cases passed. * Status: Accepted * Runtime: 260 ms */ class Solution3 { fun longestConsecutive(nums: IntArray): Int { val set = nums.toHashSet() var longestStreak = 0 set.forEach { if (!set.contains(it-1)){ var currentStreak = 1 while (set.contains(it + currentStreak)) currentStreak++ longestStreak = maxOf(longestStreak, currentStreak) } } return longestStreak } } fun main(args: Array<String>) { Solution3().longestConsecutive(intArrayOf(100, 4, 200, 1, 3, 2)).let(::println) Solution3().longestConsecutive(intArrayOf(0, -1)).let(::println) Solution3().longestConsecutive(intArrayOf(1, 3, 5, 2, 4)).let(::println) }
0
C++
8
20
2419a7d720bea1fd6ff3b75c38342a0ace18b205
2,600
algo-set
Apache License 2.0
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec11.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2020 import org.elwaxoro.advent.PuzzleDayTester class Dec11 : PuzzleDayTester(11, 2020) { override fun part1(): Int = parse().findStableSeating(maxNeighbors = 4, transformFloor = true).countOccupiedSeats() override fun part2(): Int = parse().findStableSeating(maxNeighbors = 5, transformFloor = false).countOccupiedSeats() private fun List<List<Int>>.findStableSeating( maxNeighbors: Int, transformFloor: Boolean ): List<List<Int>> = modSeating(maxNeighbors, transformFloor).let { newSeatingChart -> newSeatingChart.takeIf { noChange(newSeatingChart) } ?: newSeatingChart.findStableSeating(maxNeighbors, transformFloor) } private fun List<List<Int>>.modSeating( maxNeighbors: Int, transformFloor: Boolean ): List<List<Int>> = mapIndexed { y, row -> row.mapIndexed { x, spot -> countNeighbors(y, x, transformFloor).let { neighbors -> when { spot == 0 && neighbors == 0 -> 1 // nobody nearby! sit down spot == 1 && neighbors >= maxNeighbors -> 0 // too many! stand up else -> spot // no change } } } } private fun List<List<Int>>.countNeighbors(y: Int, x: Int, transformFloor: Boolean): Int = listOf( findSeat(y, x, -1, -1, transformFloor), // upper left findSeat(y, x, -1, 0, transformFloor), // up findSeat(y, x, -1, 1, transformFloor), // upper right findSeat(y, x, 0, -1, transformFloor), // left findSeat(y, x, 0, 1, transformFloor), // right findSeat(y, x, 1, -1, transformFloor), // lower left findSeat(y, x, 1, 0, transformFloor), // down findSeat(y, x, 1, 1, transformFloor), // lower right ).sum() private fun List<List<Int>>.findSeat(y: Int, x: Int, yMod: Int, xMod: Int, transformFloor: Boolean): Int = getSeat(y + yMod, x + xMod, transformFloor).let { if (it == 0 || it == 1) // seat or seat-equivalent floor (puzzle 1) it else // floor section, keep going findSeat(y + yMod, x + xMod, yMod, xMod, transformFloor) } private fun List<List<Int>>.getSeat(y: Int, x: Int, transformFloor: Boolean): Int = if (y < 0 || x < 0 || y >= this.size || x >= this[y].size) { 0 // fell off the side } else if (transformFloor && this[y][x] == -1) { 0 // for puzzle 1, floor counts as an empty seat } else { this[y][x] } private fun List<List<Int>>.noChange(that: List<List<Int>>): Boolean = filterIndexed { rowIdx, row -> row.filterIndexed { colIdx, _ -> this[rowIdx][colIdx] != that[rowIdx][colIdx] }.isNotEmpty() }.isEmpty() private fun List<List<Int>>.countOccupiedSeats(): Int = map { row -> row.filter { it == 1 }.sum() }.sum() private fun parse(): List<List<Int>> = load().map { row -> row.map { when (it) { '#' -> 1 'L' -> 0 '.' -> -1 else -> throw IllegalStateException("AHHHHHHHHHHHHHHHHHHHHH $it") } } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
3,304
advent-of-code
MIT License
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p00/Leet5.kt
artemkaxboy
513,636,701
false
{"Kotlin": 547181, "Java": 13948}
package com.artemkaxboy.leetcode.p00 private class Leet5 { fun longestPalindrome(s: String): String { var longestFound: Pair<Int, Int> = 0 to 0 for (firstLetterOffset in s.indices) { findLongestForSubstring(s, firstLetterOffset, longestFound.second + 1) ?.let { longestFound = it } } return s.drop(longestFound.first).take(longestFound.second) } private fun findLongestForSubstring(s: String, offset: Int, minPalindromeLength: Int): Pair<Int, Int>? { for (lastPossibleLetter in s.length downTo offset + minPalindromeLength) { val length = lastPossibleLetter - offset if (isPalindrome(s, offset, length)) return Pair(offset, length) } return null } private fun isPalindrome(string: String, offset: Int, length: Int): Boolean { val lengthToCheck = length / 2 for (i in 0 until lengthToCheck) { if (string[offset + i] != string[offset + length - 1 - i]) return false } return true } } fun main() { val testCase1 = "babad" doWork(testCase1) val testCase2 = "cbbd" doWork(testCase2) val myCase = "ababa" doWork(myCase) val myCase2 = "ababacdcdcdc" doWork(myCase2) } private fun doWork(data: String) { val solution = Leet5() val result = solution.longestPalindrome(data) println("Data: $data") println("Result: $result\n") }
0
Kotlin
0
0
516a8a05112e57eb922b9a272f8fd5209b7d0727
1,470
playground
MIT License
src/main/kotlin/aoc23/Day07.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc23 import common.Year23 import aoc23.Day07Domain.CamelCards import aoc23.Day07Domain.Cards import aoc23.Day07Parser.toCamelCards import aoc23.Day07Solution.part1Day07 import aoc23.Day07Solution.part2Day07 import com.github.shiguruikai.combinatoricskt.permutationsWithRepetition import common.Strings.replaceAt object Day07 : Year23 { fun List<String>.part1(): Int = part1Day07() fun List<String>.part2(): Int = part2Day07() } object Day07Solution { fun List<String>.part1Day07(): Int { Day07Domain.withJoker = false return toCamelCards() .toTotalWinnings() } fun List<String>.part2Day07(): Int { Day07Domain.withJoker = true return toCamelCards() .toTotalWinnings() } } object Day07Domain { var withJoker: Boolean = false class CamelCards( val hands: List<Hand> ) { fun toTotalWinnings(): Int = hands.sorted().foldIndexed(0) { index, acc, hand -> acc + hand.bid * (index + 1) } } private val cardsByValue: String get() = when { withJoker -> "J23456789TQKA" else -> "23456789TJQKA" } class Hand( val cards: Cards, val bid: Int, ) : Comparable<Hand> { private val type: Int = with(JokerReplacer) { cards .replaceJoker() .type } override fun compareTo(other: Hand): Int = type.compareTo(other.type) .takeUnless { it == 0 } ?: tieBreak(other) private fun tieBreak(other: Hand): Int = this.cards .value .mapIndexed { index, c -> c to other.cards.value[index] } .map { Card(it.first).compareTo(Card(it.second)) } .firstOrNull { it != 0 } ?: 0 } object JokerReplacer { fun Cards.replaceJoker(): Cards = if (withJoker) { toReplacedJokers() .filterMaxType() .last() } else this private fun Cards.toReplacedJokers(): List<Cards> { val jokerIndexes = this.value.toList().mapIndexedNotNull { index, c -> index.takeIf { c == 'J' } } val cardPermutations = cardsByValue.toList().permutationsWithRepetition(jokerIndexes.size).toList() return cardPermutations.map { replacements -> Cards( value = jokerIndexes.foldIndexed(this.value) { index, acc, jokerIndex -> acc.replaceAt(jokerIndex, replacements[index]) } ) } } private fun List<Cards>.filterMaxType(): List<Cards> = this.maxOf { it.type }.let { maxType -> this.filter { it.type == maxType } } } class Card(private val char: Char) : Comparable<Card> { override fun compareTo(other: Card): Int = this.char.value.compareTo(other.char.value) private val Char.value: Int get() = cardsByValue.indexOf(this) } class Cards( val value: String, ) { val type: Int by lazy { value.groupBy { it }.values .filter { type -> type.size > 1 } .let { scoringTypes -> val matchesSize = scoringTypes .sumOf { type -> type.size } * 3 val numberOfMatches = scoringTypes.size * 4 matchesSize - numberOfMatches } } } } object Day07Parser { fun List<String>.toCamelCards(): CamelCards = CamelCards( hands = this.map { line -> line.split(" ").let { (cards, bid) -> Day07Domain.Hand( cards = Cards(cards), bid = bid.toInt(), ) } } ) }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
4,179
aoc
Apache License 2.0
src/Day04.kt
haraldsperre
572,671,018
false
{"Kotlin": 17302}
fun main() { fun getElfRanges(pair: String): Pair<IntRange, IntRange> { return pair .split(",") .map { elf -> val (low, high) = elf.split("-").map { it.toInt() } low..high } .let { it[0] to it[1] } } fun part1(input: List<String>): Int { return input .count { pair -> val (first, second) = getElfRanges(pair) val overlap = first.intersect(second) overlap == first.toSet() || overlap == second.toSet() } } fun part2(input: List<String>): Int { return input .count{ pair -> val (first, second) = getElfRanges(pair) first.intersect(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)) }
0
Kotlin
0
0
c4224fd73a52a2c9b218556c169c129cf21ea415
1,087
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc23/Day11.kt
tahlers
725,424,936
false
{"Kotlin": 65626}
package aoc23 import kotlin.math.abs typealias RowAndColumnIndexes = Pair<Set<Long>, Set<Long>> object Day11 { data class Pos(val x: Long, val y: Long) data class Image(val galaxies: Set<Pos>) fun calculateSumOfShortestPaths(input: String, expansionCount: Int = 2): Long { val originalImage = parseInput(input) val expanded = expand(originalImage, expansionCount) val galaxyPairs = galaxyPairs(expanded.galaxies, expanded.galaxies) val distances = galaxyPairs.map { (galaxy1, galaxy2) -> abs(galaxy1.x - galaxy2.x) + abs(galaxy1.y - galaxy2.y) } return distances.sum() / 2 // half the sum because we have double distances a->b and b->a } private fun expand(image: Image, expansionCount: Int): Image { val (emptyRows, emptyColumns) = emptyRowsAndColumns(image) val expandedGalaxies = image.galaxies.map { galaxy -> val emptyRowsBefore = emptyRows.filter { it < galaxy.y }.size val emptyColsBefore = emptyColumns.filter { it < galaxy.x }.size Pos(galaxy.x + (emptyColsBefore * (expansionCount - 1)).toLong(), galaxy.y + (emptyRowsBefore * (expansionCount - 1)).toLong()) } return Image(expandedGalaxies.toSet()) } private fun emptyRowsAndColumns(image: Image): RowAndColumnIndexes { val maxX = image.galaxies.maxOf { it.x } val maxY = image.galaxies.maxOf { it.y } val rowIndexes = (0..maxY).filter { idx -> image.galaxies.none { it.y == idx } } val columnIndexes = (0..maxX).filter { idx -> image.galaxies.none { it.x == idx } } return rowIndexes.toSet() to columnIndexes.toSet() } private fun galaxyPairs(c1: Set<Pos>, c2: Set<Pos>): Set<Pair<Pos, Pos>> { return c1.flatMap { left -> c2.mapNotNull { right -> if (left != right) left to right else null } }.toSet() } private fun parseInput(input: String): Image { val lines = input.trim().lines() val galaxies = lines.flatMapIndexed { y: Int, line: String -> line.mapIndexedNotNull { x, c -> if (c == '#') Pos(x.toLong(), y.toLong()) else null } } return Image(galaxies.toSet()) } }
0
Kotlin
0
0
0cd9676a7d1fec01858ede1ab0adf254d17380b0
2,301
advent-of-code-23
Apache License 2.0
src/Day07.kt
f1qwase
572,888,869
false
{"Kotlin": 33268}
import java.lang.IllegalStateException private const val COMMAND_PREFIX = "$ " private val TOTAL_SPACE = 70000000 private val SPACE_REQUIRED = 30000000 private sealed interface FSNode { val parent: FSNode? val name: String val size: Int class File( override val parent: FSNode?, override val name: String, override val size: Int, ) : FSNode class Dir( override val parent: FSNode?, override val name: String, var children: List<FSNode>, var discovered: Boolean = false, ) : FSNode { override val size by lazy { if (!discovered) { throw IllegalStateException("size of $name cannot be calculated, it is not discovered still") } children.sumOf { it.size } } fun walk(block: (FSNode) -> Unit) { block(this) children .filterIsInstance<Dir>() .forEach { it.walk(block) } } } } private typealias Input = String private typealias Output = List<String> private fun parseIo(io: List<String>): List<Pair<Input, Output>> = buildList { io.forEach { if (it.startsWith(COMMAND_PREFIX)) { add(it.substringAfter(COMMAND_PREFIX) to mutableListOf()) } else { (last().second as MutableList).add(it) } } } private fun discoverFs(cmdIo: List<Pair<Input, Output>>): FSNode.Dir { var currentDir: FSNode.Dir? = null cmdIo.forEach { (cmdIn, cmdOut) -> val command = cmdIn.substringBefore(" ") when (command) { "ls" -> { currentDir!!.discovered = true currentDir!!.children = cmdOut.map { val (sizeOrDir, name) = it.split(" ") when (sizeOrDir) { "dir" -> FSNode.Dir(currentDir, name, mutableListOf()) else -> FSNode.File(currentDir, name, sizeOrDir.toInt()) } } } "cd" -> { val args = cmdIn.substringAfter(" ") currentDir = when (args) { "/" -> FSNode.Dir(null, "/", mutableListOf()) ".." -> currentDir!!.parent as FSNode.Dir else -> currentDir!!.children.find { it.name == args } as? FSNode.Dir ?: throw (IllegalArgumentException("No such directory: $args")) } } } } while (currentDir!!.parent != null) { currentDir = currentDir!!.parent as FSNode.Dir } return currentDir!! } fun main() { fun part1(input: List<String>): Int { val commandStrings = parseIo(input) val fs = discoverFs(commandStrings) return buildList { fs.walk { if (it is FSNode.Dir && it.size <= 100000) { add(it.size) } } }.sumOf { it } } fun part2(input: List<String>): Int { val commandStrings = parseIo(input) val fs = discoverFs(commandStrings) val occupiedSpace = fs.size val freeSpace = TOTAL_SPACE - occupiedSpace val spaceToFree = SPACE_REQUIRED - freeSpace return buildList { fs.walk { if (it is FSNode.Dir && it.size >= spaceToFree) { add(it.size) } } }.minByOrNull { it }!! } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) { part1(testInput) } val input = readInput("Day07") println(part1(input)) check(part2(testInput) == 24933642) { part2(testInput) } println(part2(input)) }
0
Kotlin
0
0
3fc7b74df8b6595d7cd48915c717905c4d124729
3,819
aoc-2022
Apache License 2.0
src/day08/Day08.kt
JakubMosakowski
572,993,890
false
{"Kotlin": 66633}
package day08 import readInput /** * The expedition comes across a peculiar patch of tall trees all planted carefully in a grid. * The Elves explain that a previous expedition planted these trees as a reforestation effort. * Now, they're curious if this would be a good location for a tree house. * * First, determine whether there is enough tree cover here to keep a tree house hidden. * To do this, you need to count the number of trees that are visible from outside the grid * when looking directly along a row or column. * * The Elves have already launched a quadcopter to generate a map with the height of each tree * (your puzzle input). For example: * * 30373 * 25512 * 65332 * 33549 * 35390 * Each tree is represented as a single digit whose value is its height, * where 0 is the shortest and 9 is the tallest. * * A tree is visible if all of the other trees between it and an edge of the grid are shorter than it. * Only consider trees in the same row or column; that is, only look up, * down, left, or right from any given tree. * * All of the trees around the edge of the grid are visible - * since they are already on the edge, there are no trees to block the view. * In this example, that only leaves the interior nine trees to consider: * * The top-left 5 is visible from the left and top. * (It isn't visible from the right or bottom since other trees of height 5 are in the way.) * The top-middle 5 is visible from the top and right. * The top-right 1 is not visible from any direction; for it to be visible, * there would need to only be trees of height 0 between it and an edge. * The left-middle 5 is visible, but only from the right. * The center 3 is not visible from any direction; for it to be visible, * there would need to be only trees of at most height 2 between it and an edge. * The right-middle 3 is visible from the right. * In the bottom row, the middle 5 is visible, but the 3 and 4 are not. * With 16 trees visible on the edge and another 5 visible in the interior, * a total of 21 trees are visible in this arrangement. * * Consider your map; how many trees are visible from outside the grid? * * PART 2: * Content with the amount of tree cover available, the Elves just need to know the best spot to build their tree house: * they would like to be able to see a lot of trees. * * To measure the viewing distance from a given tree, * look up, down, left, and right from that tree; * stop if you reach an edge or at the first tree that is the same height or taller than the tree under consideration. * (If a tree is right on the edge, at least one of its viewing distances will be zero.) * * The Elves don't care about distant trees taller than those found by the rules above; * the proposed tree house has large eaves to keep it dry, * so they wouldn't be able to see higher than the tree house anyway. * * In the example above, consider the middle 5 in the second row: * * 30373 * 25512 * 65332 * 33549 * 35390 * Looking up, its view is not blocked; it can see 1 tree (of height 3). * Looking left, its view is blocked immediately; it can see only 1 tree (of height 5, right next to it). * Looking right, its view is not blocked; it can see 2 trees. * Looking down, its view is blocked eventually; it can see 2 trees (one of height 3, * then the tree of height 5 that blocks its view). * A tree's scenic score is found by multiplying together its viewing distance in each of the four directions. * For this tree, this is 4 (found by multiplying 1 * 1 * 2 * 2). * * However, you can do even better: consider the tree of height 5 in the middle of the fourth row: * * 30373 * 25512 * 65332 * 33549 * 35390 * Looking up, its view is blocked at 2 trees (by another tree with a height of 5). * Looking left, its view is not blocked; it can see 2 trees. * Looking down, its view is also not blocked; it can see 1 tree. * Looking right, its view is blocked at 2 trees (by a massive tree of height 9). * This tree's scenic score is 8 (2 * 2 * 1 * 2); this is the ideal spot for the tree house. * * Consider each tree on your map. What is the highest scenic score possible for any tree? */ private fun main() { fun part1(input: List<String>): Int { val grid = getGrid(input) var counter = 0 grid.forEachIndexed { rowIndex, row -> row.forEachIndexed { columnIndex, treeSize -> when { isLeftEdge(rowIndex) -> counter++ isTopEdge(columnIndex) -> counter++ isRightEdge(rowIndex, grid.size) -> counter++ isBottomEdge(columnIndex, grid.size) -> counter++ isVisibleFromLeft(row, columnIndex, treeSize) -> counter++ isVisibleFromTop(grid, rowIndex, columnIndex, treeSize) -> counter++ isVisibleFromRight(row, columnIndex, treeSize) -> counter++ isVisibleFromBottom(grid, rowIndex, columnIndex, treeSize) -> counter++ } } } return counter } fun part2(input: List<String>): Int { val grid = getGrid(input) var max = 0 grid.forEachIndexed { rowIndex, row -> row.forEachIndexed { columnIndex, _ -> val score = getTreeScore(grid, row, rowIndex, columnIndex) if (score > max) { max = score } } } return max } val testInput = readInput("test_input") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("input") println(part1(input)) println(part2(input)) } private fun getGrid(input: List<String>): List<List<Int>> { val grid = mutableListOf<List<Int>>() input.forEach { line -> val ints = line.toCharArray().map { char -> char.digitToInt() } grid.add(ints) } return grid } private fun isLeftEdge(rowIndex: Int) = rowIndex == 0 private fun isTopEdge(columnIndex: Int) = columnIndex == 0 private fun isRightEdge(rowIndex: Int, gridSize: Int) = rowIndex == gridSize - 1 private fun isBottomEdge(columnIndex: Int, gridSize: Int) = columnIndex == gridSize - 1 private fun isVisibleFromLeft(row: List<Int>, columnIndex: Int, treeSize: Int) = row.subList(0, columnIndex).all { it < treeSize } private fun isVisibleFromTop(grid: List<List<Int>>, rowIndex: Int, columnIndex: Int, treeSize: Int) = grid.subList(0, rowIndex).map { it[columnIndex] }.all { it < treeSize } private fun isVisibleFromRight(row: List<Int>, columnIndex: Int, treeSize: Int) = row.subList(columnIndex + 1, row.size).all { it < treeSize } private fun isVisibleFromBottom(grid: List<List<Int>>, rowIndex: Int, columnIndex: Int, treeSize: Int) = grid.subList(rowIndex + 1, grid.size).map { it[columnIndex] }.all { it < treeSize } private fun getLeftScore(row: List<Int>, columnIndex: Int): Int { if (columnIndex == 0) { return 0 } val currentTreeHeight = row[columnIndex] val leftTrees = row.subList(0, columnIndex) var lastVisibleIndex = leftTrees.indexOfLast { it >= currentTreeHeight } if (lastVisibleIndex == -1) { lastVisibleIndex = 0 } return columnIndex - lastVisibleIndex } private fun getTopScore(grid: List<List<Int>>, rowIndex: Int, columnIndex: Int): Int { if (rowIndex == 0) { return 0 } val currentTreeHeight = grid[rowIndex][columnIndex] val column = grid.map { it[columnIndex] } val topTrees = column.subList(0, rowIndex) var lastVisibleIndex = topTrees.indexOfLast { it >= currentTreeHeight } if (lastVisibleIndex == -1) { lastVisibleIndex = 0 } return rowIndex - lastVisibleIndex } private fun getRightScore(row: List<Int>, columnIndex: Int): Int { if (columnIndex == row.size - 1) { return 0 } val currentTreeHeight = row[columnIndex] val rightTrees = row.subList(columnIndex + 1, row.size) var lastVisibleIndex = rightTrees.indexOfFirst { it >= currentTreeHeight } if (lastVisibleIndex == -1) { lastVisibleIndex = row.size - columnIndex - 1 } else { lastVisibleIndex++ } return lastVisibleIndex } private fun getBottomScore(grid: List<List<Int>>, rowIndex: Int, columnIndex: Int): Int { if (rowIndex == grid.size - 1) { return 0 } val currentTreeHeight = grid[rowIndex][columnIndex] val column = grid.map { it[columnIndex] } val bottomTrees = column.subList(rowIndex + 1, grid.size) var lastVisibleIndex = bottomTrees.indexOfFirst { it >= currentTreeHeight } if (lastVisibleIndex == -1) { lastVisibleIndex = grid.size - rowIndex - 1 } else { lastVisibleIndex++ } return lastVisibleIndex } private fun getTreeScore(grid: List<List<Int>>, row: List<Int>, rowIndex: Int, columnIndex: Int): Int = getLeftScore(row, columnIndex) * getTopScore(grid, rowIndex, columnIndex) * getRightScore(row, columnIndex) * getBottomScore(grid, rowIndex, columnIndex)
0
Kotlin
0
0
f6e9a0b6c2b66c28f052d461c79ad4f427dbdfc8
9,145
advent-of-code-2022
Apache License 2.0
src/main/kotlin/tw/gasol/aoc/aoc2022/Day14.kt
Gasol
574,784,477
false
{"Kotlin": 70912, "Shell": 1291, "Makefile": 59}
package tw.gasol.aoc.aoc2022 import java.util.* class Day14 { private val print: Boolean = false private fun parseRockCoordinates(input: String): List<List<Location>> { return input.lines() .filterNot { it.isBlank() } .map { line -> line.split(" -> ").map { try { it.split(",").let { (first, second) -> Location(first.toInt(), second.toInt()) } } catch (exception: IndexOutOfBoundsException) { error("Invalid line \"$it\"") } } } } fun part1(input: String): Int { val structure = Structure(parseRockCoordinates(input)) val sands = structure.pourSands(Location(500, 0)) if (print) { structure.print(true, sands) } return sands.size } fun part2(input: String): Int { val coordinates = parseRockCoordinates(input) val minPosition = coordinates.map { it.sortedBy { it.position }.first() }.sortedBy { it.position }.minOf { it.position } val maxPosition = coordinates.map { it.sortedBy { it.position }.last() }.sortedBy { it.position }.maxOf { it.position } val maxHeight = coordinates.map { it.sortedBy { it.height }.last() }.maxOf { it.height } val floorDepth = 2 val floorCoordinates = coordinates.toMutableList().also { it.add( listOf( Location(minPosition - maxHeight - floorDepth, maxHeight + floorDepth), Location(maxPosition + maxHeight + floorDepth, maxHeight + floorDepth) ) ) } val structure = Structure(floorCoordinates) val sands = structure.pourSands(Location(500, 0)) if (print) { structure.print(true, sands) } return sands.size } } enum class Symbol(private val char: Char) { Air('.'), Rock('#'), Sand('o'), Plus('+'); override fun toString(): String { return char.toString() } } infix fun Int.toward(to: Int): IntProgression { val step = if (this > to) -1 else 1 return IntProgression.fromClosedRange(this, to, step) } data class Location(val position: Int, val height: Int) { fun moveDown(): Location { return Location(position, height + 1) } fun moveLeft(): Location { return Location(position - 1, height) } fun moveRight(): Location { return Location(position + 1, height) } fun moveUp(): Location { return Location(position, height - 1) } } class Structure(coordinates: List<List<Location>>) { private val map = buildMap(coordinates) private fun buildMap(coordinatesList: List<List<Location>>): Map<Int, List<Symbol>> { val map = mutableMapOf<Int, List<Symbol>>() val setRock = { pos: Int, height: Int -> val oldList = map.getOrDefault(pos, emptyList()) val capacity = height + 1 val list = if (oldList.size < capacity) { buildList(capacity) { addAll(oldList) repeat(capacity - size) { add(Symbol.Air) } } } else { oldList } val changedList = list.toMutableList().also { it[height] = Symbol.Rock } map[pos] = changedList } for (coordinateLine in coordinatesList) { for ((from, to) in coordinateLine.windowed(2)) { val isHorizontalLine = from.position != to.position if (isHorizontalLine) { for (position in from.position toward to.position) { setRock(position, from.height) } } else { for (height in from.height toward to.height) { setRock(from.position, height) } } } } return map.toSortedMap(reverseOrder()) } fun print(reverseOrder: Boolean = true, sands: Set<Location>? = null) { val height = map.maxOf { it.value.size } val headerHeight = map.maxOf { it.key.toString().length } val paddingStart = height.toString().length val keys = if (reverseOrder) map.keys.reversed() else map.keys for (i in 0 until headerHeight) { print(" ".repeat(paddingStart + 1)) for (j in keys) { val k = j.toString() print(k.getOrElse(i) { ' ' }) } println() } for (i in 0 toward height) { print(i.toString().padStart(paddingStart) + " ") for (j in keys) { val list = map[j]!! if (j == 500 && i == 0) { print(Symbol.Plus) } else { val containsSand = sands?.contains(Location(j, i)) ?: false if (containsSand) { print(Symbol.Sand) } else { print(list.getOrNull(i) ?: Symbol.Air) } } } println() } } fun pourSands(start: Location): Set<Location> { val sandsMap = mutableMapOf<Location, Boolean>() while (true) { addSand(sandsMap, start) ?: break // print(true, sandsMap.keys.toSet()) } return sandsMap.keys.toSet() } private fun addSand(sandsMap: MutableMap<Location, Boolean>, start: Location): Location? { val queue = PriorityQueue<Location>(compareBy { it.position }) queue.add(start) var getSandOrSymbol = { location: Location -> if (sandsMap.keys.contains(location)) Symbol.Sand else getSymbol(location) } while (queue.isNotEmpty()) { val current = queue.poll() val list = map[current.position] ?: return null if (list.size < current.height) { return null } val symbol = getSandOrSymbol(current) ?: return null // println("${current.position},${current.height.toString().padStart(3)}: $symbol") when (symbol) { Symbol.Sand, Symbol.Rock -> { val left = current.moveLeft() val right = current.moveRight() val leftSymbol = getSandOrSymbol(left) ?: return null val rightSymbol = getSandOrSymbol(right) ?: return null // println("$leftSymbol$symbol$rightSymbol") if ((leftSymbol == Symbol.Sand || leftSymbol == Symbol.Rock) && (rightSymbol == Symbol.Sand || rightSymbol == Symbol.Rock) ) { val sand = current.moveUp() sandsMap[sand] = true if (sand == start) { return null } return sand } if (leftSymbol == Symbol.Air) { queue.add(left) } else { queue.add(right) } } Symbol.Air, Symbol.Plus -> { queue.add(current.moveDown()) } } } return null } private fun getSymbol(location: Location) = map[location.position]?.getOrNull(location.height) }
0
Kotlin
0
0
a14582ea15f1554803e63e5ba12e303be2879b8a
7,709
aoc2022
MIT License
src/Day05.kt
jordanfarrer
573,120,618
false
{"Kotlin": 20954}
fun main() { val day = "Day05" fun parseInstructions(input: List<String>): List<Instruction> { val instructionRegex = Regex(".*?(\\d+).*?(\\d+).*?(\\d+)") return input.map { line -> val match = instructionRegex.find(line) val quantity = match?.groups?.get(1)?.value?.toInt() ?: error("Unable to match quantity") val fromStack = match.groups[2]?.value?.toInt() ?: error("Unable to match from stack") val toStack = match.groups[3]?.value?.toInt() ?: error("Unable to match to stack") Instruction(quantity, fromStack, toStack) } } fun parseStartingStack(input: List<String>): CargoStacks { val stackCount = input.maxOf { it.chunked(4).size } val stacks = mutableListOf<MutableList<String>>() for (i in 1..stackCount) { stacks.add(mutableListOf()) } input.reversed().forEach { line -> line.chunked(4).map { it.trim() }.forEachIndexed { index, column -> if (column.isNotBlank()) { stacks[index].push(column.replace("[", "").replace("]", "")) } } } return stacks } fun executeInstructionsForSingleMove(stacks: CargoStacks, instructions: Iterable<Instruction>): CargoStacks { instructions.forEach { for (i in 1..it.quantity) { val item = stacks[it.fromStack - 1].pop() ?: error("Unable to find item $it, $stacks") stacks[it.toStack - 1].push(item) } } return stacks } fun executeInstructionsForMultiMove(stacks: CargoStacks, instructions: Iterable<Instruction>): CargoStacks { instructions.forEach { val movedItems = stacks[it.fromStack - 1].takeLast(it.quantity) stacks[it.toStack - 1].addAll(movedItems) stacks[it.fromStack - 1] = stacks[it.fromStack - 1].take(stacks[it.fromStack - 1].size - it.quantity).toMutableList() } return stacks } fun part1(input: List<String>): String { val splitIndex = input.indexOfFirst { it.isBlank() } val stacks = parseStartingStack(input.take(splitIndex - 1)) val instructions = parseInstructions(input.takeLast(input.size - splitIndex - 1)) executeInstructionsForSingleMove(stacks, instructions) return stacks.joinToString(separator = "", transform = { it.peek() ?: "" }) } fun part2(input: List<String>): String { val splitIndex = input.indexOfFirst { it.isBlank() } val stacks = parseStartingStack(input.take(splitIndex - 1)) val instructions = parseInstructions(input.takeLast(input.size - splitIndex - 1)) executeInstructionsForMultiMove(stacks, instructions) return stacks.joinToString(separator = "", transform = { it.peek() ?: "" }) } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val part1Result = part1(testInput) println("Part 1 (test): $part1Result") check(part1Result == "CMZ") val part2Result = part2(testInput) println("Part 2 (test): $part2Result") check(part2Result == "MCD") val input = readInput(day) println(part1(input)) println(part2(input)) } data class Instruction(val quantity: Int, val fromStack: Int, val toStack: Int) typealias CargoStacks = MutableList<MutableList<String>>
0
Kotlin
0
1
aea4bb23029f3b48c94aa742958727d71c3532ac
3,486
advent-of-code-2022-kotlin
Apache License 2.0
src/jvmMain/kotlin/day08/initial/Day08.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day08.initial import java.io.File fun main() { // solvePart1() ///// Solution: 19637, Time: 20:30 solvePart2() ///// Solution: 19637, Time: 20:30 } fun solvePart1() { // val input = File("src/jvmMain/kotlin/day08/input/input_part1_test.txt") val input = File("src/jvmMain/kotlin/day08/input/input.txt") val lines = input.readLines() val directionList = lines[0].trim().map(::Direction) val nodeList = lines.subList(2, lines.size).map(::Node) var currentNode = nodeList[0] var directionIndex = 0 var count = 0 while (!currentNode.final) { val direction = directionList[directionIndex] currentNode = when (direction) { Direction.Left -> nodeList.first { it.name == currentNode.leftName } Direction.Right -> nodeList.first { it.name == currentNode.rightName } } if (directionIndex + 1 >= directionList.size) { directionIndex = 0 } else { directionIndex++ } count++ val newDirection = directionList[directionIndex] println("Node: $currentNode, step: $count, directionIndex: ${directionIndex}, newDirection: $newDirection") } println(count) } fun solvePart2() { // val input = File("src/jvmMain/kotlin/day08/input/input_part2_test.txt") val input = File("src/jvmMain/kotlin/day08/input/input.txt") val lines = input.readLines() val directionList = lines[0].trim().map(::Direction) val nodeList = lines.subList(2, lines.size).map(::Node) val initialNodeList = nodeList.filter { it.name.endsWith("A") } var interimResult = InterimResult( currentNodeList = initialNodeList, directionIndex = 0, count = 0 ) println("Start nodes: ${initialNodeList}") while (!interimResult.currentNodeList.all { it.name.endsWith("Z") }) { val newNodeList = interimResult.currentNodeList.map { currentNode -> operate( node = currentNode, directionIndex = interimResult.directionIndex, count = interimResult.count, directionList = directionList, nodeList = nodeList ) } val newDirectionIndex = if (interimResult.directionIndex + 1 >= directionList.size) { 0 } else { interimResult.directionIndex + 1 } val newCount = interimResult.count + 1 interimResult = InterimResult( currentNodeList = newNodeList, directionIndex = newDirectionIndex, count = newCount ) println(interimResult) } println(interimResult.count) } data class InterimResult( val currentNodeList: List<Node>, val directionIndex: Int, val count: Int ) private fun operate( node: Node, directionIndex: Int, count: Int, directionList: List<Direction>, nodeList: List<Node> ): Node { var newNode = node // while (!newNode.final) { val direction = directionList[directionIndex] newNode = when (direction) { Direction.Left -> nodeList.first { it.name == newNode.leftName } Direction.Right -> nodeList.first { it.name == newNode.rightName } } val newDirection = directionList[directionIndex] // println("Node: $newNode, step: $count, directionIndex: ${directionIndex}, newDirection: $newDirection") // } return newNode } fun Node(line: String): Node { val (name, directions) = line.split("=").map { it.trim() } val (left, right) = directions.split(", ").map { it.replace("(", "").replace(")", "").trim() } return Node( name = name, leftName = left, rightName = right ) } data class Node( val name: String, val leftName: String, val rightName: String ) { val final: Boolean = name == "ZZZ" } fun Direction(char: Char): Direction = when (char) { 'L' -> Direction.Left 'R' -> Direction.Right else -> error("Invalid direction character: $char") } enum class Direction { Left, Right; }
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
4,100
advent-of-code
MIT License
src/Day02.kt
janbina
157,854,025
false
null
import kotlin.test.assertEquals object Day02 { fun part1(input: List<String>): Int { var two = 0 var three = 0 input .map { str -> str.groupingBy { it }.eachCount() } .map { it.values } .forEach { counts -> if (counts.any { it == 2 }) two++ if (counts.any { it == 3 }) three++ } return two * three } fun part2(input: List<String>): String { val pair = input.asSequence().uniquePairs() .filter { stringDistance(it.first, it.second) == 1 } .first() return pair.first.zip(pair.second) .filter { it.first == it.second } .map { it.first } .joinToString(separator = "") } } fun main(args: Array<String>) { val input = getInput(2).readLines() assertEquals(6000, Day02.part1(input)) assertEquals("pbykrmjmizwhxlqnasfgtycdv", Day02.part2(input)) } private fun stringDistance(a: String, b: String): Int { return a.zip(b).count { it.first != it.second } }
0
Kotlin
0
0
522d93baf9ff4191bc2fc416d95b06208be32325
1,073
advent-of-code-2018
MIT License
src/Day04.kt
iProdigy
572,297,795
false
{"Kotlin": 33616}
fun main() { fun part1(input: List<String>): Int { return parse(input).count { (a, b) -> a containsAll b || b containsAll a } } fun part2(input: List<String>): Int { return parse(input).count { (a, b) -> a containsAny b } } // 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)) // 657 println(part2(input)) // 938 } private fun parse(input: List<String>) = input .map { it.split(',') } .map { (left, right) -> convert(left) to convert(right) } private fun convert(part: String) = part.split('-').let { it[0].toInt()..it[1].toInt() }
0
Kotlin
0
1
784fc926735fc01f4cf18d2ec105956c50a0d663
772
advent-of-code-2022
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day7.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.readInputLines object Day7 : Day { override val input = buildTree(parseCommands(readInputLines(7))) override fun part1() = input.dirSizes().filter { it <= 100000 }.sum() override fun part2() = input.dirSizes().run { filter { it >= 30000000 - (70000000 - max()) }.min() } class Directory( val parent: Directory?, var directories: Map<String, Directory> = emptyMap(), var files: List<Long> = emptyList() ) { fun root(): Directory { var cwd = this while (cwd.parent != null) { cwd = cwd.parent!! } return cwd } fun dirSizes(cwd: Directory = this): List<Long> = buildList { add(cwd.size()) cwd.directories.values.forEach { addAll(dirSizes(it)) } } private fun size(): Long = directories.values.sumOf { it.size() } + files.sum() } sealed interface Command { class CD(private val path: String) : Command { fun navigate(cwd: Directory): Directory { return when (path) { "/" -> cwd.root() ".." -> cwd.parent!! else -> cwd.directories.getValue(path) } } } class LS(private val sdtout: List<String>) : Command { fun update(current: Directory) { current.directories = subdirectories(current) current.files = sizes() } private fun sizes(): List<Long> { return sdtout .filter { !it.startsWith("dir") } .map { it.split(" ").first().toLong() } } private fun subdirectories(current: Directory): Map<String, Directory> { return sdtout .filter { it.startsWith("dir") } .map { it.substring(4).trim() } .associateWith { Directory(current) } } } } private fun parseCommands(lines: List<String>): List<Command> { return buildList { lines.forEachIndexed { i, s -> when { s.startsWith("$ cd") -> add(Command.CD(s.substring(4).trim())) s.startsWith("$ ls") -> add(Command.LS(lines.drop(i + 1).takeWhile { it.first() != '$' })) } } } } private fun buildTree(commands: List<Command>): Directory { var cwd = Directory(null) commands.forEach { when (it) { is Command.CD -> cwd = it.navigate(cwd) is Command.LS -> it.update(cwd) } } return cwd.root() } }
1
Kotlin
0
0
63f48d4790f17104311b3873f321368934060e06
2,851
aoc2022
MIT License
src/main/kotlin/twentytwentytwo/Day7.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import twentytwentytwo.File.Companion.ROOT import twentytwentytwo.File.Companion.isDir fun main() { val input = {}.javaClass.getResource("input-7.txt")!!.readText().linesFiltered { it.isNotEmpty() && !it.startsWith("$ ls") } val day = Day7(input) println(day.part1()) println(day.part2()) } class Day7(input: List<String>) { init { var current = ROOT; input.forEach { line -> when { line.startsWith("$ cd") -> { current = current.changeDirectory(line.split(" ")[2]) } else -> current.addChild(File.of(line)) } } } fun part1(): Int { return ROOT.getAllFiles().filter { isDir(it) }.filter { it.dirSize() <= 100000 }.sumOf { it.dirSize() } } fun part2(): Int { val needed = 70000000 - ROOT.dirSize() return ROOT.getAllFiles().filter { isDir(it) }.filter { it.dirSize() >= 30000000 - needed } .minOf { it.dirSize() } } } class File(private val name: String, val size: Int) { private var parent: File = ROOT private var children: MutableList<File> = mutableListOf() fun addChild(node: File) { children.add(node) node.parent = this } fun changeDirectory(name: String): File { return when (name) { "/" -> ROOT ".." -> parent else -> children.first { it.name == name } } } fun dirSize(): Int = if (isDir(this)) children.sumOf { it.dirSize() } else size fun getAllFiles(): List<File> = (this.children.map { it.getAllFiles() }.flatten() + this) companion object { val ROOT = File("/", 0) fun isDir(file: File): Boolean = file.size == 0 fun of(rawInput: String): File = rawInput.split(" ").let { (size, name) -> File(name, if (size == "dir") 0 else size.toInt()) } } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
1,970
aoc202xkotlin
The Unlicense
src/Day09.kt
wgolyakov
572,463,468
false
null
import kotlin.math.absoluteValue import kotlin.math.sign fun main() { fun part1(input: List<String>): Int { var x = 0 var y = 0 var a = 0 var b = 0 val tailPositions = mutableSetOf(a to b) for (line in input) { val direction = line[0] val steps = line.substring(2).toInt() for (s in 0 until steps) { when (direction) { 'R' -> x++ 'L' -> x-- 'U' -> y++ 'D' -> y-- } if ((x - a).absoluteValue > 1 || (y - b).absoluteValue > 1) { a += (x - a).sign b += (y - b).sign } tailPositions.add(a to b) } } return tailPositions.size } fun part2(input: List<String>): Int { val x = IntArray(10) val y = IntArray(10) val tailPositions = mutableSetOf(x.last() to y.last()) for (line in input) { val direction = line[0] val steps = line.substring(2).toInt() for (s in 0 until steps) { when (direction) { 'R' -> x[0]++ 'L' -> x[0]-- 'U' -> y[0]++ 'D' -> y[0]-- } for ((i, j) in (0..9).windowed(2)) { if ((x[i] - x[j]).absoluteValue > 1 || (y[i] - y[j]).absoluteValue > 1) { x[j] += (x[i] - x[j]).sign y[j] += (y[i] - y[j]).sign } } tailPositions.add(x.last() to y.last()) } } return tailPositions.size } val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
1,516
advent-of-code-2022
Apache License 2.0
year2022/src/main/kotlin/net/olegg/aoc/year2022/day7/Day7.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2022.day7 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2022.DayOf2022 import net.olegg.aoc.year2022.day7.Day7.Node.Dir import net.olegg.aoc.year2022.day7.Day7.Node.File /** * See [Year 2022, Day 7](https://adventofcode.com/2022/day/7) */ object Day7 : DayOf2022(7) { /*override val localData: String? get() = """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent()*/ override fun first(): Any? { return solve { this.map { it.size } .filter { it <= 100000L } .sum() } } override fun second(): Any? { return solve { val rootSize = maxOf { it.size } val unused = 70000000L - rootSize val toDelete = 30000000L - unused this.map { it.size } .filter { it >= toDelete } .min() } } private fun solve(action: List<Dir>.() -> Long): Long { val root = Dir( name = "/", parent = null, content = mutableListOf(), ) var current = root val linesQueue = ArrayDeque(lines) while (linesQueue.isNotEmpty()) { val command = linesQueue.removeFirst() when { command == "$ cd /" -> { current = root } command == "$ cd .." -> { current = current.parent!! } command.startsWith("$ cd ") -> { val destination = command.replace("$ cd ", "") current = current.content.filterIsInstance<Dir>().first { it.name == destination } } command == "$ ls" -> { while (linesQueue.isNotEmpty() && !linesQueue.first().startsWith("$")) { val output = linesQueue.removeFirst().split(" ").toPair() current.content += when (output.first) { "dir" -> Dir( name = output.second, parent = current, content = mutableListOf(), ) else -> File( name = output.second, parent = current, size = output.first.toLong(), ) } } } else -> error("Unknown command $command") } } return root.flattenDirs().action() } private fun Dir.flattenDirs(): List<Dir> { return listOf(this) + content.filterIsInstance<Dir>().flatMap { it.flattenDirs() } } sealed interface Node { val name: String val size: Long val parent: Dir? data class Dir( override val name: String, override val parent: Dir?, val content: MutableList<Node>, ) : Node { override val size: Long by lazy { content.sumOf { it.size } } } data class File( override val name: String, override val parent: Dir?, override val size: Long, ) : Node } } fun main() = SomeDay.mainify(Day7)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
3,129
adventofcode
MIT License
src/Day01.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
fun main() { fun parseGroups(input: List<String>): List<List<String>> { val splitIndex = input.indexOf("") if (splitIndex == -1) return listOf(input) val first: List<String> = input.subList(0, splitIndex) val remainder: List<List<String>> = parseGroups(input.subList(splitIndex+1, input.size)) return remainder.plusElement(first) } fun part1(input: List<String>): Int { return parseGroups(input).maxOf { group -> group.sumOf { it.toInt() } } } fun part2(input: List<String>): Int { return input.joinToString(",") .replace(",,", ";") .split(';') .map { calList -> calList.split(',') .sumOf { calString -> calString.toInt() } }.sortedDescending() .subList(0, 3) .sum() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
1,080
aoc2022
Apache License 2.0
src/main/kotlin/net/voldrich/aoc2021/Day8.kt
MavoCz
434,703,997
false
{"Kotlin": 119158}
package net.voldrich.aoc2021 import net.voldrich.BaseDay // https://adventofcode.com/2021/day/8 fun main() { Day8().run() } /* 1 = 2 4 = 4 7 = 3 8 = 7 5 = 5 2 = 5 3 = 5 6 = 6 9 = 6 0 = 6 **/ class Day8 : BaseDay() { override fun task1() : Int { val signalEntries = parseEntries() return signalEntries.sumOf { it.countUniqueNumbers() } } override fun task2() : Int { val signalEntries = parseEntries() return signalEntries.sumOf {it. decodeOutputNumber() } } private fun sortString(str: String) : String { return str.toCharArray().sorted().joinToString("") } private fun parseEntries() : List<SignalEntry> { return input.lines().map { line -> val lineSplit = line.split("|") SignalEntry( lineSplit[0].trim().split(" ").map { sortString(it) }, lineSplit[1].trim().split(" ").map { sortString(it) } ) } } private class SignalEntry(val patterns: List<String>, val output: List<String>) { fun countUniqueNumbers() : Int { return output.count { it.length == 2 || it.length == 4 || it.length == 3 || it.length == 7 } } fun decodeOutputNumber() : Int { // maps number to its code val p1 = getSinglePatternOfSize(2) val p4 = getSinglePatternOfSize(4) val p7 = getSinglePatternOfSize(3) val p8 = getSinglePatternOfSize(7) val p235 = getPatternOfSize(5, 3) val p069 = getPatternOfSize(6, 3) // 3 contains a single shared line with 1 val p3 = p235.single { intersect(it, p1) == p1 } val p25 = p235.filter { intersect(it, p1) != p1 } // 6 minus 1 == 1. others == 2 val p6 = p069.single { minus(p1, it).length == 1 } val p09 = p069.filter { minus(p1, it).length != 1 } val se = minus (minus(p6, p4), p3) // zero contains E val p0 = p09.single { it.contains(se) } val p9 = p09.single { !it.contains(se) } // 2 contains E val p2 = p25.single { it.contains(se) } val p5 = p25.single { !it.contains(se) } val codeToNumberMap = mapOf( p1 to '1', p2 to '2', p3 to '3', p4 to '4', p5 to '5', p6 to '6', p7 to '7', p8 to '8', p9 to '9', p0 to '0', ) return output.map { codeToNumberMap[it] }.joinToString ("").toInt() } private fun minus(first: String, second: String): String { return first.toCharArray().toSet().minus(second.toCharArray().toSet()).joinToString("") } private fun intersect(first: String, second: String): String { val intersect = first.toCharArray().intersect(second.toCharArray().toSet()) return intersect.toCharArray().joinToString("") } private fun getPatternOfSize(size: Int, expectedSize: Int) : List<String> { val list = patterns.filter { it.length == size }.toList() if (list.size != expectedSize) throw Exception("More then $expectedSize results $list with size $size") return list } private fun getSinglePatternOfSize(size: Int) : String { return getPatternOfSize(size, 1).first() } } }
0
Kotlin
0
0
0cedad1d393d9040c4cc9b50b120647884ea99d9
3,516
advent-of-code
Apache License 2.0
src/test/kotlin/Day5Test.kt
corentinnormand
725,992,109
false
{"Kotlin": 40576}
import org.junit.jupiter.api.Test import kotlin.math.min class Day5Test { @Test fun test() { val input = Day5().readFile("day5.txt").split("\n\n") val seeds = input[0].split(":")[1].split(" ") .filter { it != "" } .map { it.trim().toLong() } val maps = input.subList(1, input.size) .map { it.split("\n") } .map { it.subList(1, it.size) } .map { it.map { i -> i.split(" ") .map { it.trim().toLong() } } .map { Triple(it[0], it[1], it[2]) } } .toList() fun mapSeed(seed: Long, map: List<Triple<Long, Long, Long>>): Long { var currentSeed = seed for (v in map) { if ((v.second..<v.second + v.third).contains(seed)) { currentSeed += (v.first - v.second) } } return currentSeed } fun mapSeed2(seed: Long, map: List<Triple<Long, Long, Long>>): Long { var currentSeed = seed for (v in map) { if ((v.first..<v.first + v.third).contains(seed)) { currentSeed -= (v.first - v.second) } } return currentSeed } val maxRes = maps.last().maxOf { it.first + it.third } val minRes = maps.last().minOf { it.first } println(maxRes) println(minRes) val seeds2 = seeds .chunked(2) .map { (it[0]..<it[0] + it[1]) } val results = mutableSetOf<Long>() var min = Long.MAX_VALUE for (range in seeds2) { for (seed in range) { var currentSeed = seed for (i in maps) { currentSeed = mapSeed(currentSeed, i) } if (min > currentSeed) min = currentSeed } } for (i in 100_000_000_000 downTo 0) { var value = i for (map in maps.asReversed()) { val mapSeed2 = mapSeed2(value, map) if (mapSeed2 < 0) { break } value = mapSeed2 } if (seeds2.any { it.contains(value) }) { println(i) return } } } }
0
Kotlin
0
0
2b177a98ab112850b0f985c5926d15493a9a1373
2,435
aoc_2023
Apache License 2.0
src/Day03.kt
gomercin
572,911,270
false
{"Kotlin": 25313}
/* * searches I needed to make: * kotlin list intersection * kotlin list split * kotlin string to list of chars * kotlin ch to ascii * */ fun main() { class Rucksack { var compartment1: List<Char> var compartment2: List<Char> var allContents: List<Char> constructor(contents: String) { allContents = contents.toList() val compartments = contents.chunked(contents.length / 2) compartment1 = compartments[0].toList() compartment2 = compartments[1].toList() } fun getCommonElement(): Char { return compartment1.intersect(compartment2).toList()[0] } } fun getPriority(ch: Char): Int { return if (ch.isLowerCase()) { ch.code - 'a'.code + 1 } else { // this might be unneeded, I don't remember if "A" was just after "z" // if that's the case, no lowercase check was necessary and we could use the above block ch.code - 'A'.code + 27 } } fun part1(input: List<String>): Int { var totalPriority = 0 for (line in input) { val rucksack = Rucksack(line) val commonElement = rucksack.getCommonElement() // println("common element is: ${commonElement}") totalPriority += getPriority(commonElement) } return totalPriority } fun part2(input: List<String>): Int { var totalPriority = 0 var commonElements = listOf<Char>() var counter = 0 for (line in input) { val rucksack = Rucksack(line) if (counter == 0) { commonElements = rucksack.allContents } else { commonElements = commonElements.intersect(rucksack.allContents).toList() } if (counter == 2) { counter = -1 //to increment to 0 after if, blergh, ugly // here we should have a single element totalPriority += getPriority(commonElements[0]) } counter++ } return totalPriority } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
30f75c4103ab9e971c7c668f03f279f96dbd72ab
2,229
adventofcode-2022
Apache License 2.0
src/Day03.kt
ajspadial
573,864,089
false
{"Kotlin": 15457}
fun main() { fun calcPriority (c: Char): Int { return if (c in 'a'..'z') c.code - 'a'.code + 1 else c.code - 'A'.code + 27 } fun part1(input: List<String>): Int { var score = 0 for (line in input) { val firstCompartment = line.substring(0..line.length/2 - 1) val secondCompartment = line.substring(line.length/2) for (element in firstCompartment) { if (element in secondCompartment) { score += calcPriority(element) break } } } return score } fun part2(input: List<String>): Int { var score = 0 for (i in 0..input.size / 3 - 1) { val rucksack0 = input[i * 3] val rucksack1 = input[i * 3 + 1] val rucksack2 = input[i * 3 + 2] for (element in rucksack0) { if (element in rucksack1 && element in rucksack2) { score += calcPriority(element) break } } } return score } // 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
ed7a2010008be17fec1330b41adc7ee5861b956b
1,415
adventofcode2022
Apache License 2.0
Coding Challenges/Advent of Code/2021/Day 8/part2.kt
Alphabeater
435,048,407
false
{"Kotlin": 69566, "Python": 5974}
import java.io.File import java.util.Scanner import kotlin.math.pow /* dddd x0x0x0x0 e a x6 x1 e a x6 x1 ffff -> x2x2x2x2 g b x5 x3 g b x5 x3 cccc x4x4x4x4 */ var stv = mutableMapOf<String, Int>() //string to value var sitl = mutableMapOf<Int, Char>() //subindex to letter: subindex from the x in the pic -> corresponding letter fun cleanFun(input: List<String>): List<String> { val output = mutableListOf<String>() for (item in input) { output.add(item.toMutableList().sorted().joinToString("")) } return if (input.size > 4) { output.sortedBy{ it.length } } else output } fun addValues(input: List<String>) { //frequency of letters: x6=4, x7=6, x4=9 val letters = IntArray(7) for (i in 'a'..'g') { for (word in input) { if (i in word) letters[i - 'a']++ } } for (i in letters.indices) { when (letters[i]) { 4 -> sitl[5] = 'a' + i 6 -> sitl[6] = 'a' + i 9 -> sitl[3] = 'a' + i } } for (item in input) { when (item.length) { 2 -> stv[item] = 1 3 -> stv[item] = 7 4 -> stv[item] = 4 7 -> stv[item] = 8 } } sitl[1] = input[0].notInLetterMap() sitl[0] = input[1].notInLetterMap() sitl[2] = input[2].notInLetterMap() sitl[4] = input[3].notInLetterMap() stv[changeIndexToString("013456")] = 0 stv[changeIndexToString("01245")] = 2 stv[changeIndexToString("01234")] = 3 stv[changeIndexToString("02346")] = 5 stv[changeIndexToString("023456")] = 6 stv[changeIndexToString("012346")] = 9 } fun String.notInLetterMap(): Char { for (char in this) { if (!sitl.containsValue(char)) return char } return 'z' //never reached } fun changeIndexToString(numbers: String): String { var word = "" for (number in numbers) { word += sitl[number.digitToInt()] } return word.toMutableList().sorted().joinToString("") } fun main() { val file = File("src/input.txt") val scanner = Scanner(file) var sum = 0 while (scanner.hasNext()) { val (input, output) = scanner.nextLine().split(" | ") val inputClean = cleanFun(input.split(' ')) val outputClean = cleanFun(output.split(' ')) var partialSum = 0 addValues(inputClean) for ((e, item) in outputClean.reversed().withIndex()) { partialSum += (10.0.pow(e) * stv[item]!!).toInt() } sum += partialSum stv.clear() sitl.clear() } println(sum) }
0
Kotlin
0
0
05c8d4614e025ed2f26fef2e5b1581630201adf0
2,711
Archive
MIT License
src/Day07/Day07.kt
rooksoto
573,602,435
false
{"Kotlin": 16098}
package Day07 import profile import readInputActual import readInputTest private const val DAY = "Day07" private const val ROOT = "ROOT" private const val PD = "/" private const val TOTAL_SPACE: Int = 70000000 private const val NEEDED_SPACE: Int = 30000000 var fileSystem: MutableMap<String, Directory> = mutableMapOf() var workingPath: String = "" fun main() { fun part1(input: List<String>): Int { reset() input.populateFileSystem(fileSystem) return fileSystem.toTotalSizes() .filter { it <= 100000 } .sum() } fun part2(input: List<String>): Int { reset() input.populateFileSystem(fileSystem) val unUsedSpace = TOTAL_SPACE - (fileSystem[ROOT]?.totalSize() ?: 0) return fileSystem.toTotalSizes() .sorted() .find { it + unUsedSpace > NEEDED_SPACE } ?: 0 } val testInput = readInputTest(DAY) val input = readInputActual(DAY) check(part1(testInput) == 95437) profile(shouldLog = true) { println("Part 1: ${part1(input)}") } // Answer: 1454188 @ 38ms check(part2(testInput) == 24933642) profile(shouldLog = true) { println("Part 2: ${part2(input)}") } // Answer: 4183246 @ 12ms } private fun reset() { workingPath = "" fileSystem = mutableMapOf() } private fun List<String>.populateFileSystem( fileSystem: MutableMap<String, Directory> ) = splitWhen { s -> s.startsWith("$") }.map { payload -> val command = payload.parseCommand() when (command.first()) { "cd" -> { workingPath = when (val key: String = command.last()) { ".." -> workingPath.dropPathSegment() PD -> ROOT else -> workingPath.addPathSegment(key) } } "ls" -> { payload .drop(1) .groupBy { it.startsWith("dir") }.let { map -> val fileSize = map[false]?.sumOf { it.split(" ").first().toInt() } ?: 0 val subDirectoryNames = map[true]?.map { val name = it.split(" ").last() workingPath.addPathSegment(name) } ?: emptyList() fileSystem[workingPath] = Directory( workingPath, fileSize, subDirectoryNames ) } } } } private fun <T> List<T>.splitWhen( predicate: (T) -> Boolean ): List<List<T>> { val result = mutableListOf<List<T>>() indices.forEach { index -> if (predicate(this[index])) { val nextIndex: Int = subList(index + 1, size) .indexOfFirst { predicate(it) }.let { nIndex -> if (nIndex == -1) size else nIndex + (index + 1) } result.add(subList(index, nextIndex)) } } return result } private fun String.addPathSegment(segment: String): String = split(PD).plus(segment).joinToString(PD) private fun String.dropPathSegment(): String = split(PD).dropLast(1).joinToString(PD) private fun List<String>.parseCommand() = first().split(" ").drop(1) private fun Directory.totalSize(): Int = size + childPaths.sumOf { c -> fileSystem[c]?.totalSize() ?: 0 } private fun Map<String, Directory>.toTotalSizes(): List<Int> = map { it.value }.map { it.totalSize() } data class Directory( val path: String, var size: Int, val childPaths: List<String> )
0
Kotlin
0
1
52093dbf0dc2f5f62f44a57aa3064d9b0b458583
3,652
AoC-2022
Apache License 2.0
src/main/kotlin/day19/Day19.kt
jakubgwozdz
571,298,326
false
{"Kotlin": 85100}
package day19 import Stack import execute import parseRecords import readAllText fun part1(input: String) = input.parseRecords(regex, ::parse) .map { it.id to it.score(24) } .sumOf { (id, score) -> id * score } fun part2(input: String) = input.parseRecords(regex, ::parse) .take(3) .map { it.score(32) } .fold(1L, Long::times) private data class Blueprint( val id: Int, val oreRobotOres: Long, val clayRobotOres: Long, val obsidianRobotOres: Long, val obsidianRobotClays: Long, val geodeRobotOres: Long, val geodeRobotObsidians: Long, ) { val maxOreRequired = maxOf(oreRobotOres, clayRobotOres, obsidianRobotOres, geodeRobotOres) } private data class State( val oreRobots: Long = 1, val clayRobots: Long = 0, val obsidianRobots: Long = 0, val geodeRobots: Long = 0, val ores: Long = 0, val clays: Long = 0, val obsidians: Long = 0, val geodes: Long = 0, val timeLeft: Int, ) private fun State.score() = geodes + geodeRobots * timeLeft private enum class Order { OreRobot, ClayRobot, ObsidianRobot, GeodeRobot } private fun Blueprint.exits(state: State) = if (!canBuildMoreGeodeRobots(state)) emptyList() else possibleOrders(state).map { (order, time) -> var ores = state.ores + state.oreRobots * time var clays = state.clays + state.clayRobots * time var obsidians = state.obsidians + state.obsidianRobots * time var geode = state.geodes + state.geodeRobots * time var oreRobots = state.oreRobots var clayRobots = state.clayRobots var obsidianRobots = state.obsidianRobots var geodeRobots = state.geodeRobots val timeLeft = state.timeLeft - time when (order) { Order.OreRobot -> { ores -= oreRobotOres oreRobots++ } Order.ClayRobot -> { ores -= clayRobotOres clayRobots++ } Order.ObsidianRobot -> { ores -= obsidianRobotOres clays -= obsidianRobotClays obsidianRobots++ } Order.GeodeRobot -> { ores -= geodeRobotOres obsidians -= geodeRobotObsidians geodeRobots++ } } check(ores >= 0) check(clays >= 0) check(obsidians >= 0) check(geode >= 0) check(timeLeft >= 0) State( oreRobots, clayRobots, obsidianRobots, geodeRobots, ores, clays, obsidians, geode, timeLeft, ) } private fun Blueprint.canBuildMoreGeodeRobots(state: State): Boolean { val maxPossibleOres = state.ores + state.oreRobots * state.timeLeft + state.timeLeft * state.timeLeft / 2 val maxPossibleObsidians = state.obsidians + state.obsidianRobots * state.timeLeft + state.timeLeft * state.timeLeft / 2 return state.timeLeft > 0 && geodeRobotOres <= maxPossibleOres && geodeRobotObsidians <= maxPossibleObsidians } private fun Blueprint.possibleOrders(state: State) = buildList { val timeToBuildGeodeRobot = if (state.obsidianRobots == 0L) state.timeLeft + 1 else if (geodeRobotOres <= state.ores && geodeRobotObsidians <= state.obsidians) 1 else maxOf( 1L, (geodeRobotOres - state.ores - 1) / state.oreRobots + 2L, (geodeRobotObsidians - state.obsidians - 1) / state.obsidianRobots + 2L ).toInt() val timeToBuildObsidianRobot = if (state.clayRobots == 0L) state.timeLeft + 1 else if (obsidianRobotOres <= state.ores && obsidianRobotClays <= state.clays) 1 else maxOf( 1L, (obsidianRobotOres - state.ores - 1) / state.oreRobots + 2L, (obsidianRobotClays - state.clays - 1) / state.clayRobots + 2L ).toInt() val timeToBuildClayRobot = if (clayRobotOres <= state.ores) 1 else if (clayRobotOres <= state.ores) 1 else maxOf( 1L, (clayRobotOres - state.ores - 1) / state.oreRobots + 2L, ).toInt() val timeToBuildOreRobot = if (oreRobotOres <= state.ores) 1 else if (oreRobotOres <= state.ores) 1 else maxOf( 1L, (oreRobotOres - state.ores - 1) / state.oreRobots + 2L, ).toInt() if (timeToBuildGeodeRobot == 1) add(Order.GeodeRobot to timeToBuildGeodeRobot) else { if (timeToBuildGeodeRobot < state.timeLeft) add(Order.GeodeRobot to timeToBuildGeodeRobot) if (timeToBuildObsidianRobot < state.timeLeft && state.obsidianRobots < geodeRobotObsidians) add(Order.ObsidianRobot to timeToBuildObsidianRobot) if (timeToBuildClayRobot < state.timeLeft && state.clayRobots < obsidianRobotClays) add(Order.ClayRobot to timeToBuildClayRobot) if (timeToBuildOreRobot < state.timeLeft && state.oreRobots < maxOreRequired) add(Order.OreRobot to timeToBuildOreRobot) } } private fun Blueprint.score(time: Int): Long { var best = State(timeLeft = time) val stack = Stack<State>() .apply { offer(best) } while (stack.isNotEmpty()) { val state = stack.poll() if (state.score() > best.score()) best = state this.exits(state).forEach(stack::offer) } return best.score() } private val regex = "Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.".toRegex() private fun parse(matchResult: MatchResult) = matchResult.destructured.let { (a, b, c, d, e, f, g) -> Blueprint(a.toInt(), b.toLong(), c.toLong(), d.toLong(), e.toLong(), f.toLong(), g.toLong()) } fun main() { val input = readAllText("local/day19_input.txt") val test = """ Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian. Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian. """.trimIndent() execute(::part1, test, 33) execute(::part1, input, 817) execute(::part2, test, 56 * 62) execute(::part2, input, 4216) }
0
Kotlin
0
0
7589942906f9f524018c130b0be8976c824c4c2a
6,236
advent-of-code-2022
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions59.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.Queue import com.qiaoyuang.algorithm.round0.Stack fun test59() { printlnResult1(intArrayOf(2, 3, 4, 2, 6, 2, 5, 1), 3) printlnResult1(intArrayOf(1, 3, 4, 7, 9, 1, 9, 8), 2) printlnResult1(intArrayOf(2, 2, 2, 2, 3, 6, 2, 5, 1), 3) printlnResult2(intArrayOf(2, 3, 4, 2, 6, 2, 5, 1)) } /** * Questions 59-1: Given an IntArray and a number, the number present the size of a slide window, * find all the largest values in these slide window. */ private fun IntArray.findAllLargestNumbers(n: Int): IntArray { require(n in 1..size) { "Illegal parameters" } if (n == 1) return this val result = IntArray(size - n + 1) val queue = Queue<Int>() for (i in 0..< n) this[i].let { queue.enqueue(it) if (it > queue.last) queue.dequeue() } result[0] = queue.last for (i in 1..result.lastIndex) { while (n == queue.size || queue.first > queue.last) queue.dequeue() val newElement = this[i + n - 1] queue.enqueue(newElement) while (newElement > queue.last) queue.dequeue() result[i] = queue.last } return result } private fun printlnResult1(array: IntArray, n: Int) = println("The IntArray is ${array.toList()}, the size of window is $n, the all max values are: ${array.findAllLargestNumbers(n).toList()}") /** * Questions 59-2: Implementing a queue that contain a max() function could find the max value, and the time complexities of function max, pop, push are O(1) */ private class MaxStack<T : Comparable<T>> { private val maxStack = Stack<T>() private val elementStack = Stack<T>() fun push(t: T) { elementStack.push(t) if (maxStack.isEmpty || maxStack.top() <= t) maxStack.push(t) } fun max(): T = maxStack.top() fun pop(): T { val t = elementStack.pop() if (t == maxStack.top()) maxStack.pop() return t } val isEmpty get() = elementStack.isEmpty val size get() = elementStack.size val top: T get() = elementStack.top() } private fun printlnResult2(numbers: IntArray) { println("Pushing the numbers: ${numbers.toList()} to our Stack") val stack = MaxStack<Int>() numbers.forEach { stack.push(it) println("Push $it, top: ${stack.top}, max: ${stack.max()}") } while (stack.size > 1) { val pop = stack.pop() println("Pop $pop, top: ${stack.top}, max: ${stack.max()}") } }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,600
Algorithm
Apache License 2.0
leetcode2/src/leetcode/HammingDistance.kt
hewking
68,515,222
false
null
package leetcode /** * 461. 汉明距离 * Created by test * Date 2019/5/30 1:26 * Description * https://leetcode-cn.com/problems/hamming-distance/ * 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 给出两个整数 x 和 y,计算它们之间的汉明距离。 注意: 0 ≤ x, y < 231. 示例: 输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。 */ object HammingDistance { @JvmStatic fun main(args : Array<String>) { val s = Solution() // print(s.toB(5)) val count = s.hammingDistance(1,4) println("count:$count") } class Solution { /** * 思路: * 1.先进行异或操作,所得结果中的1的个数即为所得 * 2.统计1的个数,通过mod 2 如果为0则是二进制结果中的1 * 3.循环往复 */ fun hammingDistance2(x : Int,y : Int) : Int { var r = x.xor(y) var count = 0 while (r > 0) { count += r.rem(2) r = r.shr(1) } return count } /** * 土办法,先计算整数的二进制,然后累加不同的数的个数 */ fun hammingDistance(x: Int, y: Int): Int { val s1 = toB(x) val s2 = toB(y) var count = 0 val s = if (s1.length > s2.length) s1 else s2 val s3 = if (s1.length > s2.length) s2 else s1 for (i in s.indices) { if (i < s.length - s3.length) { if (s[i] != '0') { count ++ } } else { if (s[i] != s3[i - (s.length -s3.length)]) { count ++ } } } return count } fun toB(n : Int) : String{ val sb = StringBuffer() var x = n while (x > 0) { sb.append(x.rem(2)) x /= 2 } return sb.toString().reversed() } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,237
leetcode
MIT License
src/Day03.kt
wellithy
571,903,945
false
null
package day03 import util.* @JvmInline value class Item(val char: Char) { fun priority(): Int = when (char) { in 'a'..'z' -> (char - 'a') + 1 in 'A'..'Z' -> (char - 'A') + 27 else -> error("") } } fun Set<Item>.priority(): Int = single().priority() @JvmInline value class Rucksack(val items: List<Item>) { fun asSet(): Set<Item> = items.toSet() private fun sub(from: Int = 0, to: Int = items.size): Set<Item> = items.subList(from, to).toSet() fun priority(): Int = (items.size / 2).let { sub(to = it) intersect sub(from = it) }.priority() companion object { fun of(line: String): Rucksack = line.toCharArray().map(::Item).let(::Rucksack) } } @JvmInline value class Group(val rucksacks: List<Rucksack>) { init { require(rucksacks.size == SIZE) } fun priority(): Int = rucksacks.map(Rucksack::asSet).reduce { acc, s -> acc intersect s }.priority() companion object { const val SIZE: Int = 3 fun of(lines: List<String>): Group = lines.map(Rucksack::of).let(::Group) } } fun part1(input: Sequence<String>): Int = input.map(Rucksack::of).map(Rucksack::priority).sum() fun part2(input: Sequence<String>): Int = input.chunked(Group.SIZE).map(Group::of).map(Group::priority).sum() fun main() { test(::part1, 157) go(::part1, 8252) test(::part2, 70) go(::part2, 2828) }
0
Kotlin
0
0
6d5fd4f0d361e4d483f7ddd2c6ef10224f6a9dec
1,487
aoc2022
Apache License 2.0
y2020/src/main/kotlin/adventofcode/y2020/Day13.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution import java.math.BigInteger fun main() = Day13.solve() object Day13 : AdventSolution(2020, 13, "Shuttle Search") { override fun solvePartOne(input: String): Int { val (ts, bussesStr) = input.lines() val t = ts.toInt() val busses = bussesStr.split(',').mapNotNull(String::toIntOrNull) fun f(x: Int) = x - t % x val b = busses.minByOrNull(::f)!! return b * f(b) } override fun solvePartTwo(input: String): Any { val (_, bussesStr) = input.lines() val busses = bussesStr.split(',').map { it.toIntOrNull() }.mapIndexedNotNull { i, v -> v?.let { i to it } } val congruences = busses.map { (i, b) -> b.toBigInteger() to ((b - i) % b).toBigInteger() } return crt(congruences) } private fun crt(congruences: List<Pair<BigInteger, BigInteger>>): BigInteger { val m = congruences.map { it.first }.reduce(BigInteger::times) return congruences .map { (mod, offset) -> offset * (m / mod) * (m / mod).modInverse(mod) } .reduce(BigInteger::plus) % m } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,171
advent-of-code
MIT License
src/main/kotlin/cz/tomasbublik/Day05.kt
tomasbublik
572,856,220
false
{"Kotlin": 21908}
package cz.tomasbublik fun main() { fun createStacks(input: List<String>): ArrayList<ArrayDeque<Char>> { val cratesLines = input.slice(0 until input.indexOf("")) val listOfStacks = ArrayList<ArrayDeque<Char>>() val numberOfStacks = cratesLines.last().split(" ").last().toInt() for (i in 1..numberOfStacks) { val stack = ArrayDeque<Char>() listOfStacks.add(stack) } for (cratesLine in cratesLines.reversed()) { // is not the last one read on by one at indexes: 1, 5, 9, 13, 17 if (cratesLines.indexOf(cratesLine) != cratesLines.size - 1) { for (i in 1..numberOfStacks) { if (cratesLine.length > ((i * 4) - 3) && cratesLine[(i * 4) - 3] != ' ') { listOfStacks[i - 1].add(cratesLine[(i * 4) - 3]) } } } } return listOfStacks } fun readMovesTriple(movesLine: String): Triple<Int, Int, Int> { val count = movesLine.split(" ")[1].toInt() val from = movesLine.split(" ")[3].toInt() val to = movesLine.split(" ")[5].toInt() return Triple(count, from, to) } fun readResult(listOfStacks: ArrayList<ArrayDeque<Char>>): String { var result = "" for (stack in listOfStacks) { result += stack.last() } return result } fun part1(input: List<String>): String { val listOfStacks = createStacks(input) val movesLines = input.slice(input.indexOf("") + 1 until input.size) for (movesLine in movesLines) { val (count, from, to) = readMovesTriple(movesLine) for (i in 1..count) { listOfStacks[to - 1].add(listOfStacks[from - 1].removeLast()) } } return readResult(listOfStacks) } fun part2(input: List<String>): String { val listOfStacks = createStacks(input) val movesLines = input.slice(input.indexOf("") + 1 until input.size) for (movesLine in movesLines) { val (count, from, to) = readMovesTriple(movesLine) val elementsToAdd = ArrayList<Char>() for (i in 1..count) { elementsToAdd.add(listOfStacks[from - 1].removeLast()) } listOfStacks[to - 1].addAll(elementsToAdd.reversed()) } return readResult(listOfStacks) } // test if implementation meets criteria from the description, like: val testInput = readFileAsLinesUsingUseLines("src/main/resources/day_5_input_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readFileAsLinesUsingUseLines("src/main/resources/day_5_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c26a93e8f6f7ab0f260c75a287608dd7218d0f0
2,824
advent-of-code-kotlin-2022
Apache License 2.0
src/Day04.kt
zuevmaxim
572,255,617
false
{"Kotlin": 17901}
private fun part1(input: List<String>) = input.count { line -> val (a, b) = line.split(",").map { r -> r.split("-").map(String::toInt).toPair() } a.first <= b.first && b.second <= a.second || b.first <= a.first && a.second <= b.second } private fun part2(input: List<String>) = input.count { line -> val (a, b) = line.split(",").map { r -> r.split("-").map(String::toInt).toPair() } a.first <= b.first && b.first <= a.second || a.first <= b.second && b.second <= a.second || b.first <= a.first && a.first <= b.second || b.first <= a.second && a.second <= b.second } fun main() { 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
34356dd1f6e27cc45c8b4f0d9849f89604af0dfd
830
AOC2022
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day17.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution import at.mpichler.aoc.lib.Vector2i import kotlin.math.ceil import kotlin.math.sign import kotlin.math.sqrt open class Part17A : PartSolution() { lateinit var targetArea: Pair<Vector2i, Vector2i> override fun parseInput(text: String) { val pattern = Regex("""target area: x=(-?\d+)\.\.(-?\d+), y=(-?\d+)\.\.(-?\d+)""") val match = pattern.find(text)!! val start = Vector2i(match.groupValues[1].toInt(), match.groupValues[3].toInt()) val end = Vector2i(match.groupValues[2].toInt(), match.groupValues[4].toInt()) targetArea = start to end } override fun compute(): Int { val vY = -targetArea.first.y - 1 return vY * (vY + 1) / 2 } override fun getExampleAnswer(): Int { return 45 } } class Part17B : Part17A() { override fun compute(): Int { val (min, max) = getPossibleVelocities() val velocities = product(min.x..max.x, min.y..max.y) return velocities.count { checkHit(it) } } private fun getPossibleVelocities(): Pair<Vector2i, Vector2i> { val minX = ceil((-1 + sqrt(1 + 8.0 * targetArea.first.x)) / 2) val maxX = targetArea.second.x val minY = targetArea.first.y val maxY = -targetArea.first.y - 1 return Vector2i(minX.toInt(), minY) to Vector2i(maxX, maxY) } private fun checkHit(velocity: Vector2i): Boolean { var x = 0 var y = 0 var vX = velocity.x var vY = velocity.y while (true) { x += vX y += vY vX -= vX.sign vY -= 1 if (x > targetArea.second.x || y < targetArea.first.y) { return false } if (x >= targetArea.first.x && y <= targetArea.second.y) { return true } } } private fun product(xValues: IntRange, yValues: IntRange): Iterable<Vector2i> { return buildList { for (x in xValues) { for (y in yValues) { add(Vector2i(x, y)) } } } } override fun getExampleAnswer(): Int { return 112 } } fun main() { Day(2021, 17, Part17A(), Part17B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
2,352
advent-of-code-kotlin
MIT License
src/main/kotlin/day18.kt
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
fun day18ProblemReader(text: String): List<String> { return text.split("\n") } // https://adventofcode.com/2020/day/18 class Day18( private val operations: List<String>, ) { fun solvePart1(): Long { return operations .asSequence() .map { "(%s)".format(it) } .map { it.replace(" ", "") } .map { resolveOperation(it, 0) } .map { (result, _) -> result } .sum() } private fun resolveOperation(line: String, start: Int): Pair<Long, Int> { var result = 0L var inx = start var operand1String = "" var operation = "" var operand2String = "" while (inx < line.length) { val valueX = line[inx].toString() if (valueX == "(") { if (operand1String.isEmpty()) { val (r, x) = resolveOperation(line, inx + 1) result = r operand1String = r.toString() inx = x } else if (operand2String.isEmpty()) { val (r, x) = resolveOperation(line, inx + 1) operand2String = r.toString() inx = x } } else if (valueX == ")") { return eval(operation, operand1String, operand2String) to inx } else if (line[inx].isDigit() && operation.isEmpty()) { operand1String = "%s%s".format(operand1String, line[inx]) } else if (line[inx].isDigit() && operation.isNotEmpty()) { operand2String = "%s%s".format(operand2String, line[inx]) } else if (!line[inx].isDigit() && operand1String.isNotEmpty() && operation.isEmpty()) { operation = line[inx].toString() } else if (!line[inx].isDigit() && operand2String.isNotEmpty()) { result = eval(operation, operand1String, operand2String) operand1String = result.toString() operation = line[inx].toString() operand2String = "" } inx += 1 } return result to inx } private fun eval( operation: String, operand1String: String, operand2String: String ): Long { return when (operation) { "+" -> { operand1String.toLong().plus(operand2String.toLong()) } "*" -> { operand1String.toLong().times(operand2String.toLong()) } else -> { 0 } } } fun solvePart2(): Long { return 0 } } fun main() { val problem = day18ProblemReader(Day18::class.java.getResource("day18.txt").readText()) println("solution = ${Day18(problem).solvePart1()}") println("solution part2 = ${Day18(problem).solvePart2()}") }
0
Kotlin
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
2,877
adventofcode_2020
MIT License
2021/src/day17/Solution.kt
vadimsemenov
437,677,116
false
{"Kotlin": 56211, "Rust": 37295}
package day17 import java.nio.file.Files import java.nio.file.Paths import kotlin.math.absoluteValue import kotlin.math.sign fun main() { fun part1(input: Input): Int { val (xRange, yRange) = input.toList().map { it.first..it.second } require(xRange.first > 0 && xRange.last >= xRange.first) require(yRange.last < 0 && yRange.last >= yRange.first) // assume we can find X such that X * (X + 1) / 2 in xRange and X <= Y * 2 + 1 // works for my test case, YMMW val y = yRange.first.absoluteValue - 1 return y * (y + 1) / 2 } fun part2(input: Input): Int { val (xRange, yRange) = input.toList().map { it.first..it.second } require(xRange.first > 0 && xRange.last >= xRange.first) require(yRange.last < 0 && yRange.last >= yRange.first) var answer = 0 for (xv in 1..xRange.last) { for (yv in yRange.first..yRange.first.absoluteValue) { var (cx, cy) = 0 to 0 var (cxv, cyv) = xv to yv while (true) { cx += cxv.also { cxv -= cxv.sign } cy += cyv-- if (cx in xRange && cy in yRange) { answer++ break } if (cx > xRange.last || cy < yRange.first) break } } } return answer } // illustrate(7, 2, readInput("test-input.txt")) // illustrate(6, 3, readInput("test-input.txt")) // illustrate(9, 0, readInput("test-input.txt")) // illustrate(17, -4, readInput("test-input.txt")) // illustrate(6, 9, readInput("test-input.txt")) // illustrate(6, 10, readInput("test-input.txt")) check(part1(readInput("test-input.txt")) == 45) check(part2(readInput("test-input.txt")) == 112) println(part1(readInput("input.txt"))) println(part2(readInput("input.txt"))) } private fun illustrate(xv: Int, yv: Int, target: Input) { val (txRange, tyRange) = target val tx = txRange.first..txRange.second val ty = tyRange.first..tyRange.second var (cx, cy) = 0 to 0 var (cxv, cyv) = xv to yv val visited = mutableListOf<Pair<Int, Int>>() while (cx <= tx.last && cy >= ty.last) { cx += cxv.also { cxv -= cxv.sign } cy += cyv-- visited.add(cx to cy) } val minX = minOf(minOf(0, tx.first), visited.minOf { it.first }) val maxX = maxOf(maxOf(0, tx.last), visited.maxOf { it.first }) val minY = minOf(minOf(0, ty.first), visited.minOf { it.second }) val maxY = maxOf(maxOf(0, ty.last), visited.maxOf { it.second }) val output = Array(maxY - minY + 1) { CharArray(maxX - minX + 1) { '.' } } for (x in tx) { for (y in ty) { output[maxY - y][x - minX] = 'T' } } output[maxY - 0][0 - minX] = 'S' for ((x, y) in visited) { output[maxY - y][x - minX] = '#' } println("($xv, $yv) -> $target") println(output.joinToString("\n") { String(it) }) } private fun readInput(s: String): Input { return Files.newBufferedReader(Paths.get("src/day17/$s")).readLine()!!.let { line -> val (xRange, yRange) = line.substring("target area: ".length).split(", ") val (xMin, xMax) = xRange.substring("x=".length).split("..").map { it.toInt() } val (yMin, yMax) = yRange.substring("y=".length).split("..").map { it.toInt() } Pair(xMin to xMax, yMin to yMax) } } private typealias Input = Pair<Pair<Int, Int>, Pair<Int, Int>>
0
Kotlin
0
0
8f31d39d1a94c862f88278f22430e620b424bd68
3,259
advent-of-code
Apache License 2.0
src/Day08_part1.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { fun part1(input: List<String>): Int { val grid = mutableListOf<List<Int>>() val seen = mutableListOf<MutableList<Boolean>>() for (it in input) { val intArr = mutableListOf<Int>() for (char in it.toList()) { intArr.add(char.digitToInt()) } grid.add(intArr) seen.add(MutableList(it.length) { false }) } for (i in grid.indices) { var curHeight = -1 for (j in grid[i].indices) { val tree = grid[i][j] if (tree > curHeight) { seen[i][j] = true curHeight = tree } } curHeight = -1 for (j in grid[i].indices.reversed()) { val tree = grid[i][j] if (tree > curHeight) { seen[i][j] = true curHeight = tree } } } for (j in grid[0].indices) { var curHeight = -1 for (i in grid.indices) { val tree = grid[i][j] if (tree > curHeight) { seen[i][j] = true curHeight = tree } } curHeight = -1 for (i in grid.indices.reversed()) { val tree = grid[i][j] if (tree > curHeight) { seen[i][j] = true curHeight = tree } } } return seen.sumOf { row -> row.count { it } } } val testInput = readInput("Day08_test") check(part1(testInput) == 21) val input = readInput("Day08") println(part1(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
1,756
advent-of-code-2022
Apache License 2.0
src/main/kotlin/solutions/year2022/Day5.kt
neewrobert
573,028,531
false
{"Kotlin": 7605}
package solutions.year2022 import readInputLines fun main() { fun moveLines(moveLines: List<String>, onePerMove: Boolean, stacks: Array<ArrayDeque<Char>>) { moveLines.forEach { line -> val parts = line.split(" ") val numCrates = parts[1].toInt() val from = parts[3].toInt() - 1 val to = parts[5].toInt() - 1 if (onePerMove) { repeat(numCrates) { val crate = stacks[from].removeLast() stacks[to].addLast(crate) } } else { var order = "" repeat(numCrates) { order += stacks[from].removeLast() } order.reversed().forEach(stacks[to]::addLast) } } } fun moveCrates(input: List<String>, onePerMove: Boolean): String { val stackLines = input.filter { '[' in it } val moveLines = input.filter { it.startsWith('m') } val stacks = Array((stackLines.maxOf { it.length } + 1) / 4) { ArrayDeque<Char>() } stackLines.forEach { line -> val crates = "$line ".chunked(4).map { it.trim() } crates.forEachIndexed { stack, crate -> if (crate.isNotEmpty()) { stacks[stack].addFirst(crate[1]) } } } moveLines(moveLines, onePerMove, stacks) return stacks.map { it.last() }.joinToString("") } fun part1(input: List<String>): String { return moveCrates(input, true) } fun part2(input: List<String>): String { return moveCrates(input, false) } val testInput = readInputLines("2022", "Day5_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputLines("2022", "Day5") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7ecf680845af9d22ef1b9038c05d72724e3914f1
1,896
aoc-2022-in-kotlin
Apache License 2.0
src/twentytwentytwo/day12/Day12.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentytwo.day12 import readInput fun main() { fun part1(input: List<String>): Int { val matrix = mutableListOf<List<Char>>() input.forEach { matrix.add(it.toList()) } val graph = Graph<Square>() lateinit var start: Square lateinit var end: Square for (i in 0 until matrix.size) { for (j in 0 until matrix[0].size) { var isStart = false var isEnd = false val char = if (matrix[i][j] == 'S') { isStart = true 'a' } else if (matrix[i][j] == 'E') { isEnd = true 'z' } else { matrix[i][j] } val square = Square(char, i, j) if (isStart) start = square if (isEnd) end = square graph.vertices.add(square) val neighbours = mutableSetOf<Square>() if (i - 1 >= 0) { neighbours.add(Square(matrix[i - 1][j], i - 1, j)) } if (i + 1 < matrix.size) { neighbours.add(Square(matrix[i + 1][j], i + 1, j)) } if (j - 1 >= 0) { neighbours.add(Square(matrix[i][j - 1], i, j - 1)) } if (j + 1 < matrix[0].size) { neighbours.add(Square(matrix[i][j + 1], i, j + 1)) } val updatedNeighbours = neighbours.map { when (it.height) { 'S' -> { it.copy(height = 'a') } 'E' -> { it.copy(height = 'z') } else -> { it } } }.toSet() graph.edges[square] = updatedNeighbours val weights = updatedNeighbours.map { Pair(square, it) }.associateWith { if (it.second.height - it.first.height > 1) 500000 else 1 } graph.weights.putAll(weights) } } val shortestPathTree = dijkstra(graph, start) return shortestPath(shortestPathTree, start, end).size - 1 } fun part2(input: List<String>): Int { val matrix = mutableListOf<List<Char>>() input.forEach { matrix.add(it.toList()) } val graph = Graph<Square>() val possibleStarts = mutableListOf<Square>() lateinit var end: Square for (i in 0 until matrix.size) { for (j in 0 until matrix[0].size) { var isStart = false var isEnd = false val char = if (matrix[i][j] == 'S' || matrix[i][j] == 'a') { isStart = true 'a' } else if (matrix[i][j] == 'E') { isEnd = true 'z' } else { matrix[i][j] } val square = Square(char, i, j) if (isStart) possibleStarts.add(square) if (isEnd) end = square graph.vertices.add(square) val neighbours = mutableSetOf<Square>() if (i - 1 >= 0) { neighbours.add(Square(matrix[i - 1][j], i - 1, j)) } if (i + 1 < matrix.size) { neighbours.add(Square(matrix[i + 1][j], i + 1, j)) } if (j - 1 >= 0) { neighbours.add(Square(matrix[i][j - 1], i, j - 1)) } if (j + 1 < matrix[0].size) { neighbours.add(Square(matrix[i][j + 1], i, j + 1)) } val updatedNeighbours = neighbours.map { when (it.height) { 'S' -> { it.copy(height = 'a') } 'E' -> { it.copy(height = 'z') } else -> { it } } }.toSet() graph.edges[square] = updatedNeighbours val weights = updatedNeighbours.map { Pair(square, it) }.associateWith { if (it.first.height - it.second.height > 1) 500000 else 1 } graph.weights.putAll(weights) } } val shortestPathTrees = dijkstra(graph, end) val pathes = possibleStarts.map { shortestPath(shortestPathTrees, end, it) }.filter { it.size != 1 } return pathes.minOf { it.size - 1 } } val input = readInput("day12", "Day12_input") println(part1(input)) println(part2(input)) } data class Square( val height: Char, val row: Int, val col: Int, ) data class Graph<T>( val vertices: MutableSet<T> = mutableSetOf(), val edges: MutableMap<T, Set<T>> = mutableMapOf(), val weights: MutableMap<Pair<T, T>, Int> = mutableMapOf(), ) private fun <T> dijkstra(graph: Graph<T>, start: T): Map<T, T?> { val vertexSet: MutableSet<T> = mutableSetOf() // a subset of vertices, for which we know the true distance val delta = graph.vertices.associateWith { 100000 }.toMutableMap() delta[start] = 0 val previous: MutableMap<T, T?> = graph.vertices.associateWith { null }.toMutableMap() while (vertexSet != graph.vertices) { val v: T = delta .filter { !vertexSet.contains(it.key) } .minBy { it.value } .key graph.edges.getValue(v).minus(vertexSet).forEach { neighbor -> val newPath = delta.getValue(v) + graph.weights.getValue(Pair(v, neighbor)) if (newPath < delta.getValue(neighbor)) { delta[neighbor] = newPath previous[neighbor] = v } } vertexSet.add(v) } return previous.toMap() } private fun <T> shortestPath(shortestPathTree: Map<T, T?>, start: T, end: T): List<T> { fun pathTo(start: T, end: T): List<T> { if (shortestPathTree[end] == null) return listOf(end) return listOf(pathTo(start, shortestPathTree[end]!!), listOf(end)).flatten() } return pathTo(start, end) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
6,592
advent-of-code
Apache License 2.0
src/Day07.kt
zdenekobornik
572,882,216
false
null
import kotlin.math.min sealed class Data { data class Directory( val name: String, val parent: Directory? = null, var children: MutableList<Data> = mutableListOf() ) : Data() data class File(val size: Long, val name: String) : Data() } data class Drive( var currentDirectory: Data.Directory = Data.Directory("/") ) { fun jumpToParentDir() { val currentParent = currentDirectory.parent if (currentParent != null) { currentDirectory = currentParent } } fun openDir(dir: String) { val foundDirectory = currentDirectory.children.filterIsInstance<Data.Directory>().find { it.name == dir } if (foundDirectory != null) { currentDirectory = foundDirectory } } fun addFile(file: Data.File) { currentDirectory.children.add(file) } fun createDirectory(name: String) { val directory = Data.Directory(name, currentDirectory, mutableListOf()) currentDirectory.children.add(directory) } } fun main() { fun Drive.processInput(input: List<String>) { for (line in input) { if (line.startsWith('$')) { if (line.startsWith("$ cd")) { val (_, _, dir) = line.split(' ') if (dir == "..") { jumpToParentDir() } else if (dir == "/") { continue } else { openDir(dir) } } } else { val (size, name) = line.split(' ') if (size == "dir") { createDirectory(name) } else { addFile(Data.File(size.toLong(), name)) } } } } fun part1(input: List<String>): Long { val drive = Drive() val parentFolder = drive.currentDirectory drive.processInput(input) var count = 0L fun computeTotalBytes(directory: Data.Directory): Long { val size = directory.children.sumOf { data -> when (data) { is Data.Directory -> computeTotalBytes(data) is Data.File -> data.size } } if (size <= 100000) { count += size } return size } computeTotalBytes(parentFolder) return count } fun part2(input: List<String>): Long { val drive = Drive() val parentFolder = drive.currentDirectory drive.processInput(input) fun computeTotalBytes(directory: Data.Directory): Long { return directory.children.sumOf { data -> when (data) { is Data.Directory -> computeTotalBytes(data) is Data.File -> data.size } } } val totalSize = computeTotalBytes(parentFolder) val minDeleteSize = 30000000 - (70000000 - totalSize) var currentDeleteSize = Long.MAX_VALUE fun detectDirectoryForDeletion(directory: Data.Directory): Long { val size = directory.children.sumOf { data -> when (data) { is Data.Directory -> detectDirectoryForDeletion(data) is Data.File -> data.size } } if (size >= minDeleteSize) { currentDeleteSize = min(currentDeleteSize, size) } return size } detectDirectoryForDeletion(parentFolder) return currentDeleteSize } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") checkResult(part1(testInput), 95437) checkResult(part2(testInput), 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f73e4a32802fa43b90c9d687d3c3247bf089e0e5
3,979
advent-of-code-2022
Apache License 2.0
y2017/src/main/kotlin/adventofcode/y2017/Day08.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution object Day08 : AdventSolution(2017, 8, "I Heard You Like Registers") { override fun solvePartOne(input: String): String { val registers = mutableMapOf<String, Int>() for (instruction in parseInput(input)) { instruction.executeOn(registers) } return registers.values.maxOrNull().toString() } override fun solvePartTwo(input: String): String { val registers = mutableMapOf<String, Int>() return parseInput(input) .onEach { it.executeOn(registers) } .maxOf { registers[it.register] ?: 0 } .toString() } private fun parseInput(input: String): Sequence<Instruction> { val regex = "([a-z]+) ([a-z]+) (-?\\d+) if ([a-z]+) ([^ ]+) (-?\\d+)" .toRegex() return input.lineSequence() .map { regex.matchEntire(it)?.destructured!! } .map { (a, b, c, d, e, f) -> val sign = if (b == "inc") 1 else -1 Instruction(a, c.toInt() * sign, d, e, f.toInt()) } } private data class Instruction(val register: String, private val amount: Int, private val comparandRegister: String, private val comparator: String, private val comparand: Int) { fun executeOn(registers: MutableMap<String, Int>) { if (compare(registers[comparandRegister] ?: 0)) { registers[register] = (registers[register] ?: 0) + amount } } fun compare(v: Int) = when (comparator) { "<" -> v < comparand "==" -> v == comparand ">" -> v > comparand "<=" -> v <= comparand ">=" -> v >= comparand "!=" -> v != comparand else -> throw IllegalStateException(comparator) } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,632
advent-of-code
MIT License
2021/src/main/kotlin/day5_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Segment import utils.Solution import utils.Vec2i import utils.mapItems fun main() { Day5Func.run() } object Day5Func : Solution<List<Segment>>() { override val name = "day5" override val parser = Parser.lines .mapItems(Segment::parse) .mapItems { if (it.start.x > it.end.x) Segment(it.end, it.start) else it } override fun part1(input: List<Segment>): Int? { return solve(input.filter { it.isVertical || it.isHorizontal }) } override fun part2(input: List<Segment>): Int? { return solve(input) } private fun solve(lines: List<Segment>): Int { return lines .flatMapIndexed { index, line -> lines.drop(index + 1).map { line to it } } .flatMap { (line1, line2) -> line1 intersect line2 } .toSet() .count() } private infix fun Segment.intersect(other: Segment): Collection<Vec2i> { val startx = maxOf(this.start.x, other.start.x) val endx = minOf(this.end.x, other.end.x) val pts = if (isVertical) { (minOf(start.y, end.y) .. maxOf(start.y, end.y)).map { Vec2i(start.x, it) } } else { (startx .. endx).map { this[it] } } return pts.filter { it in other } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,212
aoc_kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestPalindromeConcatenating.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT import kotlin.math.min /** * 2131. Longest Palindrome by Concatenating Two-Letter Words * @see <a href="https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/">Source</a> */ fun interface LongestPalindromeConcatenating { fun longestPalindrome(words: Array<String>): Int } /** * Approach 1: A Hash Map Approach */ class LongestPalindromeConcatenatingMap : LongestPalindromeConcatenating { override fun longestPalindrome(words: Array<String>): Int { val count = HashMap<String, Int>() for (word in words) { val countOfTheWord = count[word] if (countOfTheWord == null) { count[word] = 1 } else { count[word] = countOfTheWord + 1 } } var answer = 0 var central = false for ((word, countOfTheWord) in count) { // if the word is a palindrome if (word[0] == word[1]) { if (countOfTheWord % 2 == 0) { answer += countOfTheWord } else { answer += countOfTheWord - 1 central = true } // consider a pair of non-palindrome words such that one is the reverse of another } else if (word[0] < word[1]) { val reversedWord = "" + word[1] + word[0] if (count.containsKey(reversedWord)) { answer += 2 * min(countOfTheWord, count.getOrDefault(reversedWord, 1)) } } } if (central) { answer++ } return 2 * answer } } /** * Approach 2: A Two-Dimensional Array Approach */ class LongestPalindromeConcatenatingArr : LongestPalindromeConcatenating { override fun longestPalindrome(words: Array<String>): Int { val count = Array(ALPHABET_LETTERS_COUNT) { IntArray(ALPHABET_LETTERS_COUNT) } for (word in words) { count[word[0].code - 'a'.code][word[1].code - 'a'.code]++ } var answer = 0 var central = false for (i in 0 until ALPHABET_LETTERS_COUNT) { if (count[i][i] % 2 == 0) { answer += count[i][i] } else { answer += count[i][i] - 1 central = true } for (j in i + 1 until ALPHABET_LETTERS_COUNT) { answer += 2 * min(count[i][j], count[j][i]) } } if (central) { answer++ } return 2 * answer } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,284
kotlab
Apache License 2.0
src/day04/Solution.kt
abhabongse
576,594,038
false
{"Kotlin": 63915}
/* Solution to Day 4: Camp Cleanup * https://adventofcode.com/2022/day/4 */ package day04 import java.io.File fun main() { val fileName = // "day04_sample.txt" "day04_input.txt" val assignmentPairs = readInput(fileName) // Part 1: count assignment pairs where one fully contains the other val p1Count = assignmentPairs.count { (firstRange, secondRange) -> firstRange subset secondRange || secondRange subset firstRange } println("Part 1: $p1Count") // Part 2: count overlapping assignment pairs val p2Count = assignmentPairs.count { (firstRange, secondRange) -> firstRange overlaps secondRange } println("Part 2: $p2Count") } /** * Reads and parses input data according to the problem statement. */ fun readInput(fileName: String): List<AssignmentPair> { return File("inputs", fileName) .readLines() .asSequence() .map { AssignmentPair from it } .toList() } /** * Checks if this IntRange is a subset of the other [IntRange]. */ infix fun IntRange.subset(other: IntRange): Boolean { return other.first <= this.first && this.last <= other.last } /** * Checks if this IntRange overlaps with the other [IntRange] * by at least one element. */ infix fun IntRange.overlaps(other: IntRange): Boolean { return this.first <= other.last && other.first <= this.last }
0
Kotlin
0
0
8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb
1,388
aoc2022-kotlin
Apache License 2.0
advent/src/test/kotlin/org/elwaxoro/advent/y2022/Dec08.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2022 import org.elwaxoro.advent.PuzzleDayTester import org.elwaxoro.advent.padTo import org.elwaxoro.advent.splitToInt /** * Day 8: Treetop Tree House */ class Dec08: PuzzleDayTester(8, 2022) { /** * Can't see the forest for all the trees */ override fun part1(): Any = load().map { it.splitToInt() }.let { trees -> val visible = trees.map { listOf(0).padTo(it.size).toMutableList() } val rowSize = trees.lastIndex val colSize = trees.first().lastIndex trees.lookAtTrees((0..rowSize), (0..colSize), visible) trees.lookAtTrees((rowSize downTo 0), (colSize downTo 0), visible) trees.lookAtTreesTheOtherWay((0..rowSize), (0..colSize), visible) trees.lookAtTreesTheOtherWay((rowSize downTo 0), (colSize downTo 0), visible) visible.sumOf { it.sum() } } private fun List<List<Int>>.lookAtTrees(rows: IntProgression, cols: IntProgression, visible: List<MutableList<Int>>) { rows.forEach { row -> var max = -1 cols.forEach { col -> if(this[row][col] > max) { visible[row][col] = 1 max = this[row][col] } } } } private fun List<List<Int>>.lookAtTreesTheOtherWay(rows: IntProgression, cols: IntProgression, visible: List<MutableList<Int>>) { cols.forEach { col -> var max = -1 rows.forEach { row -> if(this[row][col] > max) { visible[row][col] = 1 max = this[row][col] } } } } /** * Let's find the tree with the best visibility for this here tree house * Aren't we supposed to be finding a starfruit tree for santa??? */ override fun part2(): Any = load().map { it.splitToInt() }.let { trees -> val visibility = trees.map { listOf(0).padTo(it.size).toMutableList() } trees.forEachIndexed { rowIdx, row -> row.forEachIndexed { colIdx, tree -> val up = (rowIdx-1 downTo 0).countTrees { trees[it][colIdx] < tree } val down = (rowIdx+1..trees.lastIndex).countTrees { trees[it][colIdx] < tree } val left = (colIdx-1 downTo 0).countTrees { trees[rowIdx][it] < tree } val right = (colIdx+1..trees.first().lastIndex).countTrees { trees[rowIdx][it] < tree } visibility[rowIdx][colIdx] = right * left * down * up } } visibility.maxOf { it.max() } } /** * This is literally just takeWhile except it also takes the first item that breaks the predicate * ex: look for trees of height less than 5, but also take that first tree that is 5 or higher */ private fun Iterable<Int>.countTrees(predicate: (Int) -> Boolean): Int { val list = ArrayList<Int>() for (item in this) { if (!predicate(item)) { list.add(item) break } list.add(item) } return list.size } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
3,154
advent-of-code
MIT License
src/main/kotlin/day22.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package day22 import aoc.utils.* val UP = Cursor(0, -1) val DOWN = Cursor(0, 1) val LEFT = Cursor(-1, 0) val RIGHT = Cursor(1, 0) val ROTATIONS = listOf(UP, RIGHT, DOWN, LEFT) data class Actor(val location: Block, val direction: Block) { fun turn(direction: Char): Actor { val currentDirectionIndex = location.neighbours.indexOf(this.direction) val newDirection = when (direction) { 'R' -> location.neighbours.getLooping(currentDirectionIndex+1) 'L' -> location.neighbours.getLooping(currentDirectionIndex-1) '?' -> this.direction else -> throw Error("unknown direction $direction") } return copy(direction = newDirection) } fun move(movesLeft: Int): Actor { if(movesLeft == 0) { return this } val newLocation = this.direction val newDirection = newLocation.oppositeOf(this.location) if(newLocation.type == '#') { return this } else { return copy(location =newLocation, direction = newDirection).move(movesLeft-1) } } } fun main() { part2().let { println(it) } } data class Block( var type: Char, var location: Cursor, var neighbours: List<Block> ) { override fun toString(): String { return type.toString() } // As the neighbours are in clockwise order, we get the opposite by indexing +2 fun oppositeOf(of: Block): Block { val index = neighbours.indexOf(of) return neighbours.getLooping(index+2) } } fun part2(): Int { // val map = readMap(input()).map { // Block(it.value, it.cursor, mutableListOf()) // } // // map.findAll { it.value.type != ' ' } // .forEach { // it.value.left = getNextLooping(it.cursor, LEFT, map) // } // // return solve(map) return 1 } fun part1(): Int { val map = readMap(input()).map { Block(it.value, it.cursor, listOf()) } map.findAll { it.value.type != ' ' } .forEach { it.value.neighbours = // Order must be in clockwise, and for end scoring same order as scores given listOf( getNextLooping(it.cursor, RIGHT, map), getNextLooping(it.cursor, DOWN, map), getNextLooping(it.cursor, LEFT, map), getNextLooping(it.cursor, UP, map), ) } return solve(map) } private fun solve(map: Matrix<Block>): Int { val directions = directions(input()) val startPosition = findStart(map) var actor = Actor(startPosition, startPosition.neighbours[0]) directions.forEachIndexed { index, direction -> println(index) val temp = map.get(actor.location.location).value.type map.get(actor.location.location).value.type = '@' println(map.visualize("")) println("*******************************") map.get(actor.location.location).value.type = temp if (direction.turn != '?') { actor = actor.turn(direction.turn) } else { actor = actor.move(direction.move) } } // println(actor.location) // println(actor.direction) // map.replace(actor.location) { '@' } // // println(map.visualize("")) val actorSpot = map.find { it == actor.location }!! println(actorSpot) return (actorSpot.cursor.y + 1) * 1000 + (actorSpot.cursor.x + 1) * 4 + actor.location.neighbours.indexOf(actor.direction) } fun getNextLooping(cursor: Cursor, direction: Cursor, map: Matrix<Block>): Block { var newLocation = map.putInBounds(cursor.plus(direction)) while (map.get(newLocation).value.type == ' ') { newLocation = map.putInBounds(newLocation.plus(direction)) } return map.get(newLocation).value } fun findStart(map: Matrix<Block>): Block { return map.rows()[0].firstOrNull { it.value.type == '.' }!!.value } data class Direction(val move: Int, val turn: Char) fun directions(input: List<String>): List<Direction> { return """R|L|\d+""".toRegex().findAll(input.last()) .map { it.value } .map { if (it.isInt()) { Direction(it.toInt(), '?') } else { if (it.length != 1) throw Error("Expected single char") Direction(0, it[0]) } }.toList() } fun readMap(input: List<String>): Matrix<Char> { val mapRows = input.takeWhile { it != "" }.map { it.toCharArray().toList() } return Matrix(mapRows) { x, y -> ' ' } } private fun input() = readInput("day22-input.txt")
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
4,640
adventOfCode2022
Apache License 2.0
kotlin/src/com/leetcode/120_Triangle.kt
programmerr47
248,502,040
false
null
package com.leetcode import java.lang.Integer.min //DP, but we assume the we have natural numbers. Time: O(n), Space: O(n), where n - is a total amount of numbers private class Solution120 { fun minimumTotal(triangle: List<List<Int>>): Int { val buffer = IntArray(triangle.size) triangle.forEachIndexed { i, row -> if (i != 0) { for (j in i downTo 0) { if (j != 0) { buffer[j] = if (j == i) buffer[j - 1] else min(buffer[j], buffer[j - 1]) } } } row.forEachIndexed { j, num -> buffer[j] = buffer[j] + num } } return buffer.minOrNull()!! } } //Recursion. Will not good for big data. Time: O(2^n), Space: O(n), where n - is a total amount of rows private class Solution120old { fun minimumTotal(triangle: List<List<Int>>): Int = find(triangle, 0, 0, 0) private fun find(triangle: List<List<Int>>, i: Int, j: Int, sum: Int): Int { if (i >= triangle.size) return sum return min( find(triangle, i + 1, j, sum + triangle[i][j]), find(triangle, i + 1, j + 1, sum + triangle[i][j]) ) } } fun main() { println(Solution120().minimumTotal(listOf( listOf(2), listOf(3, 4), listOf(6, 5, 7), listOf(4, 1, 8, 3) ))) }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
1,413
problemsolving
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-06.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input1 = readInputLines(2023, "06-input") val test1 = readInputLines(2023, "06-test1") println("Part1:") part1(test1).println() part1(input1).println() println() println("Part2:") part2(test1).println() part2(input1).println() } private fun part1(input: List<String>): Int { val times = input[0].split("""\s+""".toRegex()).drop(1).map(String::toLong) val distances = input[1].split("""\s+""".toRegex()).drop(1).map(String::toLong) return distances.zip(times).fold(1) { acc, (dist, time) -> acc * waysToWin(dist, time) } } private fun part2(input: List<String>): Int { val time = input[0].split("""\s+""".toRegex()).drop(1).joinToString(separator = "").let(String::toLong) val distance = input[1].split("""\s+""".toRegex()).drop(1).joinToString(separator = "").let(String::toLong) return waysToWin(distance, time) } private fun waysToWin(dist: Long, time: Long) = (1 ..< time).count { dist < it * (time - it) }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,146
advent-of-code
MIT License
src/main/kotlin/days/Day14.kt
andilau
433,504,283
false
{"Kotlin": 137815}
package days @AdventOfCodePuzzle( name = "Extended Polymerization", url = "https://adventofcode.com/2021/day/14", date = Date(day = 14, year = 2021) ) class Day14(val input: List<String>) : Puzzle { private val polymer: String = input.first() private val rules = input.drop(2) .associate { line -> line.split(" -> ").let { it[0] to it[1] } } override fun partOne() = buildMoleculePairAndCount(10) .countByMolecule() .values .mostMinusLeastCommon() override fun partTwo() = buildMoleculePairAndCount(40) .countByMolecule() .values .mostMinusLeastCommon() private fun buildMoleculePairAndCount(times: Int): Map<String, Long> { var pairCount = polymer.windowed(2) .groupingBy { pairs -> pairs }.eachCount() .mapValues { counts -> counts.value.toLong() } repeat(times) { pairCount = pairCount .flatMap { (pair, count) -> val molecule = rules.getValue(pair) val left = pair[0] + molecule val right = molecule + pair[1] listOf(left to count, right to count) } .groupBy({ it.first }, { it.second }) .mapValues { it.value.sum() } } return pairCount } private fun Map<String, Long>.countByMolecule(): Map<Char, Long> = this .flatMap { (pair, count) -> listOf(pair[0] to count, pair[1] to count) } .groupBy({ it.first }, { it.second }) .mapValues { (molecule, counts) -> when (molecule) { polymer.first(), polymer.last() -> (counts.sum() + 1) / 2 else -> counts.sum() / 2 } } private fun Collection<Long>.mostMinusLeastCommon() = sorted().let { it.last() - it.first() } internal fun countMolecules(times: Int) = countByMolecule(times).values.sum() internal fun countByMolecule(times: Int) = buildMoleculePairAndCount(times) .countByMolecule() }
0
Kotlin
0
0
b3f06a73e7d9d207ee3051879b83e92b049a0304
2,151
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/Day08.kt
cornz
572,867,092
false
{"Kotlin": 35639}
fun main() { fun scenicScore(input: List<String>): Int { val scenicScores = mutableListOf<Int>() val twoDArray = input.map { x -> x.toCharArray().map { y -> y.digitToInt() } } for ((listcounter, list) in twoDArray.withIndex()) { if (listcounter > 0 && listcounter < twoDArray.size - 1) { for ((numbercounter, number) in list.withIndex()) { if (numbercounter > 0 && numbercounter < list.size - 1) { val left = list.slice(0 until numbercounter) val right = list.slice(numbercounter + 1 until list.size) val up = twoDArray.slice(0 until listcounter).map { x -> x[numbercounter] } val down = twoDArray.slice(listcounter + 1 until twoDArray.size).map { x -> x[numbercounter] } var leftScore = 0 var rightScore = 0 var upScore = 0 var downScore = 0 for (num in left.reversed()) { if (num >= number) { leftScore += 1 break } else { leftScore += 1 } } for (num in right) { if (num >= number) { rightScore += 1 break } else { rightScore += 1 } } for (num in up.reversed()) { if (num == number) { upScore += 1 break } else { upScore += 1 } } for (num in down) { if (num >= number) { downScore += 1 break } else { downScore += 1 } } scenicScores.add(leftScore * rightScore * upScore * downScore) } } } } return scenicScores.max() } fun isVisible(input: List<String>): Int { var visibleCounter = 0 val twoDArray = input.map { x -> x.toCharArray().map { y -> y.digitToInt() } } for ((listcounter, list) in twoDArray.withIndex()) { if (listcounter > 0 && listcounter < twoDArray.size - 1) { for ((numbercounter, number) in list.withIndex()) { if (numbercounter > 0 && numbercounter < list.size - 1) { val left = list.slice(0 until numbercounter) val right = list.slice(numbercounter + 1 until list.size) val up = twoDArray.slice(0 until listcounter).map { x -> x[numbercounter] } val down = twoDArray.slice(listcounter + 1 until twoDArray.size).map { x -> x[numbercounter] } if (left.all { x -> x < number } || right.all { x -> x < number } || up.all { x -> x < number } || down.all { x -> x < number }) { visibleCounter += 1 } } } } } return visibleCounter } fun getOuterBounds(input: List<String>): Int { return input.size * 2 + (input[0].length - 2) * 2 } fun part1(input: List<String>): Int { val outerBounds = getOuterBounds(input) val visibleTrees = isVisible(input) return outerBounds + visibleTrees } fun part2(input: List<String>): Int { return scenicScore(input) } // test if implementation meets criteria from the description, like: val testInput = readInput("input/Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("input/Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2800416ddccabc45ba8940fbff998ec777168551
4,308
aoc2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/GreatestCommonDivisorOfArray.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2024 <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.math.gcd import kotlin.math.max import kotlin.math.min /** * 1979. Find Greatest Common Divisor of Array * @see <a href="https://leetcode.com/problems/find-greatest-common-divisor-of-array">Source</a> */ fun interface GreatestCommonDivisorOfArray { operator fun invoke(nums: IntArray): Int } class GreatestCommonDivisorOfArrayBF : GreatestCommonDivisorOfArray { override fun invoke(nums: IntArray): Int { if (nums.isEmpty()) return -1 nums.sort() val smallest = nums.first() val largest = nums.last() return gcd(smallest, largest) } } class Euclidean : GreatestCommonDivisorOfArray { override fun invoke(nums: IntArray): Int { var min = Int.MAX_VALUE var max = Int.MIN_VALUE for (num in nums) { min = if (min > num) num else min max = if (max < num) num else max } return gcd(min, max) } } class GreatestCommonDivisorOfArrayFunc : GreatestCommonDivisorOfArray { override fun invoke(nums: IntArray): Int { return nums .fold(Pair(Int.MIN_VALUE, Int.MAX_VALUE)) { prev, curr -> Pair( max(prev.first, curr), min(prev.second, curr), ) } .let { gcd(it.first, it.second) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,997
kotlab
Apache License 2.0
src/main/kotlin/Day01.kt
ripla
573,901,460
false
{"Kotlin": 19599}
object Day1 { fun part1(input: List<String>): Int { val elvesGrouped: List<List<Int>> = input.fold(listOf(emptyList())) { acc: List<List<Int>>, element -> (if (element == "") { acc.plusElement(emptyList()) } else { val elfAdded: List<Int> = acc.last() + element.toInt() acc.dropLast(1).plusElement(elfAdded) }) } val elvesSummed = elvesGrouped.map { elf -> elf.sum()} return elvesSummed.max() } fun part2(input: List<String>): Int { val elvesGrouped: List<List<Int>> = input.fold(listOf(emptyList())) { acc: List<List<Int>>, element -> (if (element == "") { acc.plusElement(emptyList()) } else { val elfAdded: List<Int> = acc.last() + element.toInt() acc.dropLast(1).plusElement(elfAdded) }) } val elvesSummed = elvesGrouped.map { elf -> elf.sum()} val elvesSorted = elvesSummed.sortedDescending() return elvesSorted.take(3).sum() } }
0
Kotlin
0
0
e5e6c0bc7a9c6eaee1a69abca051601ccd0257c8
1,097
advent-of-code-2022-kotlin
Apache License 2.0
src/Day03.kt
hanmet
573,490,488
false
{"Kotlin": 9896}
fun main() { fun toPriority(c: Char): Int { return if (c.isUpperCase()) { c.code - 38 } else { c.code - 96 } } fun part1(input: List<String>): Int { var sum = 0 for (rucksack in input) { val (left, right) = rucksack.chunked(rucksack.length / 2) sum += left.toSet().intersect(right.toSet()).sumOf { toPriority(it) } } return sum } fun part2(input: List<String>): Int { var sum = 0 val chunks = input.chunked(3) for (rucksacks in chunks) { sum += rucksacks[0].toSet().intersect(rucksacks[1].toSet()).intersect(rucksacks[2].toSet()).sumOf { toPriority(it) } } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e4e1722726587639776df86de8d4e325d1defa02
998
advent-of-code-2022
Apache License 2.0
2016/src/main/java/p3/Problem3.kt
ununhexium
113,359,669
false
null
package p3 import com.google.common.collect.Lists import more.Input fun main(args: Array<String>) { val sides = Input .getFor("p3") .split("\n") .map { it.trim().replace(Regex(" +"), " ").split(" ") } .map { it.map { it.toInt() } } readByLine(sides) readByColumn(sides) } fun readByColumn(sides: List<List<Int>>) { val columns = sides.map { it[0] } + sides.map { it[1] } + sides.map { it[2] } val realTriangles = Lists .partition(columns, 3) .sumBy { if (isTriangle(it)) 1 else 0 } println("By column: " + realTriangles) } private fun readByLine(sides: List<List<Int>>) { val realTriangles = sides.sumBy { if (isTriangle(it)) 1 else 0 } println("By line: " + realTriangles) } fun isTriangle(sides: List<Int>): Boolean { val sortedSides = sides.sorted() return sortedSides[2] < (sortedSides[1] + sortedSides[0]) }
6
Kotlin
0
0
d5c38e55b9574137ed6b351a64f80d764e7e61a9
876
adventofcode
The Unlicense
year2016/src/main/kotlin/net/olegg/aoc/year2016/day24/Day24.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2016.day24 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.NEXT_4 import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.permutations import net.olegg.aoc.year2016.DayOf2016 /** * See [Year 2016, Day 24](https://adventofcode.com/2016/day/24) */ object Day24 : DayOf2016(24) { override fun first(): Any? { val map = matrix val locations = ('0'..'7').flatMap { index -> map.mapIndexedNotNull { row, chars -> Vector2D(chars.indexOf(index), row).takeIf { it.x != -1 } } } val distances = (0..7).map { dist -> val start = locations[dist] val visit = mutableMapOf(start to 0) val queue = ArrayDeque(listOf(start)) while (queue.isNotEmpty()) { val pos = queue.removeFirst() val steps = visit[pos] ?: 0 NEXT_4 .map { pos + it.step } .filterNot { it in visit } .filterNot { map[it.y][it.x] == '#' } .also { cells -> cells.forEach { cell -> visit[cell] = steps + 1 } queue += cells } } return@map locations.map { visit[it] } } return (1..7) .toList() .permutations() .map { listOf(0) + it } .minOf { route -> route.windowed(2).fold(0) { acc, points -> acc + (distances[points[0]][points[1]] ?: 0) } } } override fun second(): Any? { val map = matrix val locations = ('0'..'7').flatMap { index -> map.mapIndexedNotNull { row, chars -> Vector2D(chars.indexOf(index), row).takeIf { it.x != -1 } } } val distances = (0..7).map { dist -> val start = locations[dist] val visit = mutableMapOf(start to 0) val queue = ArrayDeque(listOf(start)) while (queue.isNotEmpty()) { val pos = queue.removeFirst() val steps = visit[pos] ?: 0 NEXT_4 .map { pos + it.step } .filterNot { it in visit } .filterNot { map[it.y][it.x] == '#' } .also { cells -> cells.forEach { cell -> visit[cell] = steps + 1 } queue.addAll(cells) } } return@map locations.map { visit[it] } } return (1..7) .toList() .permutations() .map { listOf(0) + it + listOf(0) } .minOf { route -> route.windowed(2).fold(0) { acc, points -> acc + (distances[points[0]][points[1]] ?: 0) } } } } fun main() = SomeDay.mainify(Day24)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,529
adventofcode
MIT License
src/day04/Day04.kt
violabs
576,367,139
false
{"Kotlin": 10620}
package day04 import readInput fun main() { test1("day-04-test-input-01", 2) test2("day-04-test-input-01", 4) test2("day-04-actual-test-input", 4) } private fun test1(filename: String, expected: Int) { val input = readInput("day04/$filename") val actual: Int = findHighPriorityCleaningReassignments(input) println("EXPECT: $expected") println("ACTUAL: $actual") check(expected == actual) } private fun test2(filename: String, expected: Int) { val input = readInput("day04/$filename") val actual: Int = findAnyOverlapInCleaningAssignments(input) println("EXPECT: $expected") println("ACTUAL: $actual") check(expected == actual) } private fun findHighPriorityCleaningReassignments(input: List<String>): Int { return input .asSequence() .map(::WorkPair) .filter(WorkPair::containsHighPriorityReassignment) .count() } private fun findAnyOverlapInCleaningAssignments(input: List<String>): Int { return input .asSequence() .map(::WorkPair) .filter(WorkPair::containsAnyOverlap) .count() } class WorkPair(details: String) { private val splitDetails = details.split(",") private val firstSections: Pair<Int, Int> = createRange(splitDetails[0]) private val secondSections: Pair<Int, Int> = createRange(splitDetails[1]) private fun createRange(rangeString: String): Pair<Int, Int> { val sectionEnds = rangeString.split("-") return sectionEnds[0].toInt() to sectionEnds[1].toInt() } fun containsHighPriorityReassignment(): Boolean = firstSections.contains(secondSections) || secondSections.contains(firstSections) fun containsAnyOverlap(): Boolean = firstSections.sharesAny(secondSections) || secondSections.sharesAny(firstSections) } fun Pair<Int, Int>.contains(other: Pair<Int, Int>): Boolean = this.first <= other.first && this.second >= other.second fun Pair<Int, Int>.sharesAny(other: Pair<Int, Int>): Boolean = (this.first <= other.first && this.second >= other.first) || (this.first <= other.second && this.second >= other.second)
0
Kotlin
0
0
be3d6bb2aef1ebd44bbd8e62d3194c608a5b3cc1
2,139
AOC-2022
Apache License 2.0
src/main/kotlin/day16.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.* fun main() { val input = Input.day(16) println(day16A(input)) println(day16B(input)) } fun day16A(input: Input): Int { val map = XYMap(input) { it } return tilesEnergized(map, Mover(Point(0, 0), Right)) } fun day16B(input: Input): Int { val map = XYMap(input) { it } val entries = map.all().filter { it.key.x == 0 }.map { Mover(it.key, Right) } + map.all().filter { it.key.x == map.width - 1 }.map { Mover(it.key, Left) } + map.all().filter { it.key.y == 0 }.map { Mover(it.key, Down) } + map.all().filter { it.key.y == map.height - 1 }.map { Mover(it.key, Up) } return entries.maxOf { tilesEnergized(map, it) } } private fun tilesEnergized(map: XYMap<Char>, start: Mover): Int { var beams = listOf(start) val history = beams.toMutableList() while (beams.isNotEmpty()) { val nextBeams = mutableListOf<Mover>() beams.forEach { nextBeams.addAll(it.move(map[it.at])) } beams = nextBeams.filter { !history.contains(it) && map.getOrNull(it.at) != null } history.addAll(beams) } return history.map { it.at }.toSet().size } private fun Mover.move(on: Char): List<Mover> { return when { (on == '.' || on == '|') && dir == Up -> listOf(up()) (on == '.' || on == '-') && dir == Right -> listOf(right()) (on == '.' || on == '|') && dir == Down -> listOf(down()) (on == '.' || on == '-') && dir == Left -> listOf(left()) on == '\\' && dir == Up -> listOf(left()) on == '\\' && dir == Right -> listOf(down()) on == '\\' && dir == Down -> listOf(right()) on == '\\' && dir == Left -> listOf(up()) on == '/' && dir == Up -> listOf(right()) on == '/' && dir == Right -> listOf(up()) on == '/' && dir == Down -> listOf(left()) on == '/' && dir == Left -> listOf(down()) on == '-' && (dir == Up || dir == Down) -> { listOf(left(), right()) } on == '|' && (dir == Right|| dir == Left) -> { listOf(up(), down()) } else -> throw Exception() } }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
2,165
AdventOfCode2023
MIT License
src/Day07.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
data class FileProp(val path: String, val name: String, val size: Long) data class Acc(var currentPath: String, val allDirs: MutableList<String>, val files: MutableList<FileProp>) fun main() { fun foldFn(input: List<String>): Acc = input.fold(Acc("root", mutableListOf("root"), mutableListOf())) { acc: Acc, it: String -> val props = it.split(" ") if (props[0].toLongOrNull() != null) { val newElement = FileProp(path = acc.currentPath, name = props[1], size = props[0].toLong()) acc.files.add(newElement) } else if (it == "\$ cd ..") { acc.currentPath = acc.currentPath.substringBeforeLast("|") } else if (it.contains("\$ cd") && props[2] != "/") { acc.currentPath += "|${props[2]}" acc.allDirs.add(acc.currentPath) } return@fold acc } fun getDirSizes(input: List<String>): List<Long> = foldFn(input).run { this.allDirs.toSet().map { dir -> this.files.filter { file -> file.path.startsWith(dir) }.sumOf { file -> file.size } } } fun part1(input: List<String>): Long = getDirSizes(input).filter { it <= 100000 }.sum() fun part2(input: List<String>): Long = getDirSizes(input).run { this.filter { it >= this.max() - 40000000 }.min() } val testInput = readInput("Day07_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
1,573
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
roxspring
573,123,316
false
{"Kotlin": 9291}
fun main() { fun String.parseRange(): IntRange = substring(0 until indexOf('-')).toInt()..substring(indexOf('-') + 1).toInt() fun String.parsePair(): Pair<IntRange, IntRange> = substring(0 until indexOf(',')).parseRange() to substring(indexOf(',') + 1).parseRange() fun IntRange.containsAll(other: IntRange): Boolean = all { other.contains(it) } fun IntRange.containsAny(other: IntRange): Boolean = any { other.contains(it) } fun part1(lines: List<String>): Int = lines.asSequence() .map { it.parsePair() } .map { (first, second) -> first.containsAll(second) || second.containsAll(first) } .count { it } fun part2(lines: List<String>): Int = lines.asSequence() .map { it.parsePair() } .map { (first, second) -> first.containsAny(second) || second.containsAny(first) } .count { it } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) check(part2(testInput) == 4) println(part2(input)) }
0
Kotlin
0
0
535beea93bf84e650d8640f1c635a430b38c169b
1,151
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-10.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2021, "10-input") val test1 = readInputLines(2021, "10-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { return input.map { it.status() }.filterIsInstance<Status.Corrupted>().sumOf { it.score } } private fun part2(input: List<String>): Long { val sorted = input.map { it.status() }.filterIsInstance<Status.Incomplete>().map { it.score }.sorted() return sorted[sorted.size / 2] } private sealed class Status { class Corrupted(val score: Int) : Status() class Incomplete(val score: Long) : Status() } private fun String.status(): Status { val corruptedTable = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) val incompleteTable = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4) val stack = ArrayDeque<Char>() var position = 0 while (position < length) { when (val current = get(position)) { '(' -> { stack.addFirst(')') } '[' -> { stack.addFirst(']') } '<' -> { stack.addFirst('>') } '{' -> { stack.addFirst('}') } '>', ')', ']', '}' -> { val first = stack.removeFirst() if (first != current) return Status.Corrupted(corruptedTable[current]!!) } else -> error("Unexpected char $current") } position++ } if (stack.isEmpty()) error("Complete line") val score = stack.fold(0L) { acc, char -> acc * 5 + incompleteTable[char]!! } return Status.Incomplete(score) }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,954
advent-of-code
MIT License