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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
advent-of-code-2022/src/main/kotlin/Day05.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 05: Supply Stacks
//https://adventofcode.com/2022/day/5
import java.io.File
import kotlin.collections.ArrayDeque
data class Command(val itemsToMove: Int, val source: String, val destination: String) {
companion object {
fun fromString(command: String): Command {
return Command(
command.substringAfter("move ").substringBefore(" from").toInt(),
command.substringAfter("from ").substringBefore(" to"),
command.substringAfter("to ")
)
}
}
}
fun main() {
val input = File("src/main/resources/Day05.txt").readLines()
val cratesAndLabel = input.takeWhile { it.isNotEmpty() }
val labels = cratesAndLabel.last().split(" ").map { it.trim() }
val crates = cratesAndLabel.dropLast(1).reversed()
val commands = input.drop(cratesAndLabel.size + 1).map { Command.fromString(it) }
rearrangeCrates9000(getStacks(labels, crates), commands)
println()
rearrangeCrates9001(getStacks(labels, crates), commands)
}
private fun getStacks(
labels: List<String>,
inputCrate: List<String>
) = labels.mapIndexed { i, label ->
val stack = ArrayDeque<String>()
inputCrate.forEach {
it.getOrNull((i * 4) + 1)?.let { char ->
if (!char.isWhitespace()) stack.addFirst(char.toString())
}
}
label to stack
}.toMap()
fun rearrangeCrates9000(stacks: Map<String, ArrayDeque<String>>, commands: List<Command>) {
commands.forEach { command ->
(1..command.itemsToMove).forEach { _ ->
val item = stacks[command.source]?.removeFirst()
item?.let {
stacks[command.destination]?.addFirst(item)
}
}
}
stacks.values.forEach {
print(it.first())
}
}
fun rearrangeCrates9001(stacks: Map<String, ArrayDeque<String>>, commands: List<Command>) {
commands.forEach { command ->
val items = mutableListOf<String>()
(1..command.itemsToMove).forEach { _ ->
stacks[command.source]?.removeFirst()?.let { items.add(it) }
}
items.reversed().forEach {
stacks[command.destination]?.addFirst(it)
}
}
stacks.values.forEach {
print(it.first())
}
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,258 | advent-of-code | Apache License 2.0 |
ceria/10/src/main/kotlin/Solution.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File;
import java.util.Stack;
val matches = mapOf<Char, Char>(
')' to '(',
']' to '[',
'}' to '{',
'>' to '<'
)
val leftChars = matches.values.toSet()
val corruptedValues = mapOf<Char, Int>(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137
)
val scoreValues = mapOf<Char, Int>(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4
)
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
println("Solution 1: " + solution1(input))
println("Solution 2: " + solution2(input))
// CANNOT USE STRING INTERPLATION BECAUSE OF SPECIAL CHARACTERS IN THE INPUT
// println("Solution 1: ${solution1(input)}")
// println("Solution 2: ${solution2(input)}")
}
private fun solution1(input: List<String>) :Int {
var corrupted = mutableListOf<Char>()
for (line in input) {
val syntax = Stack<Char>()
for (c in line) {
if (c in leftChars) {
syntax.push(c)
} else {
val shouldMatch = syntax.pop()
if (!shouldMatch.equals(matches.get(c))) {
corrupted.add(c)
break
}
}
}
}
var corruptedCount = corrupted.groupingBy { it }.eachCount()
var sum = 0
for ((k, v) in corruptedValues) {
sum += corruptedCount.get(k)!! * v
}
return sum
}
private fun solution2(input: List<String>) :Long {
val reversedMatches = matches.entries.associate { (key, value) -> value to key }
val scores = mutableListOf<Long>()
for (line in input) {
val syntax = Stack<Char>()
var broke = false
for (c in line) {
if (c in leftChars) {
syntax.push(c)
} else {
val shouldMatch = syntax.pop()
if (!shouldMatch.equals(matches.get(c))) {
broke = true
break
}
}
}
if (!broke) {
var completion = ""
while (!syntax.isEmpty()) {
val match = syntax.pop()
completion += reversedMatches.get(match)
}
var score = 0L
for (c in completion) {
score = (score * 5) + scoreValues.get(c)!!
}
scores.add(score)
}
}
scores.sort()
return scores.get(scores.size/2) // since the list is 0 based, dividing the size by 2 and ignoring the remainder gives the middle index.
} | 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 2,559 | advent-of-code-2021 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2017/Day03.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2017
import se.saidaspen.aoc.util.Day
import kotlin.math.absoluteValue
import kotlin.math.floor
import kotlin.math.pow
fun main() = Day03.run()
object Day03 : Day(2017, 3) {
private val directions = arrayOf(Pair(0, 1), Pair(-1, 0), Pair(0, -1), Pair(1, 0))
override fun part1(): Any {
val target = input.toInt()
var sideLen = 1
while (sideLen.toDouble().pow(2) < target) sideLen += 2
val corner = sideLen.toDouble().pow(2).toInt()
val steps = corner - target
val arm = floor(steps.toDouble() / (sideLen - 1).toDouble()).toInt()
val midOnArm = (corner - (sideLen - 1) / 2) - ((sideLen - 1) * arm)
val distanceToMid = (midOnArm - target).absoluteValue
val distanceToLevel = ((sideLen - 1) / 2)
return distanceToLevel + distanceToMid
}
override fun part2(): Any {
val target = input.toInt()
val map = HashMap<Pair<Int, Int>, Int>().withDefault { 0 }
var sideLen = 1
var currPos = Pair(0, 0)
var step = 0
var direction = 0
while (true) {
val value = valueOf(currPos, map)
if (value > target) return value
map[currPos] = value
if (step == sideLen.toDouble().pow(2).toInt() - sideLen.minus(2).toDouble().pow(2).toInt()) {
currPos = Pair(currPos.first + 1, currPos.second)
sideLen += 2
direction = 0
step = 1
} else {
if (step % (sideLen - 1) == 0) direction = (direction + 1) % directions.size
currPos = Pair(currPos.first + directions[direction].first, currPos.second + directions[direction].second)
step++
}
}
}
// Get all the neighbouring cells values, default value is 0 if no value exist
private fun valueOf(pos: Pair<Int, Int>, map: Map<Pair<Int, Int>, Int>): Int {
val value = map.getValue(Pair(pos.first, pos.second + 1)) +
map.getValue(Pair(pos.first, pos.second - 1)) +
map.getValue(Pair(pos.first - 1, pos.second + 1)) +
map.getValue(Pair(pos.first - 1, pos.second - 1)) +
map.getValue(Pair(pos.first - 1, pos.second)) +
map.getValue(Pair(pos.first + 1, pos.second + 1)) +
map.getValue(Pair(pos.first + 1, pos.second - 1)) +
map.getValue(Pair(pos.first + 1, pos.second))
return if (value > 0) value else 1
}
} | 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,536 | adventofkotlin | MIT License |
logger/core/src/main/kotlin/org/sollecitom/chassis/logger/core/implementation/datastructure/Trie.kt | sollecitom | 669,483,842 | false | {"Kotlin": 831362, "Java": 30834} | package org.sollecitom.chassis.logger.core.implementation.datastructure
internal interface Trie {
/**
* Returns the word in the trie with the longest prefix in common to the given word.
*/
fun searchLongestPrefixWord(word: String): String
/**
* Returns the longest prefix in the trie common to the word.
*/
fun searchLongestPrefix(word: String): String
/**
* Returns if the word is in the trie.
*/
fun search(word: String): Boolean
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
fun searchWithPrefix(prefix: String): Boolean
interface Mutable : Trie {
/**
* Inserts a word into the trie.
*/
fun insert(word: String)
}
}
internal fun trieOf(vararg words: String): Trie = TrieNodeTree().apply { words.forEach { insert(it) } }
internal fun mutableTrieOf(vararg words: String): Trie.Mutable = TrieNodeTree().apply { words.forEach { insert(it) } }
internal fun mutableTrieOf(words: Iterable<String>): Trie.Mutable = TrieNodeTree().apply { words.forEach { insert(it) } }
private class TrieNodeTree : Trie.Mutable {
private val root: TrieNode = TrieNode()
override fun insert(word: String) {
var node: TrieNode = root
for (element in word) {
if (!node.containsKey(element)) {
node.put(element, TrieNode())
}
node = node[element]!!
}
node.setEnd()
}
override fun searchLongestPrefixWord(word: String): String {
var node = root
val prefixes = mutableListOf<String>()
val currentPrefix = StringBuilder()
for (element in word) {
if (node.containsKey(element)) {
if (node.isEnd) {
prefixes += currentPrefix.toString()
}
currentPrefix.append(element)
node = node[element]!!
} else {
if (node.isEnd) {
prefixes += currentPrefix.toString()
}
return prefixes.maxByOrNull(String::length) ?: ""
}
}
return ""
}
override fun searchLongestPrefix(word: String): String {
var node = root
val currentPrefix = StringBuilder()
for (element in word) {
if (node.containsKey(element) && node.links.size == 1) {
currentPrefix.append(element)
node = node[element]!!
} else {
return currentPrefix.toString()
}
}
return ""
}
override fun search(word: String): Boolean {
val node = searchPrefix(word)
return node != null && node.isEnd
}
override fun searchWithPrefix(prefix: String): Boolean {
val node = searchPrefix(prefix)
return node != null
}
private fun searchPrefix(word: String): TrieNode? {
var node: TrieNode? = root
for (element in word) {
node = if (node!!.containsKey(element)) {
node[element]
} else {
return null
}
}
return node
}
}
private class TrieNode private constructor(val links: MutableMap<Char, TrieNode> = mutableMapOf(), isEnd: Boolean = false) {
constructor() : this(mutableMapOf(), false)
var isEnd = isEnd
private set
fun containsKey(ch: Char): Boolean = links[ch] != null
operator fun get(ch: Char): TrieNode? = links[ch]
fun put(ch: Char, node: TrieNode) {
links[ch] = node
}
fun setEnd() {
isEnd = true
}
fun clone(): TrieNode = TrieNode(links.mapValues { it.value.clone() }.toMutableMap(), isEnd)
} | 0 | Kotlin | 0 | 2 | e4e3403e46f7358a03c8ee3520b3b94be679792b | 3,766 | chassis | MIT License |
src/main/kotlin/com/github/michaelbull/advent2021/day14/Polymer.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day14
private fun <T, K> Grouping<T, K>.eachCountLong(): Map<K, Long> {
return fold(0L) { count, _ -> count + 1 }
}
fun String.toPolymer(): Polymer {
return Polymer(
elements = groupingBy { it }.eachCountLong(),
pairs = zipWithNext().groupingBy { it }.eachCountLong()
)
}
data class Polymer(
val elements: Map<Char, Long>,
val pairs: Map<ElementPair, Long>
) {
val leastCommonQuantity: Long
get() = elements.minOf(Map.Entry<Char, Long>::value)
val mostCommonQuantity: Long
get() = elements.maxOf(Map.Entry<Char, Long>::value)
fun step(insertions: InsertionMap): Polymer {
val nextElements = elements.toMutableMap()
val nextPairs = mutableMapOf<Pair<Char, Char>, Long>()
for ((pair, count) in pairs) {
val insertion = insertions[pair] ?: continue
nextPairs.increment(pair.first to insertion, count)
nextPairs.increment(insertion to pair.second, count)
nextElements.increment(insertion, count)
}
return Polymer(nextElements, nextPairs)
}
fun stepSequence(insertions: InsertionMap): Sequence<Polymer> {
return generateSequence(this) { polymer ->
polymer.step(insertions)
}
}
private fun <K> MutableMap<K, Long>.increment(key: K, amount: Long) {
val value = getOrDefault(key, 0)
return set(key, value + amount)
}
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 1,479 | advent-2021 | ISC License |
src/Day10.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | import kotlin.math.abs
fun main() {
val input = readInput("Day10")
fun part1(input: List<String>): Int {
val reg = calculateRegister(input)
return (20..220 step 40).map { reg[it] * it }.sum()
}
// return 40x6 CRT screen seperated by newline
fun part2(input: List<String>): String {
val reg = calculateRegister(input)
return (1..240)
.joinToString("") { time -> if (abs(reg[time] - (time - 1) % 40) <= 1) "#" else "." }
.chunked(40)
.joinToString("\n")
}
val inputTest = readInput("Day10_test")
check(part1(inputTest) == 13140)
val part2image = """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
check(part2(inputTest) == part2image)
println("Part 1")
println(part1(input))
println("Part 2")
println(part2(input))
}
/** return List<int> where list[idx] is value of register at *start* of cycle `idx` (idx starts at 1) */
private fun calculateRegister(input: List<String>): List<Int> {
return listOf(1) + input.map { it.split(" ") }
.flatMap { if (it.size == 2) listOf(0, it[1].toInt()) else listOf(0) }
.runningFold(1) { acc, inc -> acc + inc }
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 1,471 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/aoc2022/Day8.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2022
import days.Day
class Day8 : Day(2022, 8) {
override fun partOne(): Any {
return calculateVisibleTrees(inputList)
}
override fun partTwo(): Any {
return calculateHighestScenicScore(inputList)
}
fun calculateVisibleTrees(input: List<String>): Int {
val forest = readForest(input)
var visible = (forest.size*forest.size) - (forest.size - 2) * (forest.size - 2)
for (y in 1 until forest.size - 1) {
for (x in 1 until forest[y].size - 1) {
if (checkVisibilityInDirection(forest, x, y, -1, 0)) visible++
else if (checkVisibilityInDirection(forest, x, y, 1, 0)) visible++
else if (checkVisibilityInDirection(forest, x, y, 0, 1)) visible++
else if (checkVisibilityInDirection(forest, x, y, 0, -1)) visible++
}
}
return visible
}
private fun checkVisibilityInDirection(forest: Array<Array<Int>>, x: Int, y: Int, xDelta: Int, yDelta: Int): Boolean {
val height = forest[x][y]
if (xDelta != 0) {
var i = x + xDelta
while (i in forest.indices) {
if (height <= forest[i][y]) return false
i += xDelta
}
} else {
var i = y + yDelta
while (i in forest.indices) {
if (height <= forest[x][i]) return false
i += yDelta
}
}
return true
}
fun calculateHighestScenicScore(input: List<String>): Int {
val forest = readForest(input)
var highestScenicScore = 0
for (y in 1 until forest.size - 1) {
for (x in 1 until forest[y].size - 1) {
val score =
calculateSightDistanceForDirection(forest, x, y, 1, 0) *
calculateSightDistanceForDirection(forest, x, y, -1, 0) *
calculateSightDistanceForDirection(forest, x, y, 0, 1) *
calculateSightDistanceForDirection(forest, x, y, 0, -1)
if (score > highestScenicScore) highestScenicScore = score
}
}
return highestScenicScore
}
private fun calculateSightDistanceForDirection(forest: Array<Array<Int>>, x: Int, y: Int, xDelta: Int, yDelta: Int): Int {
val height = forest[x][y]
var sightDistance = 0
if (xDelta != 0) {
var i = x + xDelta
while (i in forest.indices) {
if (height <= forest[i][y]) return sightDistance + 1
i += xDelta
sightDistance++
}
} else {
var i = y + yDelta
while (i in forest.indices) {
if (height <= forest[x][i]) return sightDistance + 1
i += yDelta
sightDistance++
}
}
return sightDistance
}
private fun readForest(input: List<String>): Array<Array<Int>> {
val forest = Array(input.size) {
Array(input.first().length) { 0 }
}
var x = 0
var y = 0
input.forEach { line ->
line.forEach { c ->
forest[x][y] = c.toString().toInt()
x++
}
y++
x = 0
}
return forest
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,353 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/year_2022/day_20/Day20.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_20
import readInput
class Day20(input: List<String>) {
private val encryptedData = parseInput(input)
/**
* @return
*/
fun solutionOne(): Long {
val mutable = encryptedData.toMutableList()
encryptedData.forEach { (initialIndex, value) ->
val currentIndex = mutable.indexOfFirst { (originalIndex, _) -> initialIndex == originalIndex }
mutable.removeAt(currentIndex)
var newPosition = (currentIndex + value) % (encryptedData.size -1)
if (newPosition <= 0) {
newPosition += encryptedData.size - 1
}
mutable.add(newPosition.toInt(), initialIndex to value)
}
val indexOfZero = mutable.indexOfFirst { (_, value) -> value == 0L }
val a = mutable[(indexOfZero + 1_000) % encryptedData.size].second
val b = mutable[(indexOfZero + 2_000) % encryptedData.size].second
val c = mutable[(indexOfZero + 3_000) % encryptedData.size].second
return a + b + c
}
/**
* @return
*/
fun solutionTwo(): Long {
val mutable = encryptedData
.map { it.first to it.second * 811589153 }
.toMutableList()
for (i in 1..10) {
encryptedData.forEach { (initialIndex, _) ->
val currentIndex = mutable.indexOfFirst { (originalIndex, _) -> initialIndex == originalIndex }
val removed = mutable.removeAt(currentIndex)
var newPosition = (currentIndex + removed.second) % (encryptedData.size - 1)
if (newPosition <= 0) {
newPosition += encryptedData.size - 1
}
mutable.add(newPosition.toInt(), initialIndex to removed.second)
}
}
val indexOfZero = mutable.indexOfFirst { (_, value) -> value == 0L }
val a = mutable[(indexOfZero + 1_000) % encryptedData.size].second
val b = mutable[(indexOfZero + 2_000) % encryptedData.size].second
val c = mutable[(indexOfZero + 3_000) % encryptedData.size].second
return a + b + c
}
private fun parseInput(text: List<String>): List<Pair<Int, Long>> {
return text.mapIndexed { index, string -> index to Integer.parseInt(string).toLong() }
}
}
fun main() {
val inputText = readInput("year_2022/day_20/Day20.txt")
val day20 = Day20(inputText)
val solutionOne = day20.solutionOne()
println("Solution 1: $solutionOne")
val solutionTwo = day20.solutionTwo()
println("Solution 2: $solutionTwo")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 2,599 | advent_of_code | Apache License 2.0 |
src/main/kotlin/io/dmitrijs/aoc2022/Day24.kt | lakiboy | 578,268,213 | false | {"Kotlin": 76651} | package io.dmitrijs.aoc2022
import io.dmitrijs.aoc2022.Direction.DOWN
import io.dmitrijs.aoc2022.Direction.LEFT
import io.dmitrijs.aoc2022.Direction.RIGHT
import io.dmitrijs.aoc2022.Direction.UP
class Day24(input: List<String>) {
private val grid = input.drop(1).dropLast(1).map { it.drop(1).dropLast(1) }
private val maxX = grid.first().length - 1
private val maxY = grid.size - 1
private val loop = Pair(maxX + 1, maxY + 1).lcm()
// Greedy, but simple.
private val blizzardsInTime = blizzardPositions(loop)
fun puzzle1() = bfs(Point(0, -1).inTime(0), Point(maxX, maxY))
fun puzzle2(): Int {
val t1 = bfs(Point(0, -1).inTime(0), Point(maxX, maxY))
val t2 = bfs(Point(maxX, maxY + 1).inTime(t1), Point(0, 0))
val t3 = bfs(Point(0, -1).inTime(t1 + t2), Point(maxX, maxY))
return t1 + t2 + t3
}
private fun bfs(start: PointInTime, goal: Point): Int {
val queue = ArrayDeque(listOf(start to 0))
val visited = hashSetOf<PointInTime>()
while (queue.isNotEmpty()) {
val (pit, taken) = queue.removeFirst()
val (expedition, time) = pit
if (expedition == goal) {
return taken + 1
}
val positions = expedition.orthogonalNeighbours().filterNot { it.outOfBounds }
(positions + expedition)
.map { it.inTime(time + 1) }
.filterNot { it in visited || it in blizzardsInTime }
.forEach {
visited.add(it)
queue.add(it to taken + 1)
}
}
return -1
}
private fun blizzardPositions(t: Int) = grid.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, symbol ->
symbol.takeUnless { it == SPACE }?.let {
var p = Point(x, y)
val d = Direction.of(it)
(0 until t).map { time ->
p.inTime(time).also { p = (p + d).wrap() }
}
}
}.flatten()
}.toSet()
private fun Pair<Int, Int>.lcm(): Int {
var lcm = if (first > second) first else second
while (true) {
if (lcm % first == 0 && lcm % second == 0) {
return lcm
}
lcm++
}
}
private val Point.outOfBounds get() = x < 0 || y < 0 || x > maxX || y > maxY
private fun Point.wrap() = when {
x < 0 -> copy(x = maxX)
x > maxX -> copy(x = 0)
y < 0 -> copy(y = maxY)
y > maxY -> copy(y = 0)
else -> this
}
private fun Point.inTime(t: Int) = PointInTime(this, t % loop)
private fun Direction.Companion.of(symbol: Char) = when (symbol) {
'>' -> RIGHT
'<' -> LEFT
'v' -> DOWN
'^' -> UP
else -> error("Unsupported direction symbol: $symbol.")
}
private data class PointInTime(val p: Point, val t: Int)
private companion object {
const val SPACE = '.'
}
}
| 0 | Kotlin | 0 | 1 | bfce0f4cb924834d44b3aae14686d1c834621456 | 3,029 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/wabradshaw/claptrap/design/SubstringGenerator.kt | wabradshaw | 154,681,482 | false | null | package com.wabradshaw.claptrap.design
import java.lang.Math.min
/**
* A SubstringGenerator is used to find substrings of words that are candidates for substitution. These will later be
* reduced to just the substrings representing actual words. The default setting is to select substrings at the start
* and end of the word with between 2 and 5 characters (inclusive).
*
* @property maxLength The maximum number of characters in a substring. Inclusive.
* @property minLength The minimum number of characters in a substring. Inclusive.
*/
class SubstringGenerator(val maxLength: Int = 5,
val minLength: Int = 2){
/**
* Gets all substrings in a word (or series of words) which are suitable for substitution. The results are in order
* of length, longest to shortest. Ties are given to the substring from the start of the original word. For example:
* getSubstrings("abcdefgh") -> "abcde", "defgh", "abcd", "efgh", "abc", "fgh"
*
* Duplicate words are ignored, e.g. in "tuktuk", the word "tuk" would only appear once as a substring.
*
* In situations where the input contains a series of words each word is considered separately. Ordering is the
* same as for a single word: by length, with start before end.
* E.g. "washing machine" would start "washe", "machi", "shing", "chine", "wash", "mach", "hing" ...
*
* Note that this only gathers the substrings, it doesn't ensure that they are real words, or phonetically similar
* to the original word.
*
* @param original The word (or series of words) to find substrings from.
* @return A list of substrings at either the start or end of the word that could be potential substitutions.
*/
fun getSubstrings(original: String): List<String> {
val resultSet = LinkedHashSet<String>()
val words = original.split(" ")
for (i in maxLength downTo minLength) {
val options = words.filter{w -> w.length >= i}
options.forEach{w -> resultSet.add(w.substring(0, i))}
options.forEach{w -> resultSet.add(w.substring(w.length - i))}
}
return resultSet.toList()
}
} | 0 | Kotlin | 0 | 0 | 7886787603e477d47ea858a8d9c76e11c4c25fe3 | 2,245 | claptrap | Apache License 2.0 |
src/day25/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day25
import java.io.File
fun main() {
val lines = File("src/day25/input.txt").readLines()
val seafloor = Seafloor(lines[0].length, lines.size,
Herd.values().associateWith { herd -> herd.parse(lines) }.toMutableMap())
while (seafloor.move()) {}
println(seafloor.steps)
}
data class Seafloor(val width: Int, val height: Int, val cucumbers: MutableMap<Herd, Set<Coord>>, var steps: Int = 0)
data class Coord(val x: Int, val y: Int)
enum class Herd(val ch: Char, val delta: Coord) {
EAST('>', Coord(1, 0)),
SOUTH('v', Coord(0, 1))
}
fun Herd.parse(lines: List<String>) =
lines.mapIndexed { j, row -> row.toList().mapIndexedNotNull { i, c -> if (c == ch) Coord(i, j) else null } }
.flatten().toSet()
fun Seafloor.empty(coord: Coord) = cucumbers.values.none { coords -> coords.contains(coord) }
fun Seafloor.print() {
for (y in 0 until height) {
for (x in 0 until width) {
print(Herd.values()
.mapNotNull { if (cucumbers[it]!!.contains(Coord(x, y))) it.ch else null }
.firstOrNull() ?: '.')
}
println()
}
println()
}
fun Seafloor.move(): Boolean {
var moved = false
Herd.values().forEach { herd ->
cucumbers[herd] = cucumbers[herd]!!.map { coord ->
Coord((coord.x + herd.delta.x) % width, (coord.y + herd.delta.y) % height)
.let { newCoord -> if (empty(newCoord)) newCoord.also { moved = true } else coord }
}.toSet()
}
steps++
return moved
} | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 1,544 | advent-of-code-2021 | MIT License |
src/test/kotlin/com/dambra/adventofcode2018/day17/UndergroundMap.kt | pauldambra | 159,939,178 | false | null | package com.dambra.adventofcode2018.day17
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
internal class UndergroundMap {
@Test
fun `can parse the example scan`() {
val exampleInput = """
x=495, y=2..7
y=7, x=495..501
x=501, y=3..7
x=498, y=2..4
x=506, y=1..2
x=498, y=10..13
x=504, y=10..13
y=13, x=498..504
""".trimIndent()
val scan = UndergroundScan(exampleInput)
assertThat(scan.print()).isEqualTo("""
......+.......
............#.
.#..#.......#.
.#..#..#......
.#..#..#......
.#.....#......
.#.....#......
.#######......
..............
..............
....#.....#...
....#.....#...
....#.....#...
....#######...
""".trimIndent())
}
}
data class Coordinate(val x: Int, val y: Int)
data class Vein(val xRange: IntRange, val yRange: IntRange) {
val coordinates: List<Coordinate>
init {
val cs = mutableListOf<Coordinate>()
xRange.forEach { x ->
yRange.forEach { y ->
cs.add(Coordinate(x, y))
}
}
coordinates = cs.toList()
}
companion object {
fun from(a: String, b: String) : Vein {
var xRange: IntRange? = null
var yRange: IntRange? = null
val aParts = a.split("=")
if (aParts[0] == "x") {
xRange = singleValueVeinRange(aParts)
} else {
yRange = singleValueVeinRange(aParts)
}
val bParts = b.split("=")
if (bParts[0] == "x") {
xRange = twoValueVeinRange(bParts)
} else {
yRange = twoValueVeinRange(bParts)
}
println("found $xRange and $yRange")
return Vein(xRange!!, yRange!!)
}
private fun twoValueVeinRange(
bParts: List<String>
): IntRange? {
val rangeParts = bParts[1]
.split("..")
.map { it.trim() }
.map { it.toInt() }
return rangeParts[0]..rangeParts[1]
}
private fun singleValueVeinRange(
aParts: List<String>
): IntRange {
val x = aParts[1].trim().toInt()
return x..x
}
}
}
class UndergroundScan(scanResults: String) {
val spring = Coordinate(500, 0)
val veins: Set<Coordinate>
init {
veins = scanResults.split("\n")
.map { it.split(", ") }
.map { Vein.from(it[0], it[1])}
.map { v -> v.coordinates }
.flatten()
.toSet()
}
fun print(): String {
val maxX = veins.maxBy(Coordinate::x)!!.x
val maxY = veins.maxBy(Coordinate::y)!!.y
var s = ""
(0..maxX).forEach { x ->
(0..maxY).forEach { y ->
val c = Coordinate(x, y)
s += when {
c == spring -> "+"
veins.contains(c) -> "#"
else -> "."
}
}
s + "\n"
}
return s
}
}
| 0 | Kotlin | 0 | 1 | 7d11bb8a07fb156dc92322e06e76e4ecf8402d1d | 3,097 | adventofcode2018 | The Unlicense |
src/day02/Day02_Part1.kt | m-jaekel | 570,582,194 | false | {"Kotlin": 13764} | package day02
import readInput
fun main() {
/**
* A Y
* B X
* C Z
*
* A,X -> Rock (1)
* B,Y -> Paper (2)
* C,Z -> Scissors (3)
*
* lost -> 0
* draw -> 3
* win -> 6
*
*/
fun part1(input: List<String>): Int {
var score = 0
input.forEach {
val shapes: List<String> = it.chunked(1)
score += checkWin(shapes[0], shapes[2]) + getShapeScore(shapes[2])
}
return score
}
val testInput = readInput("day02/test_input")
check(part1(testInput) == 15)
val input = readInput("day02/input")
println(part1(input))
}
private fun checkWin(player1: String, player2: String): Int = when {
player1 == "A" && player2 == "Y" -> 6
player1 == "A" && player2 == "X" -> 3
player1 == "A" && player2 == "Z" -> 0
player1 == "B" && player2 == "X" -> 0
player1 == "B" && player2 == "Y" -> 3
player1 == "B" && player2 == "Z" -> 6
player1 == "C" && player2 == "X" -> 6
player1 == "C" && player2 == "Z" -> 3
player1 == "C" && player2 == "Y" -> 0
else -> throw Exception("invalid")
}
private fun getShapeScore(shape: String): Int = when (shape) {
"X" -> 1
"Y" -> 2
else -> 3
}
| 0 | Kotlin | 0 | 1 | 07e015c2680b5623a16121e5314017ddcb40c06c | 1,250 | AOC-2022 | Apache License 2.0 |
src/main/kotlin/com/github/dangerground/aoc2020/Day22.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
import java.util.*
fun main() {
val process = Day22(DayInput.batchesOfStringList(22))
println("result part 1: ${process.part1()}")
println("result part 2: ${process.part2()}")
}
class Day22(val input: List<List<String>>) {
val player1: Queue<Int> = LinkedList(input[0].drop(1).map { it.toInt() }.toList())
val player2: Queue<Int> = LinkedList(input[1].drop(1).map { it.toInt() }.toList())
fun part1(): Int {
while (!player1.isEmpty() && !player2.isEmpty()) {
if (player1.first() > player2.first()) {
player1.add((player1.remove()))
player1.add(player2.remove())
} else {
player2.add((player2.remove()))
player2.add(player1.remove())
}
}
return calcResult()
}
private fun calcResult() = player1.reversed().mapIndexed { idx, it -> (idx + 1) * it }.sum() + player2.reversed()
.mapIndexed { idx, it -> (idx + 1) * it }.sum()
fun part2(): Long {
val player1: Queue<Long> = LinkedList(input[0].drop(1).map { it.toLong() }.toList())
val player2: Queue<Long> = LinkedList(input[1].drop(1).map { it.toLong() }.toList())
playRecursive(player1, player2)
println("\n== Post-game results ==")
println("Player 1's deck: $player1")
println("Player 2's deck: $player2")
return calc(player1) + calc(player2)
}
private fun calc(player1: Queue<Long>) =
player1.reversed().mapIndexed { idx, it -> (idx + 1) * it }.sum()
var game = 0
fun playRecursive(rec1: Queue<Long>, rec2: Queue<Long>): Int {
game++
val thisgame = game
println()
println("=== Game $thisgame ===")
val played1Rounds = mutableSetOf<Long>()
val played2Rounds = mutableSetOf<Long>()
var round = 0
do {
round++
println()
println("-- Round $round (Game $thisgame) --")
println("Player 1's deck: $rec1")
println("Player 2's deck: $rec2")
val calc1 = rec1.hashCode().toLong()
val calc2 = rec2.hashCode().toLong()
// case 1: remember rounds
if (played1Rounds.contains(calc1) && played2Rounds.contains(calc2)) {
return 1
}
played1Rounds.add(calc1)
played2Rounds.add(calc2)
// draw cards
val card1 = rec1.remove()
val card2 = rec2.remove()
println("Player 1 plays: $card1")
println("Player 2 plays: $card2")
if (rec1.size >= card1 && rec2.size >= card2) {
println("Playing a sub-game to determine the winner...")
val winner = playRecursive(
LinkedList(rec1.toList().subList(0, card1.toInt())),
LinkedList(rec2.toList().subList(0, card2.toInt()))
)
println("The winner of game ${thisgame + 1} is player $winner!")
println()
println("...anyway, back to game 1.")
if (winner == 1) {
println("Player 1 wins round $round of game $thisgame!")
rec1.add(card1)
rec1.add(card2)
} else { // winer == 2
println("Player 2 wins round $round of game $thisgame!")
rec2.add(card2)
rec2.add(card1)
}
} else {
// determined
if (card1 > card2) {
println("Player 1 wins round $round of game $thisgame!")
rec1.add(card1)
rec1.add(card2)
} else {
println("Player 2 wins round $round of game $thisgame!")
rec2.add(card2)
rec2.add(card1)
}
}
} while (!rec1.isEmpty() && !rec2.isEmpty())
return if (rec1.isEmpty()) 2 else 1
}
}
class Win(val winner: Int?, val cards: List<Int>?, val done: Boolean?, result: Int? = null)
| 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 4,231 | adventofcode-2020 | MIT License |
grind-75-kotlin/src/main/kotlin/BalancedBinaryTree.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | import commonclasses.TreeNode
import kotlin.math.abs
/**
* Given a binary tree, determine if it is
* height-balanced
* .
*
*
*
* Example 1:
*
*
* Input: root = [3,9,20,null,null,15,7]
* Output: true
* Example 2:
*
*
* Input: root = [1,2,2,3,3,null,null,4,4]
* Output: false
* Example 3:
*
* Input: root = []
* Output: true
*
*
* Constraints:
*
* The number of nodes in the tree is in the range [0, 5000].
* -104 <= Node.val <= 104
* @see <a href="https://leetcode.com/problems/balanced-binary-tree/">LeetCode</a>
*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
fun isBalanced(root: TreeNode?): Boolean {
return heightOfNode(root) != -1
}
private fun heightOfNode(node: TreeNode?): Int {
if (node == null) {
return 0
}
val heightOfLeftSubtree = heightOfNode(node.left)
val heightOfRightSubtree = heightOfNode(node.right)
return if (heightOfLeftSubtree == -1 || heightOfRightSubtree == -1 || abs(heightOfLeftSubtree - heightOfRightSubtree) > 1) {
-1
} else {
1 + maxOf(heightOfLeftSubtree, heightOfRightSubtree)
}
}
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 1,262 | grind-75 | Apache License 2.0 |
src/main/kotlin/aoc/day5/SupplyStacks.kt | hofiisek | 573,543,194 | false | {"Kotlin": 17421} | package aoc.day5
import aoc.loadInput
import aoc.matchesNot
import java.io.File
/**
* https://adventofcode.com/2022/day/5
*
* @author <NAME>
*/
typealias Stacks = Map<Int, ArrayDeque<Crate>>
data class Crate(val stackId: Int, val id: String)
data class Move(val quantity: Int, val from: Int, val to: Int)
infix fun Stacks.perform(move: Move): Stacks {
val from = getValue(move.from)
val to = getValue(move.to)
repeat(move.quantity) {
from.removeFirst().also(to::addFirst)
}
return this
}
infix fun Stacks.performBulk(move: Move): Stacks {
val from = getValue(move.from)
val to = getValue(move.to)
(0 until move.quantity)
.map { from.removeFirst() }
.reversed()
.forEach(to::addFirst)
return this
}
fun List<String>.readStacks(): Stacks = takeWhile { it.matchesNot("[\\s\\d]+".toRegex()) }
.flatMap(String::readLineStacks)
.groupBy(Crate::stackId)
.mapValues { (_, crates) -> ArrayDeque(crates) }
.toSortedMap()
fun String.readLineStacks(): List<Crate> = chunked(4)
.map(String::trim)
.mapIndexedNotNull { stackIdx, crate ->
if (crate.isBlank())
null
else
".*([A-Z]).*".toRegex()
.matchEntire(crate)
?.groupValues
?.last()
?.let { crateId -> Crate(stackIdx + 1, crateId) }
?: throw IllegalArgumentException("Illegal crate format: $crate")
}
fun List<String>.readMoves(): List<Move> = filter { it.startsWith("move") }
.map { it.replace("[move|from|to|]+".toRegex(), "").trim() }
.map { it.split("\\s+".toRegex()).map(String::toInt) }
.map { (quantity, from, to) -> Move(quantity, from, to) }
fun File.part1() = readLines()
.let { lines ->
lines.readMoves().fold(lines.readStacks()) { stacks, move -> stacks perform move }
}
.values
.mapNotNull { it.firstOrNull()?.id }
.joinToString("")
.also(::println)
fun File.part2() = readLines()
.let { lines ->
lines.readMoves().fold(lines.readStacks()) { stacks, move -> stacks performBulk move }
}
.values
.mapNotNull { it.firstOrNull()?.id }
.joinToString("")
.also(::println)
fun main() {
with(loadInput(day = 5)) {
part1()
part2()
}
} | 0 | Kotlin | 0 | 2 | 5908a665db4ac9fc562c44d6907f81cd3cd8d647 | 2,320 | Advent-of-code-2022 | MIT License |
2023/7/solve-1.kts | gugod | 48,180,404 | false | {"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595} | import java.io.File
import kotlin.math.pow
enum class HandType(val strongness: Int) {
FiveOfAKind(7),
FourOfAKind(6),
FullHouse(5),
ThreeOfAKind(4),
TwoPair(3),
OnePair(2),
HighCard(1);
companion object {
fun fromString(hand: String) : HandType {
val freq = hand.fold(hashMapOf<Char,Int>()) { f,c -> f.apply { set(c, f.getOrDefault(c,0)+1) } }
return when(freq.keys.count()) {
1 -> FiveOfAKind
2 -> when(freq.values.max()) {
4 -> FourOfAKind
else -> FullHouse
}
3 -> when(freq.values.max()) {
3 -> ThreeOfAKind
else -> TwoPair
}
4 -> OnePair
else -> HighCard
}
}
}
}
fun cardRank(c: Char) = "23456789TJQKA".indexOf(c)
fun handToNum(hand: String) =
HandType.fromString(hand).strongness * 13f.pow(5) + hand.mapIndexed { i,c -> cardRank(c) * (13f.pow(4-i)) }.sum()
File(args.getOrNull(0) ?: "input")
.readLines()
.map { it.split(" ") }
.sortedBy { handToNum(it[0]) }
.mapIndexed { i,xs -> xs[1].toInt() * (i + 1) }
.sum()
.run { println(this) }
| 0 | Raku | 1 | 5 | ca0555efc60176938a857990b4d95a298e32f48a | 1,287 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/Day06.kt | rbraeunlich | 573,282,138 | false | {"Kotlin": 63724} | fun main() {
fun part1(input: List<String>): Int {
val buffer = mutableListOf<Char>()
input.first().forEachIndexed { index, c ->
if (buffer.size < 4) {
buffer.add(c)
} else if (buffer.size == 4 && buffer.allDifferent()) {
return index
} else {
buffer.removeFirst()
buffer.add(c)
}
}
return -1
}
fun part2(input: List<String>): Int {
val buffer = mutableListOf<Char>()
input.first().forEachIndexed { index, c ->
if (buffer.size < 14) {
buffer.add(c)
} else if (buffer.size == 14 && buffer.allDifferent()) {
return index
} else {
buffer.removeFirst()
buffer.add(c)
}
}
return -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 5)
check(part2(testInput) == 23)
val testInput2 = readInput("Day06_test2")
check(part1(testInput2) == 6)
check(part2(testInput2) == 23)
val testInput3 = readInput("Day06_test3")
check(part1(testInput3) == 10)
check(part2(testInput3) == 29)
val testInput4 = readInput("Day06_test4")
check(part1(testInput4) == 11)
check(part2(testInput4) == 26)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
private fun List<Char>.allDifferent(): Boolean =
this.size == this.toSet().size
| 0 | Kotlin | 0 | 1 | 3c7e46ddfb933281be34e58933b84870c6607acd | 1,592 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | jfiorato | 573,233,200 | false | null | fun main() {
fun part1(input: List<String>): Int {
var total = 0
for (play in input) {
val (col1, col2) = play.split(" ")
val opponent = "ABC".indexOf(col1)
val you = "XYZ".indexOf(col2)
total += you + 1
when ((you - opponent).mod(3)) {
1 -> total += 6
0 -> total += 3
}
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
for (play in input) {
val (col1, col2) = play.split(" ")
val opponent = "ABC".indexOf(col1)
when (col2) {
"X" -> {
total += (opponent - 1).mod(3) + 1
}
"Y" -> {
total += 3
total += opponent + 1
}
"Z" -> {
total += 6
total += (opponent + 1).mod(3) + 1
}
}
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4455a5e9c15cd067d2661438c680b3d7b5879a56 | 1,320 | kotlin-aoc-2022 | Apache License 2.0 |
src/Day02.kt | HaydenMeloche | 572,788,925 | false | {"Kotlin": 25699} | fun main() {
val input = readInput("Day02")
// part one
var partOneScore = 0
input.forEach { line ->
val split = line.split(" ")
val opponentHand = Play.from(split[0])
val myHand = Play.from(split[1])
partOneScore += myHand.score + myHand.computeScore(opponentHand)
}
println("part one score: $partOneScore")
// part two
var partTwoScore = 0
input.forEach { line ->
val split = line.split(" ")
val opponentHand = Play.from(split[0])
val desiredState = DesiredState.from(split[1])
val myHand = opponentHand.computeHand(desiredState)
partTwoScore += myHand.score + myHand.computeScore(opponentHand)
}
println("part two score: $partTwoScore")
}
enum class DesiredState {
WIN,
LOSE,
TIE;
companion object {
fun from(value: String): DesiredState {
return when (value) {
"X" -> LOSE
"Y" -> TIE
"Z" -> WIN
else -> throw Exception()
}
}
}
}
private enum class Play(val score: Int) : Comparable<Play> {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun computeHand(desiredState: DesiredState): Play {
return when (this) {
ROCK -> when (desiredState) {
DesiredState.WIN -> PAPER
DesiredState.LOSE -> SCISSORS
DesiredState.TIE -> this
}
PAPER -> when (desiredState) {
DesiredState.WIN -> SCISSORS
DesiredState.LOSE -> ROCK
DesiredState.TIE -> this
}
SCISSORS -> when (desiredState) {
DesiredState.WIN -> ROCK
DesiredState.LOSE -> PAPER
DesiredState.TIE -> this
}
}
}
fun computeScore(other: Play): Int {
return when (this) {
ROCK -> when (other) {
ROCK -> 3
PAPER -> 0
SCISSORS -> 6
}
PAPER -> when (other) {
ROCK -> 6
PAPER -> 3
SCISSORS -> 0
}
SCISSORS -> when (other) {
ROCK -> 0
PAPER -> 6
SCISSORS -> 3
}
}
}
companion object {
fun from(value: String): Play {
return when (value) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw Exception()
}
}
}
}
| 0 | Kotlin | 0 | 1 | 1a7e13cb525bb19cc9ff4eba40d03669dc301fb9 | 2,609 | advent-of-code-kotlin-2022 | Apache License 2.0 |
kotlin/strings/StringDistances.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package strings
import java.util.Arrays
object StringDistances {
// https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
fun getLCS(x: IntArray, y: IntArray): IntArray {
val m = x.size
val n = y.size
val lcs = Array(m + 1) { IntArray(n + 1) }
for (i in 0 until m) {
for (j in 0 until n) {
if (x[i] == y[j]) {
lcs[i + 1][j + 1] = lcs[i][j] + 1
} else {
lcs[i + 1][j + 1] = Math.max(lcs[i + 1][j], lcs[i][j + 1])
}
}
}
var cnt = lcs[m][n]
val res = IntArray(cnt)
var i = m - 1
var j = n - 1
while (i >= 0 && j >= 0) {
if (x[i] == y[j]) {
res[--cnt] = x[i]
--i
--j
} else if (lcs[i + 1][j] > lcs[i][j + 1]) {
--j
} else {
--i
}
}
return res
}
// https://en.wikipedia.org/wiki/Levenshtein_distance
fun getLevensteinDistance(a: String, b: String): Int {
val m: Int = a.length()
val n: Int = b.length()
val len = Array(m + 1) { IntArray(n + 1) }
for (i in 0..m) {
len[i][0] = i
}
for (j in 0..n) {
len[0][j] = j
}
for (i in 0 until m) {
for (j in 0 until n) {
if (a.charAt(i) === b.charAt(j)) {
len[i + 1][j + 1] = len[i][j]
} else {
len[i + 1][j + 1] = 1 + Math.min(len[i][j], Math.min(len[i + 1][j], len[i][j + 1]))
}
}
}
return len[m][n]
}
// Usage example
fun main(args: Array<String?>?) {
val x = intArrayOf(1, 5, 4, 2, 3, 7, 6)
val y = intArrayOf(2, 7, 1, 3, 5, 4, 6)
val lcs = getLCS(x, y)
System.out.println(Arrays.toString(lcs))
val a = "abc"
val b = "ac"
System.out.println(getLevensteinDistance(a, b))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,071 | codelibrary | The Unlicense |
src/day03/Day03.kt | TimberBro | 572,681,059 | false | {"Kotlin": 20536} | package day03
import readInput
import separateInputByRows
fun main() {
fun part1(input: List<String>): Int {
val result = input.stream()
.map { it.take(it.length / 2) to it.takeLast(it.length / 2) }
.map { it.first.toCharArray().intersect(it.second.asIterable().toSet()).first() }
.map {
when (it) {
in 'a'..'z' -> it.code - 96
in 'A'..'Z' -> it.code - 38
else -> error("Could not transform")
}
}.reduce { t, u -> t + u }
return result.orElseThrow()
}
fun part2(input: List<String>): Int {
val rowsGroups = separateInputByRows(input, 3)
val result = rowsGroups.stream()
// explicitly intersect all three rows
.map { (x, y, z) ->
x
.toCharArray()
.intersect(y.asIterable().toSet())
.intersect(z.asIterable().toSet())
.first()
}
.map {
when (it) {
in 'a'..'z' -> it.code - 96
in 'A'..'Z' -> it.code - 38
else -> error("Could not transform")
}
}.reduce { t, u -> t + u }
return result.orElseThrow()
}
val testInput = readInput("day03/Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("day03/Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 516a98e5067d11f0e6ff73ae19f256d8c1bfa905 | 1,610 | AoC2022 | Apache License 2.0 |
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day14/Day14.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2015.day14
import nl.sanderp.aoc.common.transpose
data class Stats(val speed: Int, val flyTime: Int, val restTime: Int)
val input = mapOf(
"Vixen" to Stats(19, 7, 124),
"Rudolph" to Stats(3, 15, 28),
"Donner" to Stats(19, 9, 164),
"Blitzen" to Stats(19, 9, 158),
"Comet" to Stats(13, 7, 82),
"Cupid" to Stats(25, 6, 145),
"Dasher" to Stats(14, 3, 38),
"Dancer" to Stats(3, 16, 37),
"Prancer" to Stats(25, 6, 143),
)
fun generate(stats: Stats) = sequence {
var distance = 0L
while (true) {
repeat(stats.flyTime) {
distance += stats.speed
yield(distance)
}
repeat(stats.restTime) {
yield(distance)
}
}
}
fun main() {
val limit = 2503
val trajectories = input.mapValues { generate(it.value).take(limit).toList() }
println("Part one: ${trajectories.values.maxOf { it.last() }}")
val scores = Array(limit) { t ->
val distances = trajectories.values.map { it[t] }
val max = distances.max()
distances.map { if (it == max) 1 else 0 }.toTypedArray()
}.transpose()
println("Part two: ${scores.maxOf { it.sum() }}")
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,205 | advent-of-code | MIT License |
src/day12/day12.kt | diesieben07 | 572,879,498 | false | {"Kotlin": 44432} | package day12
import streamInput
import java.util.HashSet
import java.util.PriorityQueue
private val file = "Day12"
//private val file = "Day12Example"
data class Point(val x: Int, val y: Int)
data class Parsed(val grid: List<IntArray>, val start: Point, val end: Point)
private fun parseInput(): Parsed {
return streamInput(file) { lines ->
val rows = ArrayList<IntArray>()
var start: Point? = null
var end: Point? = null
for ((row, line) in lines.withIndex()) {
val rowData = IntArray(line.length)
line.forEachIndexed { col, c ->
val actualChar = when (c) {
'S' -> {
start = Point(col, row)
'a'
}
'E' -> {
end = Point(col, row)
'z'
}
else -> c
}
val i = actualChar - 'a'
rowData[col] = i
}
rows += rowData
}
Parsed(rows, start!!, end!!)
}
}
data class FPoint(val point: Point, val f: Int, val predecessor: FPoint?) : Comparable<FPoint> {
override fun compareTo(other: FPoint): Int {
return f.compareTo(other.f)
}
}
fun Point.withF(f: Int, predecessor: FPoint?): FPoint {
return FPoint(this, f, predecessor)
}
private fun doAStar(grid: List<IntArray>, start: Point, end: Point): ArrayList<Point>? {
val openlist = PriorityQueue<FPoint>()
val closedlist = HashSet<Point>()
openlist.add(start.withF(0, null))
val gScore = HashMap<Point, Int>()
fun Point.successors(): Sequence<Point> {
return sequence {
for ((x, y) in listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))) {
val next = copy(x = this@successors.x + x, y = this@successors.y + y)
if (next.y in 0..grid.lastIndex && next.x in 0..grid[0].lastIndex) {
val myVal = grid[this@successors.y][this@successors.x]
val nextVal = grid[next.y][next.x]
if (nextVal <= myVal + 1) {
yield(next)
}
}
}
}
}
fun expandNode(node: FPoint) {
for (successor in node.point.successors()) {
if (successor in closedlist) continue
val tentativeG = gScore[node.point]!! + 1
val successorG = gScore[successor]
if (successorG != null && tentativeG >= successorG) continue
gScore[successor] = tentativeG
val successorF = successor.withF(tentativeG + 1, node)
if (successorG != null) {
openlist.removeIf { it.point == successor }
}
openlist.add(successorF)
}
}
gScore[start] = 0
var foundEndFNode: FPoint? = null
do {
val currentNode = checkNotNull(openlist.poll())
if (currentNode.point == end) {
// done
foundEndFNode = currentNode
break
}
closedlist.add(currentNode.point)
expandNode(currentNode)
} while (openlist.isNotEmpty())
if (foundEndFNode == null) return null // no path
val path = ArrayList<Point>()
var current: FPoint? = foundEndFNode
while(current != null) {
path.add(current.point)
current = current.predecessor
}
path.reverse()
return path
}
private fun part1() {
val (grid, start, end) = parseInput()
val path = checkNotNull(doAStar(grid, start, end))
println(path)
println(path.size - 1) // steps = points - 1
}
private fun part2() {
val (grid, _, end) = parseInput()
val possibleStarts = grid.flatMapIndexed { row: Int, rowData: IntArray ->
rowData.flatMapIndexed { col, d -> if (d == 0) listOf(Point(col, row)) else listOf() }
}
val minPath = possibleStarts.minOf { start ->
val path = doAStar(grid, start, end)
if (path != null) path.size - 1 else Int.MAX_VALUE
}
println(minPath)
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6 | 4,147 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | dmstocking | 575,012,721 | false | {"Kotlin": 40350} | import java.lang.Exception
fun main() {
fun part1(input: List<String>): Int {
return input
.map { line ->
val first = line.substring(0, line.length/2)
val second = line.substring(line.length/2)
first
.toSet()
.intersect(second.toSet())
.first()
.let {
if (it in 'a'..'z') {
it.code - 96
} else {
it.code - 64 + 26
}
}
}
.sum()
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { sacks ->
sacks.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.first()
.let {
if (it in 'a'..'z') {
it.code - 96
} else {
it.code - 64 + 26
}
}
}
.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 | e49d9247340037e4e70f55b0c201b3a39edd0a0f | 1,434 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2023/Day17.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 17 - Clumsy Crucible
* Problem Description: http://adventofcode.com/2023/day/17
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day17/
*/
package com.ginsberg.advent2023
import com.ginsberg.advent2023.Point2D.Companion.EAST
import com.ginsberg.advent2023.Point2D.Companion.NORTH
import com.ginsberg.advent2023.Point2D.Companion.SOUTH
import com.ginsberg.advent2023.Point2D.Companion.WEST
import java.util.PriorityQueue
class Day17(input: List<String>) {
private val grid = input.map { row -> row.map { it.digitToInt() } }
private val directions = mapOf(
NORTH to setOf(NORTH, EAST, WEST),
WEST to setOf(WEST, NORTH, SOUTH),
SOUTH to setOf(SOUTH, EAST, WEST),
EAST to setOf(EAST, NORTH, SOUTH)
)
fun solvePart1(): Int =
calculateHeatLoss { state, nextDirection ->
state.steps < 3 || state.direction != nextDirection
}
fun solvePart2(): Int =
calculateHeatLoss(4) { state, nextDirection ->
if (state.steps > 9) state.direction != nextDirection
else if (state.steps < 4) state.direction == nextDirection
else true
}
private fun calculateHeatLoss(minSteps: Int = 1, isValidNextMove: (State, Point2D) -> Boolean): Int {
val goal = Point2D(grid.first().lastIndex, grid.lastIndex)
val seen = mutableSetOf<State>()
val queue = PriorityQueue<Work>()
listOf(EAST, SOUTH).forEach { startDirection ->
State(Point2D(0, 0), startDirection, 0).apply {
queue += Work(this, 0)
seen += this
}
}
while (queue.isNotEmpty()) {
val (current, heatLoss) = queue.poll()
if (current.location == goal && current.steps >= minSteps) return heatLoss
directions
.getValue(current.direction)
.filter { direction -> grid.isSafe(current.location + direction) }
.filter { direction -> isValidNextMove(current, direction) }
.map { direction -> current.next(direction) }
.filterNot { state -> state in seen }
.forEach { state ->
queue += Work(state, heatLoss + grid[state.location])
seen += state
}
}
throw IllegalStateException("No route to goal")
}
private data class State(val location: Point2D, val direction: Point2D, val steps: Int) {
fun next(nextDirection: Point2D): State =
State(location + nextDirection, nextDirection, if (direction == nextDirection) steps + 1 else 1)
}
private data class Work(val state: State, val heatLoss: Int) : Comparable<Work> {
override fun compareTo(other: Work): Int =
heatLoss - other.heatLoss
}
} | 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 2,924 | advent-2023-kotlin | Apache License 2.0 |
src/main/aoc2018/Day22.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
import Pos
import Search
import Search.WeightedGraph
class Day22(input: List<String>) {
enum class Type(val risk: Int) {
ROCKY(0),
WET(1),
NARROW(2);
companion object {
fun typeForErosionLevel(level: Int) = when (level % 3) {
0 -> ROCKY
1 -> WET
2 -> NARROW
else -> throw RuntimeException("invalid terrain type")
}
}
}
enum class Equipment {
NONE,
TORCH,
CLIMBING_GEAR;
fun canTraverse(type: Type): Boolean {
return when (this) {
NONE -> type != Type.ROCKY
TORCH -> type != Type.WET
CLIMBING_GEAR -> type != Type.NARROW
}
}
companion object {
fun equipmentFor(type: Type): List<Equipment> {
return when (type) {
Type.ROCKY -> listOf(CLIMBING_GEAR, TORCH)
Type.WET -> listOf(CLIMBING_GEAR, NONE)
Type.NARROW -> listOf(TORCH, NONE)
}
}
}
}
data class State(val currentPos: Pos, val equipment: Equipment)
class Graph(private val depth: Int, private val target: Pos) : WeightedGraph<State> {
override fun neighbours(id: State): List<State> {
return buildList {
// Move to adjacent position without changing equipment
id.currentPos.allNeighbours()
.forEach {
if (it.x >= 0 && it.y >= 0 && id.equipment.canTraverse(type(it))) {
add(State(it, id.equipment))
}
}
// Change equipment without moving
Equipment.equipmentFor(type(id.currentPos))
.forEach { equipment ->
if (equipment != id.equipment) {
add(State(id.currentPos, equipment))
}
}
}
}
// cost 1 to move, cost 7 to change equipment
override fun cost(from: State, to: State): Float {
return if (from.equipment == to.equipment) 1f else 7f
}
private val erosionLevels = mutableMapOf<Pos, Int>() //position to erosion level
private fun geologicIndex(pos: Pos): Int {
return when {
pos.x == 0 && pos.y == 0 -> 0
pos.y == 0 -> pos.x * 16807
pos.x == 0 -> pos.y * 48271
pos == target -> 0
else -> {
val pos1 = Pos(pos.x - 1, pos.y)
val pos2 = Pos(pos.x, pos.y - 1)
if (erosionLevels[pos1] == null) {
erosionLevels[pos1] = erosionLevel(pos1)
}
if (erosionLevels[pos2] == null) {
erosionLevels[pos2] = erosionLevel(pos2)
}
erosionLevels[pos1]!! * erosionLevels[pos2]!!
}
}
}
private fun erosionLevel(pos: Pos) = (geologicIndex(pos) + depth) % 20183
private val typeCache = mutableMapOf<Pos, Type>()
private fun type(pos: Pos): Type {
val cached = typeCache[pos]
if (cached == null) {
val type = Type.typeForErosionLevel(erosionLevel(pos))
typeCache[pos] = type
return type
}
return cached
}
@Suppress("unused")
fun printMap(maxX: Int, maxY: Int) {
for (y in 0..maxX) {
for (x in 0..maxY) {
when (type(Pos(x, y))) {
Type.ROCKY -> print('.')
Type.WET -> print('=')
Type.NARROW -> print('|')
}
}
println()
}
}
fun totalRisk(): Int {
for (y in 0..target.y) {
for (x in 0..target.x) {
val currentPos = Pos(x, y)
erosionLevels[currentPos] = erosionLevel(currentPos)
}
}
return erosionLevels.keys
.filter { it.x <= target.x && it.y <= target.y }
.sumOf { type(it).risk }
}
}
private val target = Pos(
input[1].substringAfter(" ").substringBefore(",").toInt(),
input[1].substringAfter(",").toInt()
)
private val depth: Int = input[0].substringAfter(" ").toInt()
private val graph = Graph(depth, target)
fun solvePart1(): Int {
return graph.totalRisk()
}
fun solvePart2(): Int {
val goal = State(target, Equipment.TORCH)
return Search.aStar(graph, State(Pos(0, 0), Equipment.TORCH), goal, ::heuristic).cost[goal]!!.toInt()
}
private fun heuristic(current: State, goal: State): Float {
return current.currentPos.distanceTo(goal.currentPos) + if (current.equipment == goal.equipment) 0f else 7f
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 5,160 | aoc | MIT License |
src/Day20.kt | Kietyo | 573,293,671 | false | {"Kotlin": 147083} | import java.lang.Exception
import kotlin.math.absoluteValue
import kotlin.math.sign
data class CircularArrayElement(
var idx: Int,
val data: Long
)
@JvmInline
value class CircularArray(
val data: Array<CircularArrayElement>
) {
private fun normalizeIndex(idx: Int): Int {
val mod = idx % data.size
return if (mod < 0) mod + data.size else mod
}
operator fun get(idx: Int) = data[normalizeIndex(idx)]
fun swap(idx1: Int, idx2: Int) {
val circularIdx1 = normalizeIndex(idx1)
val circularIdx2 = normalizeIndex(idx2)
try {
val t = data[circularIdx1]
data[circularIdx1] = data[circularIdx2]
data[circularIdx1].idx = circularIdx1
data[circularIdx2] = t
t.idx = circularIdx2
} catch (e: Exception) {
println("Failed with: idx1: $idx1, idx2: $idx2")
throw e
}
}
}
fun main() {
fun part1(input: List<String>): Unit {
val originalNums = input.map { it.toLong() }
val originalNumsCircularArrayElements = originalNums.mapIndexed { index, i ->
CircularArrayElement(index, i)
}
val circularArray = CircularArray(originalNumsCircularArrayElements.toTypedArray())
println("size: ${originalNums.size}")
println(circularArray)
for (circularArrayElement in originalNumsCircularArrayElements) {
val sign = circularArrayElement.data.sign
var idx = circularArrayElement.idx
// println("$it: processing: $currNum, sign: $sign")
repeat((circularArrayElement.data.absoluteValue % (originalNums.size * originalNums.size)).toInt()) {
circularArray.swap(idx, idx + sign)
idx += sign
}
}
println(circularArray)
val zeroIdx = originalNumsCircularArrayElements.first {
it.data == 0L
}.idx
val nums = listOf(
circularArray[zeroIdx + 1000],
circularArray[zeroIdx + 2000],
circularArray[zeroIdx + 3000],
).map { it.data }
println(nums)
println(nums.sum())
}
fun part2(input: List<String>): Unit {
val originalNums = input.map { it.toLong() * 811589153L }
val originalNumsCircularArrayElements = originalNums.mapIndexed { index, i ->
CircularArrayElement(index, i)
}
val circularArray = CircularArray(originalNumsCircularArrayElements.toTypedArray())
println("size: ${originalNums.size}")
println(circularArray)
repeat(10) {
println("Finished $it")
for (circularArrayElement in originalNumsCircularArrayElements) {
val sign = circularArrayElement.data.sign
var idx = circularArrayElement.idx
// println("$it: processing: $currNum, sign: $sign")
repeat((circularArrayElement.data.absoluteValue %
(originalNums.size.dec() * originalNums.size)).toInt()) {
circularArray.swap(idx, idx + sign)
idx += sign
}
}
}
println(circularArray)
val zeroIdx = originalNumsCircularArrayElements.first {
it.data == 0L
}.idx
val nums = listOf(
circularArray[zeroIdx + 1000],
circularArray[zeroIdx + 2000],
circularArray[zeroIdx + 3000],
).map { it.data }
println(nums)
println(nums.sum())
}
val dayString = "day20"
// test if implementation meets criteria from the description, like:
val testInput = readInput("${dayString}_test")
// part1(testInput)
// part2(testInput)
val input = readInput("${dayString}_input")
// -597 is wrong
// 7228 is right
// part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | dd5deef8fa48011aeb3834efec9a0a1826328f2e | 3,960 | advent-of-code-2022-kietyo | Apache License 2.0 |
code/day_07/src/jvm8Main/kotlin/task2.kt | dhakehurst | 725,945,024 | false | {"Kotlin": 105846} | package day_07
val map2 = mapOf(
"A" to 14,
"K" to 13,
"Q" to 12,
"J" to 1,
"T" to 10
)
data class Hand2(
val cards: String,
val bid: Int
) : Comparable<Hand2> {
val cardValues = cards.map { map2[it.toString()] ?: it.toString().toInt() }
val grouped = cardValues.filterNot { map2["J"]==it }.groupBy { it }
val numJokers = cardValues.count { it == map2["J"] }
val maxGroup = grouped.maxOfOrNull { it.value.size } ?: 0
val num2Groups = grouped.count { it.value.size == 2 }
val isFiveOfAKind = maxGroup==5 || numJokers==5 || (maxGroup+numJokers)==5
val isFourOfAKind = (maxGroup+numJokers)==4
val isFullHouse = (maxGroup==3 && num2Groups==1) || (num2Groups==2 && numJokers==1) || (maxGroup==3 && numJokers==2)
val isThreeOdAKind = (maxGroup+numJokers)==3
val isTwoPair = num2Groups==2 || (num2Groups==1 && numJokers==1)
val isOnePair = num2Groups==1 || numJokers==1
val handValue = when {
isFiveOfAKind -> 6
isFourOfAKind -> 5
isFullHouse -> 4
isThreeOdAKind -> 3
isTwoPair -> 2
isOnePair -> 1
else -> 0
}
override fun compareTo(other: Hand2): Int = when {
this.handValue > other.handValue -> 1
this.handValue < other.handValue -> -1
this.handValue == other.handValue -> {
var r = 0
for(i in 0 .. 4) {
r = when {
cardValues[i] > other.cardValues[i] -> +1
cardValues[i] < other.cardValues[i] -> -1
else -> 0
}
if (0!=r) break
}
r
}
else -> 0
}
}
fun task2(lines: List<String>): Long {
var total = 0L
val hands = lines.map {
val cards = it.substringBefore(" ")
val bid = it.substringAfter(" ").toInt()
Hand2(cards, bid)
}
val sorted = hands.sortedBy { it }
sorted.forEachIndexed { idx, it ->
println("${it.handValue} ${it.cards} ${it.bid} ${idx+1} ${it.bid * (idx+1)}")
total += it.bid * (idx+1)
}
println("Day 07 task 1: $total")
return total
} | 0 | Kotlin | 0 | 0 | be416bd89ac375d49649e7fce68c074f8c4e912e | 2,168 | advent-of-code | Apache License 2.0 |
aoc2023/day8.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2023
import utils.InputRetrieval
import utils.Math
fun main() {
Day8.execute()
}
private object Day8 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: DesertMap): Long = input.walkMap(STARTING_NODE) { it == FINAL_NODE }
private fun part2(input: DesertMap): Long {
// At first, I thought we would need to calculate the loop size, and not just the first occurrence. But after testing they are the same, so...
val firstZPosition = input.nodes.keys
.filter { it.endsWith(STARTING_NODE_PLACE) }
.map { input.walkMap(it) { node -> node.endsWith(FINAL_NODE_PLACE) } }
return firstZPosition.reduce { a, b -> Math.findLCM(a, b) }
}
private fun readInput(): DesertMap {
val input = InputRetrieval.getFile(2023, 8).readLines()
return DesertMap.parse(input)
}
private const val STARTING_NODE = "AAA"
private const val FINAL_NODE = "ZZZ"
private const val STARTING_NODE_PLACE = 'A'
private const val FINAL_NODE_PLACE = 'Z'
private data class DesertMap(val instructions: String, val nodes: Map<String, Pair<String, String>>) {
fun walkMap(initialNode: String, reachedEnd: (String) -> Boolean): Long {
var i = 0L
var node = initialNode
while (!reachedEnd.invoke(node)) {
node = when (this.instructions[(i % this.instructions.length).toInt()]) {
'L' -> this.nodes[node]!!.first
else -> this.nodes[node]!!.second
}
i++
}
return i
}
companion object {
fun parse(input: List<String>): DesertMap {
val instructions = input.first()
val nodes = input.drop(2).associate {
val (key, paths) = it.split('=')
val (left, right) = paths.replace('(', ' ').replace(')', ' ').trim().split(',')
key.trim() to (left to right.trim())
}
return DesertMap(instructions, nodes)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 2,229 | Advent-Of-Code | MIT License |
src/main/kotlin/day01/day01.kt | corneil | 572,437,852 | false | {"Kotlin": 93311, "Shell": 595} | package main.day01
import utils.readFile
import utils.readLines
fun main() {
fun findCalories(input: List<String>): List<Int> {
val elves = mutableListOf<Int>()
var calories = 0
for (line in input) {
if (line.isBlank()) {
elves.add(calories)
calories = 0
} else {
calories += line.toInt()
}
}
elves.add(calories)
return elves
}
fun findMaxCalories(input: List<String>): Int {
val calories = findCalories(input)
return calories.max()
}
fun topThree(input: List<String>): Int {
val calories = findCalories(input)
return calories.sortedDescending().take(3).sum()
}
val testText = """1000
2000
3000
4000
5000
6000
7000
8000
9000
10000"""
fun part1() {
val testInput = readLines(testText)
val testMax = findMaxCalories(testInput)
println("Part 1 - Test Max Calories = $testMax")
check(testMax == 24000)
val input = readFile("day01")
val maxCalories = findMaxCalories(input)
println("Part 1 - Max Calories = $maxCalories")
check(maxCalories == 71300)
}
fun part2() {
val testInput = readLines(testText)
val testTop3 = topThree(testInput)
println("Part 2 - Test Top3 = $testTop3")
check(testTop3 == 45000)
val input = readFile("day01")
val top3 = topThree(input)
println("Part 2 - Top3 = $top3")
check(top3 == 209691)
}
println("Day - 01")
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | dd79aed1ecc65654cdaa9bc419d44043aee244b2 | 1,434 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day03.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} |
fun main() {
fun Char.toScore() = when (this) {
in 'a'..'z' -> 1 + (this - 'a')
else -> 27 + (this - 'A')
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { (a, b, c) ->
a.toSet().intersect(b.toSet()).intersect(c.toSet()).first().toScore()
}
}
fun part1(input: List<String>): Int {
return input.sumOf {
val firstHalf = it.substring(0, it.length / 2)
val secondHalf = it.substring(it.length / 2)
firstHalf.toSet().intersect(secondHalf.toSet()).first().toScore()
}
}
println(part1(readInput("data/Day03_test")))
println(part1(readInput("data/Day03")))
println(part2(readInput("data/Day03_test")))
println(part2(readInput("data/Day03")))
}
| 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 801 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/arrays/MergeSortedArray.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.arrays
/**
* You are given two integer arrays nums1 and nums2,
* sorted in non-decreasing order, and two integers m and n,
* representing the number of elements in nums1 and nums2 respectively.
*
* Merge nums1 and nums2 into a single array sorted in non-decreasing order.
*
* The final sorted array should not be returned by the function,
* but instead be stored inside the array nums1.
* To accommodate this, nums1 has a length of m + n,
* where the first m elements denote the elements that should be merged,
* and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
*
* Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
* Output: [1,2,2,3,5,6]
* Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
* The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
*
* Input: nums1 = [1], m = 1, nums2 = [], n = 0
* Output: [1]
* Explanation: The arrays we are merging are [1] and [].
* The result of the merge is [1].
*
* Input: nums1 = [0], m = 0, nums2 = [1], n = 1
* Output: [1]
* Explanation: The arrays we are merging are [] and [1].
* The result of the merge is [1].
* Note that because m = 0, there are no elements in nums1.
* The 0 is only there to ensure the merge result can fit in nums1.
*/
// O(m + n) time | O(1) space
fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int) {
var high1 = m - 1
var high2 = n - 1
for (i in nums1.size - 1 downTo 0) {
when {
high2 < 0 -> return
high1 >= 0 && nums1[high1] > nums2[high2] -> nums1[i] = nums1[high1--]
else -> nums1[i] = nums2[high2--]
}
}
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 1,733 | algs4-leprosorium | MIT License |
src/main/kotlin/days/Day20.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
fun Int.isOutOfBounds(upperLimit: Int): Boolean {
return (this < 0 || this > upperLimit)
}
fun Long.isOutOfBounds(upperLimit: Int): Boolean {
return (this < 0 || this > upperLimit)
}
fun part1(input: List<String>): Int {
val encryptedFile = input.mapIndexed { i, num -> i to num.toInt() }
val mixedFile = encryptedFile.toMutableList()
val size = encryptedFile.size - 1
encryptedFile.forEach { pair ->
val originalIndex = mixedFile.indexOfFirst { it == pair }
mixedFile.remove(pair)
var newIndex = originalIndex + pair.second
while (newIndex.isOutOfBounds(size)) {
if (newIndex > 0) newIndex -= size
else newIndex += size
}
mixedFile.add(newIndex, pair)
}
val zeroIndex = mixedFile.indexOf(encryptedFile.first { it.second == 0 })
val groveCoordinates = listOf(1000, 2000, 3000).map {
var i = it + zeroIndex
while (i.isOutOfBounds(size)) {
i -= size + 1
}
mixedFile[i].second
}
println(groveCoordinates)
return groveCoordinates.sum()
}
fun part2(input: List<String>): Long {
val decryptionKey = 811589153L
val encryptedFile = input.mapIndexed { i, num -> i to num.toLong() * decryptionKey }
val mixedFile = encryptedFile.toMutableList()
val size = encryptedFile.size - 1
repeat(10) {
// % remainder??
encryptedFile.forEach { pair ->
val originalIndex = mixedFile.indexOfFirst { it == pair }
mixedFile.remove(pair)
var newIndex = originalIndex + pair.second
while (newIndex.isOutOfBounds(size)) {
if (newIndex > 0) newIndex -= size
else newIndex += size
}
mixedFile.add(newIndex.toInt(), pair)
}
}
val zeroIndex = mixedFile.indexOf(encryptedFile.first { it.second == 0L })
val groveCoordinates = listOf(1000, 2000, 3000).map {
var i = it + zeroIndex
while (i.isOutOfBounds(size)) {
i -= size + 1
}
mixedFile[i].second
}
println(groveCoordinates)
return groveCoordinates.sum()
}
val testInput = readInput("Day20_test")
check(part1(testInput) == 3)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 2,657 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/ca/kiaira/advent2023/day6/Day6.kt | kiairatech | 728,913,965 | false | {"Kotlin": 78110} | package ca.kiaira.advent2023.day6
import ca.kiaira.advent2023.Puzzle
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
/**
* Class responsible for solving the Day 6 puzzle of Advent of Code.
*
* This class extends the Puzzle class, providing implementations for parsing the input
* and solving the two parts of the puzzle.
*
* @author <NAME> <<EMAIL>>
* @since December 11th, 2023
*/
object Day6 : Puzzle<List<Race>>(6) {
/**
* Parses a sequence of strings into a list of Race objects.
* Assumes the first line contains race times and the second line contains records, separated by spaces.
*
* @param input The input sequence of strings.
* @return A list of Race objects.
*/
override fun parse(input: Sequence<String>): List<Race> {
val lines = input.toList()
val raceTimes = lines[0].split("\\s+".toRegex()).drop(1).map { it.toLong() }
val records = lines[1].split("\\s+".toRegex()).drop(1).map { it.toLong() }
return raceTimes.zip(records).map { Race(it.first, it.second) }
}
/**
* Solves the first part of the puzzle.
* Calculates the product of the number of ways to beat each race record.
*
* @param input List of Race objects.
* @return The product of ways to beat each race's record.
*/
override fun solvePart1(input: List<Race>): Long {
return input.fold(1L) { acc, race ->
acc * calculateWaysToBeatRecord(race)
}
}
/**
* Solves the second part of the puzzle.
* Combines all races into one and calculates the ways to beat the combined race record.
*
* @param input List of Race objects.
* @return The number of ways to beat the combined race record.
*/
override fun solvePart2(input: List<Race>): Long {
val combinedRace = combineRaces(input)
return calculateWaysToBeatRecord(combinedRace)
}
/**
* Calculates the number of ways to beat a race record.
* Utilizes the quadratic equation to determine the range of possible solutions.
*
* @param race The Race object.
* @return The number of ways to beat the race record.
*/
private fun calculateWaysToBeatRecord(race: Race): Long {
val (time, record) = race
val discriminantSqrt = sqrt(time.toDouble() * time - 4.0 * record)
var possibleRoot1 = floor((time + discriminantSqrt) / 2).toLong()
var possibleRoot2 = ceil((time - discriminantSqrt) / 2).toLong()
if (possibleRoot1 * (time - possibleRoot1) <= record) possibleRoot1--
if (possibleRoot2 * (time - possibleRoot2) <= record) possibleRoot2++
return possibleRoot1 - possibleRoot2 + 1
}
/**
* Combines multiple races into a single race.
* Concatenates the times and records of individual races.
*
* @param races The list of Race objects.
* @return A combined Race object.
*/
private fun combineRaces(races: List<Race>): Race {
val combinedRaceTime = races.map { it.time }.joinToString("").toLong()
val combinedRecord = races.map { it.record }.joinToString("").toLong()
return Race(combinedRaceTime, combinedRecord)
}
} | 0 | Kotlin | 0 | 1 | 27ec8fe5ddef65934ae5577bbc86353d3a52bf89 | 2,998 | kAdvent-2023 | Apache License 2.0 |
leetcode2/src/leetcode/powx-n.kt | hewking | 68,515,222 | false | null | package leetcode
/**
*50. Pow(x, n)
* https://leetcode-cn.com/problems/powx-n/
* @program: leetcode
* @description: ${description}
* @author: hewking
* @create: 2019-10-15 15:34
* 实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/powx-n
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
object PowxN {
@JvmStatic
fun main(args: Array<String>) {
println(Solution().myPow3(2.0,-2))
}
class Solution {
fun myPow(x: Double, n: Int): Double {
var calcResult = 1.0
if (x == 0.0) return 0.0
if (x == 1.0) return 1.0
if (n < 0) {
val x1 = x
}
for (i in 0 until Math.abs(n)) {
calcResult *= x
}
return if (n < 0) {
1 / calcResult
} else {
calcResult
}
}
/**
* 思路:
* 1. x^2n = (x^n)^2
* 2. 通过递归,不断的判断是否是偶数,如果是则递归
* 3. 对于奇数则 -1 然后在进行处理
* 4. 基准情形:幂 为 1
*/
fun myPow2(x: Double, n: Int): Double {
var num = x
var n1 = n
if (n < 0) {
num = 1/ x
n1 = Math.abs(n)
}
if (n == 0) {
return 1.0
}
if (n == 1) {
return x
}
var result = 0.0
result = if (n1 % 2 == 0) {
myPow2(num,n1 / 2) * myPow2(num,n1 / 2)
} else {
myPow2(num,(n1 - 1) / 2) * myPow2(num,(n1 - 1) / 2) * num
}
return result
}
fun myPow3(x: Double, n: Int): Double {
var num = x
var n1 = n.toLong()
if (n < 0) {
num = 1/ x
n1 = -n.toLong()
}
if (n == 0) {
return 1.0
}
if (n == 1) {
return x
}
var ans = 1.0
var x2 = num
while(n1 > 0){
if (n1 % 2 == 1L) {
ans *= x2
}
x2 *= x2
n1 /= 2
}
return ans
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,750 | leetcode | MIT License |
advent-of-code-2021/src/code/day14/Main.kt | Conor-Moran | 288,265,415 | false | {"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733} | package code.day14
import java.io.File
import kotlin.math.max
import kotlin.math.min
val doDump = false
fun main() {
doIt("Day 14 Part 1: Test Input", "src/code/day14/test.input", part1)
doIt("Day 14 Part 1: Real Input", "src/code/day14/part1.input", part1)
doIt("Day 14 Part 2: Test Input", "src/code/day14/test.input", part2);
doIt("Day 14 Part 2: Real Input", "src/code/day14/part1.input", part2);
}
fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Long) {
val lines = arrayListOf<String>()
File(input).forEachLine { lines.add(it) }
println(String.format("%s: Ans: %d", msg , calc(lines)))
}
val part1: (List<String>) -> Long = { lines ->
val input = parse(lines)
var src = input.initStr
var result = emptyList<Char>()
for(i in 1 .. 1) {
result = mutableListOf<Char>()
result.add(src[0])
for(i in 1 until src.length) {
result.add(input.replacements[src.slice(i-1 .. i)]!!)
result.add(src[i])
}
src = result.joinToString("")
}
val counts = mutableMapOf<Char, Long>()
var minC: Long = Long.MAX_VALUE
var maxC: Long = Long.MIN_VALUE
result.forEach {
counts[it] = counts.getOrDefault(it, 0) + 1
}
counts.values.forEach {
minC = min(it, minC)
maxC = max(it, maxC)
}
maxC - minC
}
typealias Data = MutableMap<Char, MutableMap<Char, Long>>
val part2: (List<String>) -> Long = { lines ->
val input = parse(lines)
var data = newData()
val src = input.initStr
for(i in 1 until src.length) {
val charPair = src.slice(i-1 .. i)!!
incMapBy(data, 1, charPair[0], charPair[1])
}
// dump(data)
val summary1 = summarise(input.initStr, data)
for (i in 1..40) {
data = step(data, input)
}
// dump(data)
val summary = summarise(input.initStr, data)
var maxV = Long.MIN_VALUE
var minV = Long.MAX_VALUE
for (i in summary) {
maxV = max(maxV, i.value)
if (i.value != 0L) {
minV = min(minV, i.value)
}
}
maxV - minV
}
private fun newData(): Data {
val data = mutableMapOf<Char, MutableMap<Char, Long>>()
for (i in 'A' until 'Z') {
val map = mutableMapOf<Char, Long>()
for (j in 'A' until 'Z') {
map[j] = 0
}
data[i] = map
}
return data
}
private fun step(data: Data, input: Input): Data {
val increments = mutableMapOf<String, Long>()
for (x in data) {
for (y in x.value) {
if (y.value > 0) {
val charPair = String(charArrayOf(x.key, y.key))
val newChar = input.replacements[charPair]!!
val key1 = str(charPair[0], newChar)
val key2 = str(newChar, charPair[1])
increments[key1] = increments.getOrDefault(key1, 0L) + y.value
increments[key2] = increments.getOrDefault(key2, 0L) + y.value
}
}
}
val newData = newData()
for (inc in increments) {
incMapBy(newData, inc.value, inc.key[0], inc.key[1])
}
return newData
}
fun str(vararg chars: Char): String {
return String(chars)
}
fun dump(data: Data) {
for(i in data) {
for (j in data[i.key]!!) {
print(j.value)
print(',')
}
println()
}
println()
}
fun summarise(initStr: String, data: Data): MutableMap<Char, Long> {
val summary = mutableMapOf<Char, Long>()
for (i in 'A' until 'Z') {
summary[i] = 0
}
for (i in 'A' until 'Z') {
summary[i] = sumFor(i, initStr, data)
}
return summary
}
fun sumFor(c: Char, initStr: String, data: Data): Long {
var startsWithCount = 0L
for (j in data[c]!!) {
startsWithCount += j.value
}
val correction = if (initStr.last() == c) 1 else 0
return startsWithCount + correction
}
fun incMapBy(data: Data, byAmount: Long, i: Char, j: Char) {
data[i]!!.merge(j, byAmount, Long::plus)
}
fun parse(lines: List<String>): Input {
val replacements = mutableMapOf<String,Char>()
for(i in 2 .. lines.lastIndex) {
val r1 = lines[i].slice(0 .. 0)
val r2 = lines[i].slice(1 .. 1)
val yy = lines[i][6]
replacements[r1.plus(r2)] = yy
}
return Input(lines[0], replacements)
}
class Input(val initStr: String, val replacements: Map<String, Char>)
| 0 | Kotlin | 0 | 0 | ec8bcc6257a171afb2ff3a732704b3e7768483be | 4,449 | misc-dev | MIT License |
src/aoc2022/Day02.kt | miknatr | 576,275,740 | false | {"Kotlin": 413403} | package aoc2022
fun main() {
class Round(
// A for Rock, B for Paper, and C for Scissors
val attack: String,
// X for Rock, Y for Paper, and Z for Scissors
val defense: String
) {
val scoreForResponse get() = when (defense) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> throw RuntimeException("Unknown defense: $defense")
}
val scoreForResult get() = when ("$attack $defense") {
"A X" -> 3
"A Y" -> 6
"A Z" -> 0
"B X" -> 0
"B Y" -> 3
"B Z" -> 6
"C X" -> 6
"C Y" -> 0
"C Z" -> 3
else -> throw RuntimeException("Unknown attack and defense: $attack $defense")
}
val score get() = scoreForResponse + scoreForResult
}
class Round2(
// A for Rock, B for Paper, and C for Scissors
val attack: String,
// X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win
val needResult: String
) {
val scoreForResult get() = when (needResult) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> throw RuntimeException("Unknown needResult: $needResult")
}
val scoreForResponse get() = when ("$attack $needResult") {
"A X" -> 3
"A Y" -> 1
"A Z" -> 2
"B X" -> 1
"B Y" -> 2
"B Z" -> 3
"C X" -> 2
"C Y" -> 3
"C Z" -> 1
else -> throw RuntimeException("Unknown attack and defense: $attack $needResult")
}
val score get() = scoreForResponse + scoreForResult
}
fun part1(input: List<String>) = input
.filter { it != "" }
.sumOf { Round(it[0].toString(), it[2].toString()).score }
fun part2(input: List<String>) = input
.filter { it != "" }
.sumOf { Round2(it[0].toString(), it[2].toString()).score }
val testInput = readInput("Day02_test")
part1(testInput).println()
part2(testInput).println()
val input = readInput("Day02")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 400038ce53ff46dc1ff72c92765ed4afdf860e52 | 2,239 | aoc-in-kotlin | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions39.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import com.qiaoyuang.algorithm.round0.partition
fun test39() {
printlnResult(intArrayOf(1, 2, 3, 2, 2, 2, 5, 4, 2))
printlnResult(intArrayOf(0, 9, 9, 8, 2, 9, 5, 9, 9))
}
/**
* Questions 39: Find the number that more than a half in an IntArray
*/
private fun IntArray.findTheNumber1(): Int {
require(isNotEmpty()) { "The IntArray can't be empty" }
var num = first()
if (size == 1)
return num
var count = 1
for (i in 1..< size) {
val current = this[i]
when {
current == num -> count++
--count == 0 -> {
num = current
count = 1
}
}
}
require(count > 0) { "The IntArray must contain a number that more than a half" }
return num
}
private fun IntArray.findTheNumber2(): Int {
require(isNotEmpty()) { "The IntArray can't be empty" }
val mid = size shr 1
var start = 0
var end = lastIndex
var index = partition(start, end)
while (index != mid) {
if (index > mid)
end = index - 1
else
start = index + 1
index = partition(start, end)
}
return this[mid].takeIf { checkMoreThanHalf(it) } ?: throw IllegalArgumentException("The IntArray must contain a number that more than a half")
}
private infix fun IntArray.checkMoreThanHalf(target: Int): Boolean {
var count = 0
val half = size shr 1
forEach {
if (it == target && ++count > half)
return true
}
return false
}
private fun printlnResult(intArray: IntArray) {
println("The number in IntArray: ${intArray.toList()} that more than a half is ${intArray.findTheNumber1()}")
println("The number in IntArray: ${intArray.toList()} that more than a half is ${intArray.findTheNumber2()}")
}
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,839 | Algorithm | Apache License 2.0 |
src/Day01.kt | rweekers | 573,305,041 | false | {"Kotlin": 38747} | fun main() {
fun part1(input: List<String>): Int {
return input.splitBy { it.isEmpty() }
.map { it.map { s -> s.toInt() } }
.maxOfOrNull { it.fold(0) { acc, curr -> acc + curr } } ?: throw IllegalArgumentException()
}
fun part2(input: List<String>): Int {
return input.splitBy { it.isEmpty() }
.asSequence()
.map { it.map { s -> s.toInt() } }
.map { it.sum() }
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 276eae0afbc4fd9da596466e06866ae8a66c1807 | 810 | adventofcode-2022 | Apache License 2.0 |
src/Day21.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | fun main() {
class Monkey(val name: String, var value: Long?, val operation: String) {
fun yell(monkeys: Map<String, Monkey>): Long = if (value != null)
value!!
else {
val (name1, operator, name2) = operation.split(" ")
val monkey1 = monkeys[name1]!!.yell(monkeys)
val monkey2 = monkeys[name2]!!.yell(monkeys)
when (operator) {
"+" -> monkey1 + monkey2
"-" -> monkey1 - monkey2
"*" -> monkey1 * monkey2
"/" -> monkey1 / monkey2
else -> throw Exception("Unknown operator $operator")
}
}
fun dependsOn(name: String, monkeys: Map<String, Monkey>): Boolean {
if (this.name == name)
return true
else if (this.value != null)
return false
else {
val (name1, _, name2) = operation.split(" ")
if (name1 == name || name2 == name)
return true
val monkey1 = monkeys[name1]!!.dependsOn(name, monkeys)
val monkey2 = monkeys[name2]!!.dependsOn(name, monkeys)
return monkey1 || monkey2
}
}
fun fix(targetValue: Long, nodeToFix: String, monkeys: Map<String, Monkey>) {
if (this.name == nodeToFix) {
this.value = targetValue
return
} else if (this.value != null)
throw Exception("Should not be fixing here!")
else {
val (name1, operator, name2) = operation.split(" ")
val monkey1 = monkeys[name1]!!
val monkey2 = monkeys[name2]!!
val monkey1dependOnNodeToFix = monkey1.dependsOn(nodeToFix, monkeys)
val otherValue = if (monkey1dependOnNodeToFix) monkey2.yell(monkeys) else monkey1.yell(monkeys)
if (monkey1dependOnNodeToFix) {
when (operator) {
"+" -> monkey1.fix(targetValue - otherValue, nodeToFix, monkeys)
"-" -> monkey1.fix(targetValue + otherValue, nodeToFix, monkeys)
"*" -> monkey1.fix(targetValue / otherValue, nodeToFix, monkeys)
"/" -> monkey1.fix(targetValue * otherValue, nodeToFix, monkeys)
else -> throw Exception("Unknown operator $operator")
}
} else {
when (operator) {
"+" -> monkey2.fix(targetValue - otherValue, nodeToFix, monkeys)
"-" -> monkey2.fix(otherValue - targetValue, nodeToFix, monkeys)
"*" -> monkey2.fix(targetValue / otherValue, nodeToFix, monkeys)
"/" -> monkey2.fix(otherValue / targetValue, nodeToFix, monkeys)
else -> throw Exception("Unknown operation $operator")
}
}
}
}
}
fun parseMonkeys(input: List<String>) = input.map { it.split(": ") }.associate { (name, yell) ->
name to Monkey(name, value = yell.toLongOrNull(), operation = yell)
}
fun part1(input: List<String>) = parseMonkeys(input).let { it["root"]!!.yell(it) }
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input)
val humn = monkeys["humn"]!!
val root = monkeys["root"]!!
val (root1name, _, root2name) = root.operation.split(" ")
val root1 = monkeys[root1name]!!
val root2 = monkeys[root2name]!!
val root1dependOnHumn = root1.dependsOn("humn", monkeys)
val targetValue = if (root1dependOnHumn) root2.yell(monkeys) else root1.yell(monkeys)
val branchToFix = if (root1dependOnHumn) root1 else root2
branchToFix.fix(targetValue, "humn", monkeys)
return humn.value!!
}
test(
day = 21,
testTarget1 = 152L,
testTarget2 = 301L,
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 4,084 | aoc2022 | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec09.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.Coord
import org.elwaxoro.advent.PuzzleDayTester
import org.elwaxoro.advent.neighborCoords
import org.elwaxoro.advent.neighbors
import org.elwaxoro.advent.splitToInt
/**
* Smoke Basin
*/
class Dec09 : PuzzleDayTester(9, 2021) {
override fun part1(): Any = parse().let { grid ->
grid.mapIndexed { rowIdx, row ->
row.mapIndexedNotNull { colIdx, height ->
(height + 1).takeIf { grid.neighbors(rowIdx, colIdx).none { it <= height } }
}
}.flatten().sum()
}
override fun part2(): Any = parse().let { grid ->
var basinCtr = 0 // idk number basins I guess
val basinMap = mutableMapOf<Coord, Int>() // each point in the grid, mapped to the basin it belongs to
grid.forEachIndexed { rowIdx, row ->
row.forEachIndexed { colIdx, height ->
Coord(colIdx, rowIdx).takeIf {
height != 9 && !basinMap.contains(it)
}?.let {
// New basin! Explore!
basinCtr += 1
basinMap[it] = basinCtr
explore(grid, basinMap, basinCtr, it)
}
}
}
basinMap.entries.groupingBy { it.value }.eachCount().map { it.value }.sorted().takeLast(3)
.reduce { acc, basinSize -> acc * basinSize }
}
private fun explore(
grid: List<List<Int>>,
basinMap: MutableMap<Coord, Int>,
currentBasin: Int,
coord: Coord
) {
grid.neighborCoords(coord.y, coord.x)
.filterNot { (coord, height) -> height == 9 || basinMap.contains(coord) } // ignore neighbors already mapped or too tall
.map { (coord, _) -> coord.also { basinMap[it] = currentBasin } } // strip out the neighbor height and add neighbor to basin map
.map { explore(grid, basinMap, currentBasin, it) } // explore!
}
private fun parse(): List<List<Int>> = load().map { it.splitToInt() }
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,046 | advent-of-code | MIT License |
src/Day23.kt | Riari | 574,587,661 | false | {"Kotlin": 83546, "Python": 1054} | fun main() {
data class Vector2(var x: Int, var y: Int) {
operator fun plus(other: Vector2): Vector2 = Vector2(x + other.x, y + other.y)
operator fun minus(other: Vector2): Vector2 = Vector2(x - other.x, y - other.y)
}
var paddingSize = 0
val directions = listOf(
listOf(Vector2(0, -1), Vector2(1, -1), Vector2(-1, -1)),
listOf(Vector2(0, 1), Vector2(1, 1), Vector2(-1, 1)),
listOf(Vector2(-1, 0), Vector2(-1, -1), Vector2(-1, 1)),
listOf(Vector2(1, 0), Vector2(1, -1), Vector2(1, 1)),
)
fun processInput(input: List<String>): List<BooleanArray> {
paddingSize = input.size * 2
val output = mutableListOf<BooleanArray>()
val paddingRow = BooleanArray(paddingSize * 2 + input.size)
val paddingSide = BooleanArray(paddingSize)
repeat (paddingSize) { output.add(paddingRow.clone()) }
input.forEach {
val middle = it.map { c -> c == '#' }.toBooleanArray()
output.add(paddingSide.clone() + middle + paddingSide.clone())
}
repeat (paddingSize) { output.add(paddingRow.clone()) }
return output
}
fun getSmallestArea(map: List<BooleanArray>): List<List<Boolean>> {
val start = Vector2(Int.MAX_VALUE, map.indexOfFirst { it.contains(true) })
val end = Vector2(0, map.indexOfLast { it.contains(true) })
for (row in map) {
val firstElf = row.indexOfFirst { it }
val lastElf = row.indexOfLast { it }
if (firstElf > -1) start.x = minOf(start.x, firstElf)
if (lastElf > -1) end.x = maxOf(end.x, lastElf)
}
return map.subList(start.y, end.y + 1).map { it.slice(start.x .. end.x) }
}
fun print(area: List<List<Boolean>>) {
for (row in area) {
for (isElf in row) {
print(if (isElf) '#' else '.')
}
print('\n')
}
print("\n\n")
}
fun solve(input: List<BooleanArray>, maxRounds: Int): Pair<List<List<Boolean>>, Int> {
val map = input.map { it.clone() }
var startDirection = 0
val moves = mutableMapOf<Vector2, MutableList<Vector2>>()
var round = 0
while (round < maxRounds) {
// Calculate moves
var elvesMoved = 0
for ((y, row) in map.withIndex()) {
for ((x, isElf) in row.withIndex()) {
if (!isElf) continue
val position = Vector2(x, y)
val movesForElf = mutableListOf<Vector2>()
for (i in startDirection until startDirection + directions.size) {
val index = i % 4
val direction = directions[index]
val destinations = direction.map { position + it }
if (destinations.none { map[it.y][it.x] }) {
movesForElf.add(destinations[0])
}
}
if (movesForElf.size in 1 until 4) {
if (!moves.containsKey(movesForElf[0])) moves[movesForElf[0]] = mutableListOf()
moves[movesForElf[0]]!!.add(position)
elvesMoved++
}
}
}
if (elvesMoved == 0) break
// Execute moves for elves who won't clash with any others
for (move in moves) {
if (move.value.size > 1) continue
val destination = move.key
val position = move.value[0]
map[position.y][position.x] = false
map[destination.y][destination.x] = true
}
moves.clear()
// Start with the next direction for the next round
startDirection = (startDirection + 1) % 4
round++
}
return Pair(getSmallestArea(map), round + 1)
}
fun part1(input: List<BooleanArray>): Int {
val result = solve(input, 10)
return result.first.sumOf { it.count { isElf -> !isElf } }
}
fun part2(input: List<BooleanArray>): Int {
val result = solve(input, 1000)
return result.second
}
val testInput = processInput(readInput("Day23_test"))
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = processInput(readInput("Day23"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d | 4,492 | aoc-2022 | Apache License 2.0 |
src/Day09.kt | mcrispim | 573,449,109 | false | {"Kotlin": 46488} | import kotlin.Exception
fun main() {
data class Pos(var x: Int, var y: Int) {
fun move(dir: String) {
when (dir) {
"L" -> x--
"R" -> x++
"U" -> y++
"D" -> y--
"LU" -> { x--; y++ }
"RU" -> { x++; y++ }
"LD" -> { x--; y-- }
"RD" -> { x++; y-- }
else -> throw Exception("Invalid movement: [$dir]")
}
}
fun around(): MutableMap<Pos, String> {
val result = mutableMapOf<Pos, String>()
val directions = listOf(
"LU", "LU", "U" , "RU", "RU" ,
"LU", "ST", "ST", "ST", "RU",
"L" , "ST", "ST", "ST", "R" ,
"LD", "ST", "ST", "ST", "RD",
"LD" , "LD", "D" , "RD", "RD" ,
)
var i = 0
for (row in 2 downTo -2) {
for (col in - 2..2) {
result[Pos(col + x, row + y)] = directions[i]
i++
}
}
return result
}
}
fun moveTailIfNecessary(tail: Pos, head: Pos) {
val aroundMap = tail.around()
when (val dir = aroundMap[head]!!) {
"ST" -> return
"." -> throw Exception("BIG ERROR")
else -> tail.move(dir)
}
return
}
fun parseInput(input: List<String>): String =
input.joinToString("") { row ->
val dir = row.substringBefore(" ")
val units = row.substringAfter(' ').toInt()
dir.repeat(units)
}
fun part1(input: List<String>): Int {
val head = Pos(0, 0)
val tail = Pos(0, 0)
val tailSet = mutableSetOf(Pos(0, 0))
val headDirections = parseInput(input)
headDirections.forEach { dir ->
head.move(dir.toString())
moveTailIfNecessary(tail, head)
tailSet.add(Pos(tail.x, tail.y))
}
return tailSet.size
}
fun moveRope(rope: List<Pos>, dir: Char) {
rope[0].move(dir.toString())
for (tail in 1..rope.lastIndex) {
moveTailIfNecessary(rope[tail], rope[tail - 1])
}
}
fun part2(input: List<String>): Int {
val rope = List(10) { Pos(0, 0)}
val tailSet = mutableSetOf(Pos(0, 0))
val headDirections = parseInput(input)
headDirections.forEach { dir ->
moveRope(rope, dir)
tailSet.add(Pos(rope.last().x, rope.last().y))
}
return tailSet.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5fcacc6316e1576a172a46ba5fc9f70bcb41f532 | 2,886 | AoC2022 | Apache License 2.0 |
src/Day11.kt | Vlisie | 572,110,977 | false | {"Kotlin": 31465} | import java.io.File
import java.lang.IllegalArgumentException
//inputbestand doorlopen en volgende waarden verzamelen voor monkeys: check
//innitial values, accumulator calculatie en test waarde.
//Dit in fold/reduce methode vullen met initial list waar accumulator wordt gebruikt. vervolgens test uitvoeren met deler getal.
//tussen inspect en test delen door 3 en naar beneden afronden
//resultaat van uitvoeringen verwerken naar einde andere monkey lists
//tel hoeveelheid turns van monkeys, twee actiefste monkeys turns vermenigvuldigen
//alle taken per aap is turn en elke aap z'n turn is een round
class Day11(file: File) {
private val monkeyList = mutableListOf<Monkey>()
init {
file.readLines().forEachIndexed { index, it ->
if (index == 0 || index % 7 == 0) {
monkeyList.add(Monkey())
}
if (it.contains("Starting items")) {
monkeyList.last().items.addAll(it.substring(18).split(", ").map { it.toLong() })
}
if (it.contains("Operation")) {
monkeyList.last().formula = it.substring(19)
}
if (it.contains("Test")) {
monkeyList.last().testDivisibleNumber = it.filter { it.isDigit() }.toLong()
}
if (it.contains("true")) {
monkeyList.last().receiverTrue = it.filter { it.isDigit() }.toInt()
}
if (it.contains("false")) {
monkeyList.last().receiverFalse = it.filter { it.isDigit() }.toInt()
}
}
}
fun solvePart1(): Long {
val testProduct: Long = monkeyList.map { it.testDivisibleNumber }.reduce(Long::times)
executeRounds(10000, testProduct)
return monkeyBusiness()
}
private fun monkeyBusiness(): Long {
monkeyList.sortByDescending { it.turns }
return monkeyList[0].turns * monkeyList[1].turns
}
private fun executeRounds(amount: Int, operation: Long) {
(0 until amount).forEach { _ ->
monkeyList.forEach {
it.items.removeAll { item ->
it.turns++
val noWorry = it.executeFormula(item) % operation
if (noWorry % it.testDivisibleNumber == 0L) {
monkeyList[it.receiverTrue].items.add(noWorry)
} else {
monkeyList[it.receiverFalse].items.add(noWorry)
}
}
}
}
}
}
data class Monkey(
var items: MutableList<Long> = mutableListOf(),
var formula: String = "",
var testDivisibleNumber: Long = 0,
var receiverTrue: Int = 0,
var receiverFalse: Int = 0,
var turns: Long = 0
) {
fun executeFormula(item: Long): Long {
val sign = "[/+*-]+".toRegex().find(formula)?.value
val numberlist = formula.split(" ")
val isdigit = numberlist.last().map { it.toChar().isDigit() }.last()
var number = item
if (isdigit) {
number = numberlist.last().toLong()
}
return when (sign!!.trim()) {
"+" -> item + number
"-" -> item - number
"*" -> item * number
"/" -> item / number
else -> error("Unknown operator $sign")
}
}
}
| 0 | Kotlin | 0 | 0 | b5de21ed7ab063067703e4adebac9c98920dd51e | 3,324 | AoC2022 | Apache License 2.0 |
src/Day03.kt | MerickBao | 572,842,983 | false | {"Kotlin": 28200} | fun main() {
fun computer1(s: String): Int {
var cnt = 0
val n = s.length
val left = HashSet<Char>()
val right = HashSet<Char>()
for (i in 0 until n / 2) left.add(s[i])
for (i in n / 2 until n) right.add(s[i])
for (key in left) {
if (right.contains(key)) {
cnt += if (key in 'a'..'z') key - 'a' + 1
else key - 'A' + 27
}
}
return cnt
}
fun part1(input: List<String>): Int {
var ans = 0
for (s in input) ans += computer1(s)
return ans
}
fun computer2(s1: String, s2: String, s3: String): Int {
var cnt = 0
val left = HashSet<Char>()
val right = HashSet<Char>()
val mid = HashSet<Char>()
for (i in s1) left.add(i)
for (i in s2) mid.add(i)
for (i in s3) right.add(i)
for (key in left) {
if (mid.contains(key) && right.contains(key)) {
cnt += if (key in 'a'..'z') key - 'a' + 1
else key - 'A' + 27
}
}
return cnt
}
fun part2(input: List<String>): Int {
var ans = 0
for (i in input.indices step 3) {
ans += computer2(input[i], input[i + 1], input[i + 2])
}
return ans
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 70a4a52aa5164f541a8dd544c2e3231436410f4b | 1,423 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day14.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2020
import com.dvdmunckhof.aoc.splitOnce
class Day14(private val input: List<String>) {
fun solvePart1(): Long {
val memory = mutableMapOf<Long, Long>()
runProgram { index, value, maskZeroes, maskOnes, _ ->
memory[index] = value and maskZeroes or maskOnes
}
return memory.values.sum()
}
fun solvePart2(): Long {
val memory = mutableMapOf<Long, Long>()
runProgram { index, value, _, maskOnes, floatingBitIndices ->
val possibilities = 1 shl floatingBitIndices.size // 2^size
for (floatingBits in 0 until possibilities) {
val maskedIndex = floatingBitIndices.foldIndexed(index) { valueBitIndex, maskedIndex, floatingBitIndex ->
val bitSet = (floatingBits shr valueBitIndex and 1) == 1
if (bitSet) {
1L shl floatingBitIndex or maskedIndex
} else {
(1L shl floatingBitIndex).inv() and maskedIndex
}
}
memory[maskedIndex or maskOnes] = value
}
}
return memory.values.sum()
}
private fun runProgram(callback: (index: Long, value: Long, maskZeroes: Long, maskOnes: Long, floatingBits: List<Int>) -> Unit) {
var maskZeroes = 0L
var maskOnes = 0L
var floatingBits = emptyList<Int>()
for (line in input) {
if (line.startsWith("mask")) {
val mask = line.substring(7)
maskZeroes = mask.replace('X', '1').toLong(2)
maskOnes = mask.replace('X', '0').toLong(2)
floatingBits = mask.reversed().withIndex().filter { it.value == 'X' }.map { it.index }
} else {
// parse: "mem[xxx] = xxxxxxxx"
val parts = line.substring(4).splitOnce("] = ")
val index = parts.first.toLong()
val value = parts.second.toLong()
callback(index, value, maskZeroes, maskOnes, floatingBits)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 2,128 | advent-of-code | Apache License 2.0 |
year2022/src/cz/veleto/aoc/year2022/Day11.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2022
import cz.veleto.aoc.core.AocDay
import cz.veleto.aoc.core.component6
class Day11(config: Config) : AocDay(config) {
override fun part1(): String {
val monkeys = parseMonkeys()
return simulate(monkeys, rounds = 20) { it / 3 }
}
override fun part2(): String {
val monkeys = parseMonkeys()
val mod = monkeys.map { it.testDivisor }.reduce { acc, i -> acc * i }
return simulate(monkeys, rounds = 10_000) { it.rem(mod) }
}
private fun parseMonkeys(): List<Monkey> = input
.map { it.trim() }
.chunked(7)
.map { (monkey, items, operation, test, testSuccess, testFail) ->
Monkey(
id = monkey[7].digitToInt(),
operation = run {
val parts = operation.split(' ')
val number = parts[5].toLongOrNull()
when (val op = parts[4].single()) {
'+' -> { old: Long -> old + (number ?: old) }
'*' -> { old: Long -> old * (number ?: old) }
else -> error("Unknown operator $op")
}
},
testDivisor = test.split(' ')[3].toInt(),
testSuccessTarget = testSuccess.split(' ')[5].toInt(),
testFailTarget = testFail.split(' ')[5].toInt(),
items = items.drop(16).split(", ").map { it.toLong() }.toMutableList(),
)
}
.toList()
private fun simulate(monkeys: List<Monkey>, rounds: Int, boredom: (Long) -> Long): String {
val inspectsCount = monkeys.associate { it.id to 0 }.toMutableMap()
for (round in 1..rounds) {
for (monkey in monkeys) {
for (item in monkey.items) {
val increasedWorry = monkey.operation(item)
val boredWorry = boredom(increasedWorry)
val target = if (boredWorry.rem(monkey.testDivisor) == 0L) {
monkey.testSuccessTarget
} else {
monkey.testFailTarget
}
monkeys[target].items += boredWorry
}
inspectsCount[monkey.id] = inspectsCount[monkey.id]!! + monkey.items.size
monkey.items.clear()
}
}
return inspectsCount.values
.sortedDescending()
.take(2)
.fold(1L) { acc, i -> acc * i }
.toString()
}
data class Monkey(
val id: Int,
val operation: (Long) -> Long,
val testDivisor: Int,
val testSuccessTarget: Int,
val testFailTarget: Int,
val items: MutableList<Long>,
)
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 2,776 | advent-of-pavel | Apache License 2.0 |
app/src/y2021/day11/Day11DumboOctopus.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day11
import common.Answers
import common.AocSolution
import common.annotations.AoCPuzzle
import kotlin.properties.Delegates
fun main(args: Array<String>) {
Day11DumboOctopus().solveThem()
}
@AoCPuzzle(2021, 11)
class Day11DumboOctopus : AocSolution {
override val answers = Answers(samplePart1 = 1656, samplePart2 = 195, part1 = 1571, part2 = 387)
override fun solvePart1(input: List<String>): Any {
val herdOfDumboOctopuses = createOctopuses(input)
var sumOfFlashes = 0
repeat(100) {
// Let each octopus know that there is a step
herdOfDumboOctopuses.forEach { it.increaseEnergy() }
// Check and reset each octopus
sumOfFlashes += herdOfDumboOctopuses.count { it.hasFlashedLastStep() }
}
return sumOfFlashes
}
override fun solvePart2(input: List<String>): Any {
val herdOfDumboOctopuses = createOctopuses(input)
var step = 0
while (true) {
step++
herdOfDumboOctopuses.forEach { it.increaseEnergy() }
if(herdOfDumboOctopuses.count { it.hasFlashedLastStep() } == herdOfDumboOctopuses.size) {
break
}
}
return step
}
private fun createOctopuses(input: List<String>): List<Octopus> {
val herdOfDumboOctopuses = mutableMapOf<Pair<Int, Int>, Octopus>()
// Create a map of octopus
forAll(input.first().lastIndex, input.lastIndex) { x, y ->
herdOfDumboOctopuses[x to y] = Octopus(initialEnergyLevel = Character.getNumericValue(input[y][x]))
}
// Associate the neighbour situation
forAll(input.first().lastIndex, input.lastIndex) { x, y ->
val position = x to y
for (direction in directions) {
herdOfDumboOctopuses[position]?.addNeighbour(herdOfDumboOctopuses[position + direction])
}
}
return herdOfDumboOctopuses.values.toList()
}
private fun forAll(lastX: Int, lastY: Int, action: (x: Int, y: Int)->Unit) {
for (y in (0..lastX)) {
for (x in (0..lastY)) {
action(x, y)
}
}
}
}
class Octopus(
initialEnergyLevel: Int
) {
private var energyLevel: Int by Delegates.observable(initialEnergyLevel) { _, _, new ->
if (new == 10) neighbours.forEach { it.increaseEnergy() }
}
private val neighbours: MutableList<Octopus> = mutableListOf()
fun addNeighbour(octopus: Octopus?) {
octopus?.let(neighbours::add)
}
fun increaseEnergy() {
energyLevel++
}
fun hasFlashedLastStep(): Boolean = when (energyLevel > 9) {
true -> true.also { energyLevel = 0 }
else -> false
}
override fun toString(): String = "$energyLevel"
}
val directions = listOf(
Pair(0, -1),
Pair(1, -1),
Pair(1, 0),
Pair(1, 1),
Pair(0, 1),
Pair(-1, 1),
Pair(-1, 0),
Pair(-1, -1),
)
operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> =
first + other.first to second + other.second
| 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 3,117 | advent-of-code-2021 | Apache License 2.0 |
src/day8.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import java.util.function.Predicate
import kotlin.system.exitProcess
private const val DAY = 8
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String -> x }
val input = loadInput(DAY, test = false, transformer)
// println(input)
val instructions = input[0]
val map = parseMap(input.drop(2))
println(solvePart1(instructions, map))
println(solvePart2(instructions, map))
}
// Part 1
private fun solvePart1(instructions: String, map: Map<String, Pair<String, String>>): Long {
return getStepsToTarget("AAA", { it == "ZZZ" }, instructions, map)
}
// Part 2
private fun solvePart2(instructions: String, map: Map<String, Pair<String, String>>): Long {
val dist =
map.keys.filter { it.endsWith('A') }
.associateWith { getStepsToTarget(it, { it.endsWith('Z') }, instructions, map) }
return dist.values.reduce(::getLcm)
}
fun getLcm(a: Long, b: Long): Long {
return (a * b) / getGcd(a, b)
}
fun getGcd(a: Long, b: Long): Long {
var x = a
var y = b
while (y > 0) {
x = y.also { y = x.mod(y) }
}
return x
}
fun getStepsToTarget(
from: String,
to: Predicate<String>,
instructions: String,
map: Map<String, Pair<String, String>>
): Long {
var steps = 0.toLong()
val ins = instructions.toMutableList()
var cur = from
while (!to.test(cur)) {
steps++
val i = ins.removeFirst()
cur = if (i == 'L') map[cur]!!.first else map[cur]!!.second
ins.add(i)
}
return steps
}
fun parseMap(input: List<String>): Map<String, Pair<String, String>> {
val regex = "(\\w{3}) = \\((\\w{3}), (\\w{3})\\)".toRegex()
return input.associate {
val x = regex.find(it)!!.groupValues
x[1] to Pair(x[2], x[3])
}
} | 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 1,923 | aoc2023 | MIT License |
kotlin/0115-distinct-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} | /*
* DP bottom up
*/
class Solution {
fun numDistinct(s: String, t: String): Int {
val dp = Array(s.length + 1) { IntArray(t.length + 1) }
for (i in 0..s.length)
dp[i][t.length] = 1
for (i in s.length - 1 downTo 0) {
for (j in t.length - 1 downTo 0) {
if (s[i] == t[j])
dp[i][j] += (dp[i + 1][j + 1] + dp[i + 1][j])
else
dp[i][j] += dp[i + 1][j]
}
}
return dp[0][0]
}
}
/*
* DFS + Memoization
*/
class Solution {
fun numDistinct(s: String, t: String): Int {
val memo = Array(s.length) { IntArray(t.length) { -1 } }
fun dfs(i: Int, j: Int): Int {
if (j == t.length) return 1
if (i == s.length) return 0
if (memo[i][j] != -1) return memo[i][j]
if (s[i] == t[j])
memo[i][j] = dfs(i + 1, j + 1) + dfs(i + 1, j)
else
memo[i][j] = dfs(i + 1, j)
return memo[i][j]
}
return dfs(0, 0)
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,106 | leetcode | MIT License |
app/src/main/java/edu/hm/pedemap/density/strategy/RadiusNormalDistributedDensityCalculationStrategy.kt | matthinc | 342,849,905 | false | {"Jupyter Notebook": 266922, "Kotlin": 99317, "C++": 7484, "HTML": 2589} | package edu.hm.pedemap.density.strategy
import edu.hm.pedemap.density.Density
import edu.hm.pedemap.density.UTMLocation
import edu.hm.pedemap.density.sum
import kotlin.collections.HashMap
import kotlin.math.exp
import kotlin.math.floor
import kotlin.math.pow
class RadiusNormalDistributedDensityCalculationStrategy(val cellSize: Int) : DensityCalculationStrategy {
private var density: List<Map<LocationKey, Density>> = emptyList()
/**
* Normalize distribution: Returns a probability field
* where the sum of all probabilities is 1
*/
private fun Map<LocationKey, Density>.normalizeDensityDistribution(): Map<LocationKey, Density> {
val sum = values.sum()
return mapValues { it.value.normalized(sum.people) }
}
/**
* Calculate the probability field for each device.
* @return [Map<LocationKey, Density>]
*/
private fun densityDistributionByDevice(location: UTMLocation): Map<LocationKey, Density> {
val densDist = HashMap<LocationKey, Density>()
// Calculate the density in a circle with r = accuracy * MAX_RADIUS
val range = floor(location.accuracy!! * MAX_RADIUS).toInt() / cellSize
// Get density function of normal distribution with sigma = accuracy
val distribution = normDist(location.accuracy!!.toDouble())
for (n in -range..range) {
for (e in -range..range) {
val offsetLocation = location.withOffset(n * cellSize, e * cellSize)
// Only calculate within a MAX_RADIUS sigma radius
if (offsetLocation.distanceTo(location) ?: 0 > MAX_RADIUS * location.accuracy!!) continue
val distance = location.distanceTo(offsetLocation) ?: 0
// Calculate the density
val density = Density(distribution(distance))
// Insert into the map
densDist[LocationKey(offsetLocation.northing, offsetLocation.easting)] = density
}
}
// normalize
return densDist.normalizeDensityDistribution()
}
override fun update(locations: List<UTMLocation>) {
density = locations.map { densityDistributionByDevice(it) }
}
override fun calculateDensityAt(locations: List<UTMLocation>, location: UTMLocation): Density {
return density.map { it[LocationKey(location.northing, location.easting)] ?: Density.empty() }.sum()
}
/**
* Returns the density function of the normal distribution
* @param sigma Sigma value. Mu is always 0
*/
private fun normDist(sigma: Double): (Int) -> Double {
// Normal distribution with mu = 0 and variable sigma
return { (1 / (sigma * PI2_SQRT)) * exp(-(it.toDouble()).pow(2.0) / (2 * sigma.pow(2.0))) }
}
/**
* Helper class. Like [UTMLocation] but only northing and easting values.
*/
private data class LocationKey(val n: Int, val e: Int)
companion object {
private const val MAX_RADIUS = 1.5
private const val PI2_SQRT = 2.50662827463 // sqrt(2pi)
}
}
| 0 | Jupyter Notebook | 0 | 2 | afe5d9adbb918141c520934cfe04637be0b880c7 | 3,081 | PeDeMaP | Apache License 2.0 |
src/main/kotlin/day03/Day03.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day03
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day03/Day03.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 03 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private fun parse(path: String): List<String> =
File(path).readLines()
private fun part1(lines: List<String>): Int {
val bitCount = lines[0].length
val gamma = (0 until bitCount)
.map { index -> lines.count { line -> line[index] == '1' } }
.map { count -> if (2 * count > lines.size) 1 else 0 }
.fold(0) { acc, bit -> (acc shl 1) or bit }
val epsilon = gamma xor ((1 shl bitCount) - 1)
return gamma * epsilon
}
private fun part2(lines: List<String>): Int {
val calculateRating = { criteria: Char, complement: Char ->
var index = 0
val values = lines.toMutableList()
while (values.size != 1) {
val count = values.count { it[index] == '1' }
val bit = if (2 * count >= values.size) criteria else complement
values.removeAll { it[index] == bit }
++index
}
values.first().toInt(radix = 2)
}
val o2 = calculateRating('1', '0')
val co2 = calculateRating('0', '1')
return o2 * co2
}
| 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 1,378 | advent-of-code-2021 | MIT License |
src/Day10.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val queue = java.util.LinkedList<Int>()
input.forEach {
if (it == "noop"){
queue.add(0)
}else{
queue.add(0)
queue.add(it.split(" ").last().toInt())
}
}
var v = 1
val arr = queue.take(220).map {
val prev = v
v += it
prev
}
return listOf(20, 60, 100, 140, 180, 220).fold(0){
acc, i ->
acc + i * arr[i-1]
}
}
fun part2(input: List<String>){
val queue = java.util.LinkedList<Int>()
input.forEach {
if (it == "noop"){
queue.add(0)
}else{
queue.add(0)
queue.add(it.split(" ").last().toInt())
}
}
var v = 1
val arr = queue.take(240).map {
val prev = v
v += it
prev
}
arr.forEachIndexed { index, i ->
val idx = index.mod(40)
val pos = i
val sign = if (abs(idx - pos)<=1) "#" else "."
if (idx == 0) println()
print(sign)
}
}
var input = readInput("Test10")
println(part1(input))
part2(input)
input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 1,428 | advent-of-code-kotlin-2022 | Apache License 2.0 |
advent2022/src/main/kotlin/year2022/Day22.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
import Point2D
import kotlin.math.sqrt
private fun List<String>.findAllWithChar(char: Char): Set<Point2D> = buildSet {
this@findAllWithChar.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
if (c == char) {
add(Point2D(x.toLong(), y.toLong()))
}
}
}
}
private fun moveInsideAs2d(
into: Set<Point2D>
): Point2D.(Day22.Direction) -> Point2D = { direction: Day22.Direction ->
when (direction) {
year2022.Day22.Direction.UP, year2022.Day22.Direction.DOWN -> {
val possibleNextStep = into.filter { it.x == x }
val next = this + direction.asPointDiff
when {
next in possibleNextStep -> next
direction == year2022.Day22.Direction.DOWN -> possibleNextStep.minBy { it.y }
else -> possibleNextStep.maxBy { it.y }
}
}
else -> {
val possibleNextStep = into.filter { it.y == y }
val next = this + direction.asPointDiff
when {
next in possibleNextStep -> next
direction == year2022.Day22.Direction.RIGHT -> possibleNextStep.minBy { it.x }
else -> possibleNextStep.maxBy { it.x }
}
}
}
}
inline fun Point2D.move(
length: Int,
dir: Day22.Direction,
field: Day22.FieldInformation,
moveInDir: Point2D.(Day22.Direction) -> Point2D
): Point2D {
var current = this
repeat(length) {
val next = current.moveInDir(dir)
if (next in field.walls) {
return current
}
current = next
}
return current
}
class Day22 : AdventDay(2022, 22) {
enum class Direction(val asPointDiff: Point2D, val facing: Int) {
RIGHT(Point2D.RIGHT, 0),
DOWN(Point2D.DOWN, 1),
LEFT(Point2D.LEFT, 2),
UP(Point2D.UP, 3);
fun turnRight() = when (this) {
RIGHT -> DOWN
DOWN -> LEFT
LEFT -> UP
UP -> RIGHT
}
fun turnLeft() = when (this) {
RIGHT -> UP
DOWN -> RIGHT
LEFT -> DOWN
UP -> LEFT
}
}
sealed interface Instruction {
companion object {
private tailrec fun parseAllHelper(
restInput: String,
currentList: List<Instruction>
): List<Instruction> = when {
restInput.isEmpty() -> currentList
restInput[0].isDigit() -> parseAllHelper(
restInput.dropWhile { it.isDigit() },
currentList + Move(restInput.takeWhile { it.isDigit() }.toInt())
)
restInput[0] == 'L' ->
parseAllHelper(restInput.drop(1), currentList + LeftTurn)
restInput[0] == 'R' ->
parseAllHelper(restInput.drop(1), currentList + RightTurn)
else -> error("malformed input")
}
fun parseAll(input: String): List<Instruction> = parseAllHelper(input, emptyList())
}
}
data class Move(val length: Int) : Instruction
data object LeftTurn: Instruction
data object RightTurn: Instruction
data class FieldInformation(
val field: Set<Point2D>,
val walls: Set<Point2D>,
val instructions: List<Instruction>
) {
data class State(val position: Point2D, val direction: Direction)
companion object {
fun from(input: List<String>): FieldInformation {
val fieldInput = input.dropLast(2)
val freeTiles = fieldInput.findAllWithChar('.')
val wallTiles = fieldInput.findAllWithChar('#')
val regionSize = sqrt((freeTiles.size + wallTiles.size).toFloat() / 6).toInt()
return FieldInformation(
input.dropLast(2).findAllWithChar('.'),
input.dropLast(2).findAllWithChar('#'),
Instruction.parseAll(input.last())
)
}
}
inline fun executeInstructions(
wrap: Point2D.(Direction) -> Point2D
): Pair<Point2D, Direction> {
val topRow = field.minOf { it.y }
val topLeftOpen = field.filter { it.y == topRow }.minBy { it.x }
var currentState = State(topLeftOpen, Direction.RIGHT)
instructions.forEach {
currentState = when (it) {
is LeftTurn -> currentState.copy(
direction = currentState.direction.turnLeft()
)
is RightTurn -> currentState.copy(
direction = currentState.direction.turnRight()
)
is Move -> currentState.copy(
position = currentState.position.move(
it.length,
currentState.direction,
this,
wrap
)
)
}
}
return currentState.position to currentState.direction
}
}
override fun part1(input: List<String>): Long {
val field = FieldInformation.from(input)
return field
.executeInstructions(moveInsideAs2d(field.field + field.walls))
.let { (pos, dir) ->
(pos.y + 1) * 1000 + (pos.x + 1) * 4 + dir.facing
}
}
override fun part2(input: List<String>): Long {
val field = FieldInformation.from(input)
return field // TODO: here has to be another function
.executeInstructions(moveInsideAs2d(field.field + field.walls))
.let { (pos, dir) ->
(pos.y + 1) * 1000 + (pos.x + 1) * 4 + dir.facing
}
}
}
fun main() = Day22().run() | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 5,958 | advent-of-code | Apache License 2.0 |
google/2019/qualification_round/3/main_brute_force.kt | seirion | 17,619,607 | false | {"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294} | import java.util.*
var n = 0
var limit = 0
val prime = arrayListOf(2)
var v = emptyList<Int>() // input
fun main(args: Array<String>) {
for (i in 3 until 10000 step 2) {
if (isPrime(i)) prime.add(i)
}
val t = readLine()!!.toInt()
(1..t).forEach {
print("Case #$it: ")
input()
solve()
}
}
fun isPrime(i: Int) = prime.none { i % it == 0 }
fun input() {
val temp = readLine()!!.split(" ").map { s -> s.toInt() }
limit = temp[0]
n = temp[1]
v = readLine()!!.split("\\s".toRegex()).map { s -> s.toInt() }
}
fun solve() {
val out = ArrayList<ArrayList<Int>>()
var prev = -1
var next = -1
v.forEach { i ->
val p1 = prime.first { i % it == 0 }
val p2 = i / p1
when (next) {
-1 -> { // not determined the result so far
if (prev == -1 || prev == i) {
if (p1 == p2) { // AA
out.add(arrayListOf(p1))
next = p1
} else {
out.add(arrayListOf(p1, p2))
}
} else { // finally it determined
val c1 = out[out.size-1][0]
val c2 = out[out.size-1][1]
if (p1 == c1 || p1 == c2) {
out.add(arrayListOf(p1))
next = p2
} else {
out.add(arrayListOf(p2))
next = p1
}
clear(out)
}
}
else -> {
if (p1 == next) {
out.add(arrayListOf(p1))
next = p2
} else {
out.add(arrayListOf(p2))
next = p1
}
}
}
// forward
prev = i
}
out.add(arrayListOf(next))
val s = TreeSet<Int>()
out.map { it[0] }.forEach { s.add(it) }
val m = TreeMap<Int, Char>()
s.forEachIndexed { i, v -> m[v] = 'A' + i }
out.map { it[0] }.forEach { print(m[it]) }
println("")
}
fun clear(out: ArrayList<ArrayList<Int>>) {
var current = out[out.size-1][0]
var i = out.size - 2
while (i >= 0) {
val p1 = out[i][0]
val p2 = out[i][1]
if (p1 == current) {
out[i] = arrayListOf(p2)
current = p2
} else {
out[i] = arrayListOf(p1)
current = p1
}
i--
}
}
| 0 | C++ | 4 | 4 | a59df98712c7eeceabc98f6535f7814d3a1c2c9f | 2,538 | code | Apache License 2.0 |
src/Day03.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | fun main() {
fun Char.prio() = if (isUpperCase()) {
52 - ('Z' - this)
} else {
26 - ('z' - this)
}
fun part1(input: List<String>): Int {
return input.sumOf {
val first = it.substring(0, it.length / 2)
val second = it.substring(it.length / 2)
first.first { c -> c in second }.prio()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { (a, b, c) ->
a.first { it in b && it in c }.prio()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 815 | AdventOfCode2022 | Apache License 2.0 |
2021/src/main/kotlin/de/skyrising/aoc2021/day4/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day4
import de.skyrising.aoc.*
val test = TestInput("""
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
1 12 20 15 19
3 15 0 2 22
9 18 13 17 5
19 8 7 25 23
20 11 10 24 4
14 21 16 12 6
14 21 17 24 4
10 16 15 9 19
18 8 23 26 20
22 11 13 6 5
2 0 12 3 7
""")
fun readInput(input: PuzzleInput): Pair<List<Int>, List<IntArray>> {
val numbers = input.lines[0].split(',').map(String::toInt)
val boards = mutableListOf<IntArray>()
for (i in 0 until (input.lines.size - 1) / 6) {
val board = IntArray(25)
for (y in 0 until 5) {
val line = input.lines[2 + i * 6 + y].trim().split(Regex("\\s+"))
for (x in 0 until 5) {
board[y * 5 + x] = line[x].toInt()
}
}
boards.add(board)
}
return numbers to boards
}
@PuzzleName("Giant Squid")
fun PuzzleInput.part1(): Any {
val (numbers, boards) = readInput(this)
val markedByRow = ByteArray(boards.size * 5)
val markedByColumn = ByteArray(boards.size * 5)
for (number in numbers) {
for (i in boards.indices) {
val board = boards[i]
for (y in 0 until 5) {
for (x in 0 until 5) {
val num = board[y * 5 + x]
if (num != number) continue
markedByRow[i * 5 + y] = (markedByRow[i * 5 + y].toInt() or (1 shl x)).toByte()
markedByColumn[i * 5 + x] = (markedByColumn[i * 5 + x].toInt() or (1 shl y)).toByte()
}
}
}
var winningBoard: Int? = null
for (i in markedByRow.indices) {
if (markedByRow[i].toInt() == 0x1f) {
winningBoard = i / 5
}
}
for (i in markedByColumn.indices) {
if (markedByColumn[i].toInt() == 0x1f) {
winningBoard = i / 5
}
}
if (winningBoard != null) {
val board = boards[winningBoard]
var sum = 0
for (y in 0 until 5) {
for (x in 0 until 5) {
if ((markedByRow[winningBoard * 5 + y].toInt() shr x) and 1 == 0) {
sum += board[y * 5 + x]
}
}
}
return sum * number
}
}
return -1
}
fun PuzzleInput.part2(): Any {
val (numbers, boards) = readInput(this)
val markedByRow = ByteArray(boards.size * 5)
val markedByColumn = ByteArray(boards.size * 5)
val wonBoards = linkedSetOf<Int>()
val wonNumbers = linkedSetOf<Int>()
for (number in numbers) {
for (i in boards.indices) {
val board = boards[i]
for (y in 0 until 5) {
for (x in 0 until 5) {
val num = board[y * 5 + x]
if (num != number) continue
markedByRow[i * 5 + y] = (markedByRow[i * 5 + y].toInt() or (1 shl x)).toByte()
markedByColumn[i * 5 + x] = (markedByColumn[i * 5 + x].toInt() or (1 shl y)).toByte()
}
}
}
for (i in markedByRow.indices) {
if (markedByRow[i].toInt() == 0x1f) {
wonBoards.add(i / 5)
wonNumbers.add(number)
}
}
for (i in markedByColumn.indices) {
if (markedByColumn[i].toInt() == 0x1f) {
wonBoards.add(i / 5)
wonNumbers.add(number)
}
}
if (wonBoards.size == boards.size) break
}
val winningBoard = wonBoards.last()
val board = boards[winningBoard]
var sum = 0
for (y in 0 until 5) {
for (x in 0 until 5) {
if ((markedByRow[winningBoard * 5 + y].toInt() shr x) and 1 == 0) {
sum += board[y * 5 + x]
}
}
}
return sum * wonNumbers.last()
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 4,138 | aoc | MIT License |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p00/Leet1.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p00
private class Leet1 {
fun twoSum(nums: IntArray, target: Int): IntArray {
for (i in nums.indices) {
getPairForSum(nums, i, target)
?.let { return intArrayOf(i, it) }
}
return intArrayOf()
}
private fun getPairForSum(nums: IntArray, currentIndex: Int, target: Int): Int? {
val first = nums[currentIndex]
for (i in (currentIndex + 1) until nums.size) {
if (target - first == nums[i]) return i
}
return null
}
}
fun main() {
val case1 = "[2,7,11,15]" to 9 // 0,1
val case2 = "[3,2,4]" to 6 // 1,2
val case3 = "[3,3]" to 6 // 0,1
// doWork(case1)
doWork(case2)
// doWork(case3)
}
private fun doWork(case: Pair<String, Int>) {
val solution = Leet1()
val (numsString, target) = case
val nums = numsString.trim('[', ']').split(",").map { it.toInt() }.toIntArray()
val result = solution.twoSum(nums, target).joinToString()
println("Result = $result\n")
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 1,056 | playground | MIT License |
src/main/kotlin/days/day10.kt | josergdev | 573,178,933 | false | {"Kotlin": 20792} | package days
import java.io.File
fun String.parse() = when(this) {
"noop" -> sequence{ yield { (cycle, x): Pair<Int, Int> -> cycle + 1 to x } }
else -> this.replace("addx ", "").toInt().let {
sequence{
yield { (cycle, x): Pair<Int, Int> -> cycle + 1 to x }
yield { (cycle, x): Pair<Int, Int> -> cycle + 1 to x + it }
}
}
}
fun day10part1() = File("input/10.txt").readLines()
.flatMap { it.parse() }
.scan(1 to 1) { acc, f -> f(acc) }
.filter { (cycle, _) -> cycle in 20..220 step 40 }
.sumOf { (cycle, x) -> cycle * x }
fun day10part2() = File("input/10.txt").readLines()
.flatMap { it.parse() }.asSequence()
.scan(0 to 1) { acc, f -> f(acc) }
.map { (cycle, x) -> cycle.mod(40) to x }
.map { (pointer, x ) -> if (x in (pointer - 1 .. pointer + 1)) '#' else '.' }
.chunked(40)
.map { it.joinToString(" ") }
.joinToString("\n")
| 0 | Kotlin | 0 | 0 | ea17b3f2a308618883caa7406295d80be2406260 | 927 | aoc-2022 | MIT License |
ceria/21/src/main/kotlin/Solution.kt | VisionistInc | 317,503,410 | false | null | import java.io.File
val allergenStart ="(contains "
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(input :List<String>) :Int {
var allergenToCandidates = mutableMapOf<String, MutableSet<String>>()
var ingredientsLists = mutableListOf<List<String>>()
for (line in input) {
if (line.contains(allergenStart)) {
val allergens = line.substring(line.indexOf(allergenStart) + allergenStart.length, line.lastIndexOf(")")).split(", ")
for (allergen in allergens) {
val ingredients = line.substring(0, line.indexOf(allergenStart) - 1).split(" ").toSet()
if (allergenToCandidates.contains(allergen)) {
var existingIngredients = allergenToCandidates.get(allergen)!!
allergenToCandidates.put(allergen, existingIngredients.intersect(ingredients).toMutableSet())
} else {
allergenToCandidates.put(allergen, ingredients.toMutableSet())
}
}
ingredientsLists.add(line.substring(0, line.indexOf(allergenStart) - 1).split(" "))
} else {
ingredientsLists.add(line.split(" "))
}
}
var keepFiltering = true
while (keepFiltering) {
for ((k, v) in allergenToCandidates) {
if (v.size == 1) {
var known = v.first()
for ((_, v2) in allergenToCandidates.minus(k)) {
if (v2.contains(known)) {
v2.remove(known)
}
}
}
}
for (v in allergenToCandidates.values) {
if (v.size > 1) {
break
}
keepFiltering = false
}
}
return ingredientsLists.map{ it.minus(allergenToCandidates.values.filter{ !it.isEmpty() }.map{ it.first() } )}.flatten().size
}
private fun solution2(input :List<String>) :String {
var allergenToCandidates = mutableMapOf<String, MutableSet<String>>()
for (line in input) {
if (line.contains(allergenStart)) {
val allergens = line.substring(line.indexOf(allergenStart) + allergenStart.length, line.lastIndexOf(")")).split(", ")
for (allergen in allergens) {
val ingredients = line.substring(0, line.indexOf(allergenStart) - 1).split(" ").toSet()
if (allergenToCandidates.contains(allergen)) {
var existingIngredients = allergenToCandidates.get(allergen)!!
allergenToCandidates.put(allergen, existingIngredients.intersect(ingredients).toMutableSet())
} else {
allergenToCandidates.put(allergen, ingredients.toMutableSet())
}
}
}
}
var keepFiltering = true
while (keepFiltering) {
for ((k, v) in allergenToCandidates) {
if (v.size == 1) {
var known = v.first()
for ((_, v2) in allergenToCandidates.minus(k)) {
if (v2.contains(known)) {
v2.remove(known)
}
}
}
}
for (v in allergenToCandidates.values) {
if (v.size > 1) {
break
}
keepFiltering = false
}
}
var sorted = allergenToCandidates.keys.sortedBy { it }
var dangerous = mutableListOf<String>()
for (k in sorted) {
dangerous.add(allergenToCandidates.get(k)!!.first())
}
return dangerous.joinToString(separator = ",")
} | 0 | Rust | 0 | 0 | 002734670384aa02ca122086035f45dfb2ea9949 | 3,264 | advent-of-code-2020 | MIT License |
src/main/kotlin/Day03.kt | SimonMarquis | 434,880,335 | false | {"Kotlin": 38178} | import Day03.Criteria.LEAST
import Day03.Criteria.MOST
import Day03.Fallback.ONES
import Day03.Fallback.ZEROS
class Day03(raw: List<String>) {
private val input: List<String> = raw
fun part1(): Int = input
.map { number -> number.map { char -> char.toBit() } }
.fold(IntArray(input.first().length)) { acc, bits ->
bits.forEachIndexed { index, bit ->
when (bit) {
false -> acc[index]--
true -> acc[index]++
}
}; acc
}
.reduceToBooleanArray()
.let { it.epsilon() * it.gamma() }
fun part2(): Int = input.oxygenGeneratorRating() * input.c02ScrubberRating()
private fun Char.toBit() = when (this) {
'1' -> true
'0' -> false
else -> throw IllegalStateException()
}
private fun BooleanArray.gamma() = toBinary()
private fun BooleanArray.epsilon() = toBinary { !it }
private fun BooleanArray.toBinary(
eval: (Boolean) -> Boolean = { it }
) = joinToString(separator = "") { if (eval(it)) "1" else "0" }.toInt(2)
private fun IntArray.reduceToBooleanArray(): BooleanArray = map {
when {
it > 0 -> true
it < 0 -> false
else -> throw IllegalStateException()
}
}.toBooleanArray()
private fun List<String>.oxygenGeneratorRating() = findRating(criteria = MOST, fallback = ONES).toInt(2)
private fun List<String>.c02ScrubberRating() = findRating(criteria = LEAST, fallback = ZEROS).toInt(2)
private fun List<String>.findRating(criteria: Criteria, fallback: Fallback): String {
var result = this
for (index in first().indices) {
result = result.filterBy(index, criteria, fallback)
if (result.size == 1) return result.single()
}
throw IllegalStateException()
}
private fun List<String>.filterBy(
index: Int,
criteria: Criteria,
fallback: Fallback,
): List<String> = partition {
when (it[index]) {
'1' -> true
'0' -> false
else -> throw IllegalStateException()
}
}.let { (ones, zeros) ->
when {
zeros.size > ones.size -> zeros to ones
zeros.size < ones.size -> ones to zeros
else -> return when (fallback) {
ONES -> ones
ZEROS -> zeros
}
}
}.let { (mostCommon, leastCommon) ->
when (criteria) {
MOST -> mostCommon
LEAST -> leastCommon
}
}
private enum class Criteria { MOST, LEAST }
private enum class Fallback { ONES, ZEROS }
}
| 0 | Kotlin | 0 | 0 | 8fd1d7aa27f92ba352e057721af8bbb58b8a40ea | 2,703 | advent-of-code-2021 | Apache License 2.0 |
src/Day03.kt | Hwajun1323 | 574,962,608 | false | {"Kotlin": 6799} | fun main() {
val priorities = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun findSharedItem(items: String): String {
val (firstCompartment, secondCompartment) = items.chunked(items.length / 2)
return firstCompartment.filter { c -> secondCompartment.contains(c) }.toSet().joinToString()
}
fun findSharedGroupItem(groupItem: List<String>): String{
val firstElf = groupItem[0]
val secondElf = groupItem[1]
val thirdElf = groupItem[2]
return firstElf.filter { c -> secondElf.contains(c) && thirdElf.contains(c) }.toSet().joinToString()
}
fun part1(input: List<String>): Int {
return input.sumOf {
priorities.indexOf(findSharedItem(it))
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf {
priorities.indexOf(findSharedGroupItem(it))
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 667a8c7a0220bc10ddfc86b74e3e6de44b73d5dd | 1,120 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | fun main() {
fun getGrid(input: List<String>, hasFloor: Boolean = false): Array<Array<Char>> {
val grid = Array(1000) { Array(1000) { '.' } }
var maxX = Int.MIN_VALUE
fun addPath(s: String, t: String) {
val (sy, sx) = s.split(",").map { it.toInt() }
val (ty, tx) = t.split(",").map { it.toInt() }
val xRange = minOf(sx, tx) .. maxOf(sx, tx)
val yRange = minOf(sy, ty) .. maxOf(sy, ty)
maxX = maxOf(maxX, sx, tx)
for (i in xRange) {
for (j in yRange) {
grid[i][j] = '#'
}
}
}
input.forEach { s -> s.split(" -> ").zipWithNext().forEach { addPath(it.first, it.second) } }
if (hasFloor) {
for (j in grid[0].indices) grid[maxX + 2][j] = '#'
}
return grid
}
fun dropSand(grid: Array<Array<Char>>): Boolean {
var x = 0
var y = 500
if (grid[x][y] == '#') return false
while (x < 999) {
if (grid[x + 1][y] == '.') {
x ++
} else if (grid[x + 1][y - 1] == '.') {
x ++
y --
} else if (grid[x + 1][y + 1] == '.') {
x ++
y ++
} else {
break
}
}
if (x >= 999) return false
grid[x][y] = '#'
return true
}
fun part1(input: List<String>): Int {
val grid = getGrid(input)
var i = 0
while (dropSand(grid)) i ++
return i
}
fun part2(input: List<String>): Int {
val grid = getGrid(input, hasFloor = true)
var i = 0
while (dropSand(grid)) i ++
return i
}
println(part1(readInput("data/Day14_test")))
println(part1(readInput("data/Day14")))
println(part2(readInput("data/Day14_test")))
println(part2(readInput("data/Day14")))
} | 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 1,693 | aoc-2022-in-kotlin | Apache License 2.0 |
day23/part2.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Part Two ---
// As you reach the trailhead, you realize that the ground isn't as slippery as
// you expected; you'll have no problem climbing up the steep slopes.
//
// Now, treat all slopes as if they were normal paths (.). You still want to
// make sure you have the most scenic hike possible, so continue to ensure that
// you never step onto the same tile twice. What is the longest hike you can
// take?
//
// In the example above, this increases the longest hike to 154 steps:
//
// #S#####################
// #OOOOOOO#########OOO###
// #######O#########O#O###
// ###OOOOO#.>OOO###O#O###
// ###O#####.#O#O###O#O###
// ###O>...#.#O#OOOOO#OOO#
// ###O###.#.#O#########O#
// ###OOO#.#.#OOOOOOO#OOO#
// #####O#.#.#######O#O###
// #OOOOO#.#.#OOOOOOO#OOO#
// #O#####.#.#O#########O#
// #O#OOO#...#OOO###...>O#
// #O#O#O#######O###.###O#
// #OOO#O>.#...>O>.#.###O#
// #####O#.#.###O#.#.###O#
// #OOOOO#...#OOO#.#.#OOO#
// #O#########O###.#.#O###
// #OOO###OOO#OOO#...#O###
// ###O###O#O###O#####O###
// #OOO#OOO#O#OOO>.#.>O###
// #O###O###O#O###.#.#O###
// #OOOOO###OOO###...#OOO#
// #####################O#
//
// Find the longest hike you can take through the surprisingly dry hiking
// trails listed on your map. How many steps long is the longest hike?
import java.io.*
enum class Direction(val dx: Int, val dy: Int) {
UP(0, -1),
DOWN(0, 1),
LEFT(-1, 0),
RIGHT(1, 0)
}
data class Node(val x: Int, val y: Int) {
val links: MutableList<Link> = mutableListOf()
constructor(pos: Pair<Int, Int>) : this(pos.first, pos.second)
}
data class Link(val to: Node, val steps: Int)
data class Crossroad(val at: Pair<Int, Int>, val steps: Int, val paths: List<Pair<Int, Int>>)
val map = File("input.txt").readLines()
val start = map[0].indexOf('.') to 0
val end = map.last().indexOf('.') to map.size - 1
fun findCrossroad(start: Pair<Int, Int>, to: Pair<Int, Int>): Crossroad {
var from = start
var next = listOf(to)
var steps = 0
while (next.size == 1) {
steps++
if (next[0] == end) {
return Crossroad(end, steps, listOf())
}
var (x, y) = next[0]
next = Direction.entries
.map { x + it.dx to y + it.dy }
.filter { it != from && map[it.second][it.first] != '#' }
from = x to y
}
return Crossroad(from, steps, next)
}
// Reduce the map to a graph where nodes are forks in the path with edge
// weights equal to the number of steps to reach that fork.
val startNode = Node(start.first, start.second)
val nodes = mutableMapOf(start to startNode)
val remainingCrossroads = mutableListOf(Crossroad(start, 0, listOf(start.first to 1)))
while (remainingCrossroads.isNotEmpty()) {
val (at, _, paths) = remainingCrossroads.removeFirst()
paths.forEach {
val node = nodes[at]!!
val crossroad = findCrossroad(at, it)
var crossroadNode = nodes[crossroad.at]
if (crossroadNode != null) {
if (node.links.all { it.to != crossroadNode }) {
node.links.add(Link(crossroadNode, crossroad.steps))
crossroadNode.links.add(Link(node, crossroad.steps))
}
} else {
crossroadNode = Node(crossroad.at)
nodes[crossroad.at] = crossroadNode
node.links.add(Link(crossroadNode, crossroad.steps))
crossroadNode.links.add(Link(node, crossroad.steps))
remainingCrossroads.add(crossroad)
}
}
}
// Now a DFS to find the longest path - I'm pretty happy with this algo, taking
// only roughly twice as long as my part 1 solution. Lots of people on reddit
// seemed to have runtimes way longer.
val endNode = nodes[end]!!
fun findLongestPath(node: Node, visited: MutableSet<Node> = mutableSetOf()): Int {
var longest = Int.MIN_VALUE
if (node == endNode) {
return 0
}
if (node.links.isNotEmpty() && visited.add(node)) {
longest = node.links.maxOf { it.steps + findLongestPath(it.to, visited) }
visited.remove(node)
}
return longest
}
println(findLongestPath(startNode))
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 3,915 | adventofcode2023 | MIT License |
src/main/kotlin/advent/day6/Lanternfish.kt | hofiisek | 434,171,205 | false | {"Kotlin": 51627} | package advent.day6
import advent.loadInput
import java.io.File
/**
* @author <NAME>
*/
@JvmInline
value class Fish(val age: Int)
fun part1(input: File) = loadFish(input).let(::makeThoseFishHaveRecursiveSex)
/**
* Just accumulate the fish in the list and count them
*/
fun makeThoseFishHaveRecursiveSex(fish: List<Fish> = emptyList(), day: Int = 0): Int = when (day) {
80 -> fish.count()
else -> makeThoseFishHaveRecursiveSex(
fish = fish.flatMap {
if (it.age == 0)
listOf(Fish(6), Fish(8))
else
listOf(Fish(it.age - 1))
},
day = day + 1
)
}
fun part2(input: File) = loadFish(input)
.groupingBy { it.age }
.eachCount()
.mapValues { (_, count) -> count.toLong() } // integer would overflow
.let { (0..8).associateWith { 0L } + it } // make sure the map contains all ages
.let(::makeThoseFishHaveEffectiveRecursiveSex)
/**
* Fish are perverts and in 256 days there's too many fish that a single list can effectively contain :)
* However, we only need to know the number of fish for each age, which can be represented as a map where
* the keys are ages and the values are the number of fish of that age.
*/
fun makeThoseFishHaveEffectiveRecursiveSex(ageToCount: Map<Int, Long>, day: Int = 0): Long = when (day) {
256 -> ageToCount.values.sum()
else -> ageToCount.entries.associate { (age, _) ->
val crackedCondomsCount = ageToCount.getValue(0)
when (age) {
6 -> age to crackedCondomsCount + ageToCount.getValue(7)
8 -> age to crackedCondomsCount
else -> age to ageToCount.getValue(age + 1)
}
}
.let { makeThoseFishHaveEffectiveRecursiveSex(it, day + 1) }
}
fun loadFish(input: File): List<Fish> = input.readLines()
.first()
.split(",")
.map(String::toInt)
.map(::Fish)
fun main() {
// with(loadInput(day = 6, filename = "input_example.txt")) {
with(loadInput(day = 6)) {
println(part1(this))
println(part2(this))
}
} | 0 | Kotlin | 0 | 2 | 3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb | 2,070 | Advent-of-code-2021 | MIT License |
src/org/aoc2021/Day12.kt | jsgroth | 439,763,933 | false | {"Kotlin": 86732} | package org.aoc2021
import java.nio.file.Files
import java.nio.file.Path
object Day12 {
private fun solvePart1(lines: List<String>): Int {
val points = parseLines(lines)
return search("start", points)
}
private fun solvePart2(lines: List<String>): Int {
val points = parseLines(lines)
return searchPart2("start", points)
}
private fun parseLines(lines: List<String>): Map<String, List<String>> {
return lines.flatMap { line ->
val (b, e) = line.split("-")
listOf(b to e, e to b)
}
.groupBy(Pair<String, String>::first, Pair<String, String>::second)
}
private fun search(p: String, points: Map<String, List<String>>, visitedSmallCaves: Set<String> = setOf()): Int {
return points[p]!!.filter { edge ->
edge != "start" && !visitedSmallCaves.contains(edge)
}
.sumOf { edge ->
if (edge == "end") {
1
} else {
val newVisitedCaves = if (edge.all(Char::isLowerCase)) {
visitedSmallCaves.plus(edge)
} else {
visitedSmallCaves
}
search(edge, points, newVisitedCaves)
}
}
}
private fun searchPart2(
p: String,
points: Map<String, List<String>>,
visitedSmallCaves: Set<String> = setOf(),
visitedTwice: Boolean = false,
): Int {
return points[p]!!.filter { it != "start" }
.sumOf { edge ->
if (edge == "end") {
1
} else if (visitedSmallCaves.contains(edge) && visitedTwice) {
0
} else {
val newVisitedTwice = if (visitedSmallCaves.contains(edge)) true else visitedTwice
val newVisitedCaves = if (edge.all(Char::isLowerCase)) {
visitedSmallCaves.plus(edge)
} else {
visitedSmallCaves
}
searchPart2(edge, points, newVisitedCaves, newVisitedTwice)
}
}
}
@JvmStatic
fun main(args: Array<String>) {
val lines = Files.readAllLines(Path.of("input12.txt"), Charsets.UTF_8)
val solution1 = solvePart1(lines)
println(solution1)
val solution2 = solvePart2(lines)
println(solution2)
}
} | 0 | Kotlin | 0 | 0 | ba81fadf2a8106fae3e16ed825cc25bbb7a95409 | 2,516 | advent-of-code-2021 | The Unlicense |
src/day24/second/Solution.kt | verwoerd | 224,986,977 | false | null | package day24.second
import day24.first.ErisTile
import day24.first.ErisTile.BUG
import day24.first.ErisTile.EMPTY
import day24.first.toTile
import tools.Coordinate
import tools.adjacentCoordinates
import tools.timeSolution
import tools.xRange
import tools.yRange
const val MINUTES = 200
val CENTER = Coordinate(2, 2)
val EMPTY_MAZE = emptyMaze()
typealias ErisMaze = Map<Coordinate, ErisTile>
typealias LevelMap = Map<Int, ErisMaze>
fun main() = timeSolution {
val maze = System.`in`.bufferedReader().readLines()
.mapIndexed { y, line -> line.toCharArray().mapIndexed { x, char -> Coordinate(x, y) to char.toTile() } }.flatten()
.toMap().withDefault { EMPTY }
var time = 0
var currentMaxLevel = 1 // inside start zone
var currentMinLevel = -1 // outside start zone
var levelMap = mutableMapOf(0 to maze, -1 to emptyMaze(), 1 to emptyMaze()).withDefault { EMPTY_MAZE }
while (time < MINUTES) {
levelMap = levelMap.map { (level, maze) -> level to maze.expandMaze(levelMap, level) }
.toMap().toMutableMap().withDefault { EMPTY_MAZE }
// check the outer edge
when {
levelMap.getValue(currentMaxLevel).filter { it.key != CENTER }.any { it.value == BUG } -> levelMap[++currentMaxLevel] =
emptyMaze()
}
when {
levelMap.getValue(currentMinLevel).filter { it.key != CENTER }.any { it.value == BUG } -> levelMap[--currentMinLevel] =
emptyMaze()
}
time++
// println("-------------SUMARY---------------")
// println("Iteration $time levels: ($currentMinLevel, $currentMaxLevel)")
// println("Bugs: ${levelMap.map {level -> level.value.count { it.value == BUG } }.sum()}")
// levelMap.forEach { (level, maze) ->
// println("Level $level\n")
// maze.render()
//
// }
}
println("Bugs: ${levelMap.map { level -> level.value.count { it.value == BUG } }.sum()}")
}
fun emptyMaze(): ErisMaze =
(0 until 5).flatMap { y -> (0 until 5).map { x -> (Coordinate(x, y) to EMPTY) } }.toMap().withDefault { EMPTY }
fun ErisMaze.expandMaze(levelMap: LevelMap, level: Int) =
keys.filter { it != CENTER }.fold(mutableMapOf<Coordinate, ErisTile>()) { acc, coordinate ->
val adjacentBugs = coordinate.adjacentCoordinatesRecursive(level)
.map { (level, coordinate) -> levelMap.getValue(level).getValue(coordinate) }.count { it == BUG }
acc.also {
acc[coordinate] = when (getValue(coordinate)) {
BUG -> when (adjacentBugs) {
1 -> BUG
else -> EMPTY
}
EMPTY -> when (adjacentBugs) {
1, 2 -> BUG
else -> EMPTY
}
}
}
}.toMap().withDefault { EMPTY }
fun Map<Coordinate, ErisTile>.render() {
when {
isEmpty() -> println("Empty maze")
else -> {
val (xMin, xMax) = xRange()
val (yMin, yMax) = yRange()
for (y in yMin..yMax) {
for (x in xMin..xMax) {
when {
x == 2 && y == 2 -> print('?')
else -> print(getValue(Coordinate(x, y)).char)
}
}
println()
}
}
}
}
private fun Coordinate.adjacentCoordinatesRecursive(currentLevel: Int) = adjacentCoordinates(this).map {
when {
it == CENTER -> when (this) {
Coordinate(1, 2) -> (0 until 5).map { x -> currentLevel + 1 to Coordinate(0, x) }
Coordinate(3, 2) -> (0 until 5).map { x -> currentLevel + 1 to Coordinate(4, x) }
Coordinate(2, 1) -> (0 until 5).map { y -> currentLevel + 1 to Coordinate(y, 0) }
Coordinate(2, 3) -> (0 until 5).map { y -> currentLevel + 1 to Coordinate(y, 4) }
else -> error("Unknown adjacent coordinate encounterd $this")
}
it.x == -1 -> listOf(currentLevel - 1 to Coordinate(1, 2))
it.x == 5 -> listOf(currentLevel - 1 to Coordinate(3, 2))
it.y == -1 -> listOf(currentLevel - 1 to Coordinate(2, 1))
it.y == 5 -> listOf(currentLevel - 1 to Coordinate(2, 3))
else -> listOf(currentLevel to it)
}
}.flatten()
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 3,933 | AoC2019 | MIT License |
src/main/kotlin/com/jacobhyphenated/advent2022/day7/Day7.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day7
import com.jacobhyphenated.advent2022.Day
/**
* Day 7: No Space Left On Device
*
* To run the system update, your device needs more space.
* The puzzle input is a list of commands that provide the directory structure and file sizes on the device.
*/
class Day7: Day<List<String>> {
override fun getInput(): List<String> {
return readInputFile("day7").lines()
}
override fun warmup(input: List<String>): Any {
return runInputCommands(input)
}
/**
* A directory does not have a size itself. The size is the sum of all its files and directories (recursive)
* Return the sum of all directories with sizes of at most 100000
*/
override fun part1(input: List<String>): Int {
val (_, allDirectories) = runInputCommands(input)
return allDirectories
.map { it.size }
.filter { it <= 100000 }
.sum()
}
/**
* The total space on the device is 70,000,000. You need 30,000,000 free space to run the update.
* What is the size of the smallest single directory you can delete that frees up enough space?
*/
override fun part2(input: List<String>): Int {
val (root, allDirectories) = runInputCommands(input)
val freeSpace = 70_000_000 - root.size
val spaceToDelete = 30_000_000 - freeSpace
return allDirectories
.map { it.size }
.filter { it >= spaceToDelete }
.min()
}
/**
* Run through the input commands to build the file system.
*
* @param input list of cd and ls commands to use to build out the file system
* @return The root directory and a list of all directories in the file system.
* These particular problems involve looking at each directory in the file system,
* including nested directories. It's useful to return that flat list, so we don't
* need to recurse the graph structure to look for directories we already know about.
*/
private fun runInputCommands(input: List<String>): Pair<Directory, List<Directory>> {
val root = Directory(null, "/")
var currentDirectory = root
val allDirectories = mutableListOf(root)
input.forEach { cmd ->
val args = cmd.split(" ")
if (args[0] == "$"){
// Handle the CD command to change directories
if (args[1] == "cd") {
currentDirectory = when(args[2]) {
".." -> currentDirectory.parent!!
"/" -> root
else -> currentDirectory.children
.filterIsInstance<Directory>()
.find { it.name == args[2] }!!
}
}
// The other command is ls, which prints the FileSystem lines, handled below
}
// This line is not a command, so it is the output of ls, either a directory or a file
else if (args[0] == "dir") {
val dir = Directory(currentDirectory, args[1])
allDirectories.add(dir)
currentDirectory.children.add(dir)
}
else {
val file = File(currentDirectory, args[1], args[0].toInt())
currentDirectory.children.add(file)
}
}
return Pair(root, allDirectories)
}
}
sealed class FileSystem(val parent: Directory?, val name: String) {
abstract val size: Int
}
class File(
parent: Directory,
name: String,
override val size: Int
): FileSystem(parent, name)
class Directory(
parent: Directory?,
name: String,
val children: MutableList<FileSystem> = mutableListOf()
): FileSystem(parent, name) {
override val size: Int
get() = children.sumOf { it.size }
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 3,884 | advent2022 | The Unlicense |
src/main/kotlin/aoc2023/Day04.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2023
import AoCDay
// https://adventofcode.com/2023/day/4
object Day04 : AoCDay<Int>(
title = "Scratchcards",
part1ExampleAnswer = 13,
part1Answer = 20829,
part2ExampleAnswer = 30,
part2Answer = 12648035,
) {
private class Card(val id: Int, val winningNumbers: List<Int>, val myNumbers: List<Int>)
private val SPACE = Regex("""\s+""")
private fun parseCard(input: String): Card {
val (card, numbers) = input.split(':', limit = 2)
val id = card.substringAfter("Card").trim().toInt()
val (winningNumbers, myNumbers) = numbers.split('|', limit = 2)
fun parseNumbers(input: String) = input.trim().split(SPACE).map(String::toInt)
return Card(id, parseNumbers(winningNumbers), parseNumbers(myNumbers))
}
private val Card.matchingNumbers get() = myNumbers.filter { it in winningNumbers }.size
private val Card.points get() = matchingNumbers.let { if (it == 0) 0 else 1 shl (it - 1) }
override fun part1(input: String) = input
.lineSequence()
.map(::parseCard)
.sumOf { it.points }
override fun part2(input: String): Int {
val cards = input.lines().map(::parseCard)
val copies = cards.associateTo(HashMap()) { it.id to 1 }
for (card in cards) {
val currentCopies = copies.getValue(card.id)
repeat(card.matchingNumbers) { i ->
val nextId = card.id + i + 1
copies[nextId] = copies.getValue(nextId) + currentCopies
}
}
return copies.values.sum()
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 1,585 | advent-of-code-kotlin | MIT License |
src/main/kotlin/day21.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.*
fun main() {
val input = Input.day(21)
println(day21A(input))
println(day21B(input))
}
fun day21A(input: Input, steps: Int = 64): Long {
val map = InfinityMap(input)
return possibleGardenPlots(map, steps)
}
/* Runs in a few hours */
fun day21B(input: Input, steps: Int = 26501365): Long {
val map = InfinityMap(input)
return possibleGardenPlots(map, steps)
}
private fun Char.isMovable() = this == 'S' || this == '.'
/* Let's pretend I got 65 and 131 from the length of the map and not Reddit */
private fun possibleGardenPlots(map: InfinityMap, steps: Int): Long {
val sequence = mutableListOf<Long>()
repeat(steps) { step ->
if((step - 65) % 131 == 0) {
sequence.add(map.reachable().toLong())
if (sequence.size == 3) {
val sequenceFixer = Sequence(sequence)
repeat((steps - step) / 131) {
sequenceFixer.addNextValue()
}
return sequenceFixer.values.last()
}
}
map.walk()
}
return map.reachable().toLong()
}
private class InfinityMap(private val input: Input) {
private var on = setOf(Point(input.lines[0].length / 2, input.lines.size / 2))
val width = input.lines[0].length
val height = input.lines.size
fun walk() {
on = on.flatMap { onPoint ->
listOf(
Point(onPoint.x - 1, onPoint.y),
Point(onPoint.x + 1, onPoint.y),
Point(onPoint.x, onPoint.y - 1),
Point(onPoint.x, onPoint.y + 1),
).filter {
input.lines[Math.floorMod(it.y, height)][Math.floorMod(it.x, width)].isMovable()
}
}.toSet()
}
fun reachable() = on.size
} | 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 1,788 | AdventOfCode2023 | MIT License |
src/aoc21/Day03.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc21.day03
import lib.Solution
import lib.Collections.histogram
enum class Day03Rating {
O2,
CO2
}
private val solution = object : Solution<List<String>, Int>(2021, "Day03") {
override fun parse(input: String): List<String> = input.lines()
override fun format(output: Int): String = output.toString()
fun countBits(input: List<String>): Map<Int, Map<Char, Int>> =
input.flatMap { it.mapIndexed(::Pair) }
.groupBy({ it.first }, { it.second })
.mapValues { it.value.histogram() }
fun gamma(input: Map<Int, Map<Char, Int>>) = input.mapValues {
it.value.maxByOrNull { it.value }?.key ?: '0'
}
fun epsilon(input: Map<Int, Map<Char, Int>>) = input.mapValues {
it.value.minByOrNull { it.value }?.key ?: '0'
}
fun Map<Int, Char>.readBits() = values.toCharArray().concatToString().toInt(2)
override fun part1(input: List<String>) = countBits(input).let {
gamma(it).readBits() * epsilon(it).readBits()
}
fun bitCriteria(bitCount: Map<Char, Int>, rating: Day03Rating): Char {
return bitCount['1']?.let { one ->
bitCount['0']?.let { zero ->
when (rating) {
Day03Rating.O2 -> if (one >= zero) '1' else '0'
Day03Rating.CO2 -> if (one < zero) '1' else '0'
}
} ?: '1'
} ?: '0'
}
tailrec fun filterValues(values: List<String>, rating: Day03Rating, bit: Int = 0): String {
if (values.size == 1) {
return values[0]
}
val bitCount = values.map { it[bit] }.histogram()
val selectedBit = bitCriteria(bitCount, rating)
return filterValues(values.filter { it[bit] == selectedBit }, rating, bit + 1)
}
override fun part2(input: List<String>) =
filterValues(input, Day03Rating.O2).toInt(2) *
filterValues(input, Day03Rating.CO2).toInt(2)
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 1,862 | aoc-kotlin | Apache License 2.0 |
src/Day16.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun input(): ValvesInput {
val file = "Day16"
val g: HashMap<Int, List<Edge>> = HashMap()
val flows = IntArray(readInput(file).size)
val idMap = readInput(file).mapIndexed { i, s ->
(s.substring(
"Valve ".length, "Valve ".length + 2
) to i).also { if (it.first == "AA") start = it.second }
}.toMap()
readInput(file).forEach { s ->
val (valveS, tunnelS) = s.split(";")
val id = idMap[valveS.substring("Valve ".length, "Valve ".length + 2)]!!
val flow = valveS.substring("Valve AA has flow rate=".length).toInt()
// input could contain `tunnel lead to valve` instead, but I just replaced it with plural
val paths = tunnelS.substring(" tunnels lead to valves ".length).split(", ")
g[id] = paths.map { Edge(idMap[it]!!, 1) }
flows[id] = flow
}
// pre-calculate bitmask state with all open valves
flows.withIndex().filter { (_, f) -> f > 0 }.forEach { allOpen = setOpened(allOpen, it.index) }
// pre-calculate bitmask -> closed valves flow sum
fun closedFlowSum(curFlowSum: Int, i: Int, curOpened: Long) {
if (i >= flows.size) {
closedFlowSum[curOpened] = curFlowSum
return
}
if (flows[i] > 0) {
closedFlowSum(curFlowSum - flows[i], i + 1, setOpened(curOpened, i))
}
closedFlowSum(curFlowSum, i + 1, curOpened)
}
closedFlowSum(flows.filter { f -> f > 0 }.sum(), 0, 0)
return ValvesInput(g, flows)
}
private var start = -1
private var maxRelease = 0
private var allOpen = 0L
private var closedFlowSum = HashMap<Long, Int>()
private fun part1(input: ValvesInput): Int {
dfs(input.g, input.flows, start, 0L, 30, 0)
return maxRelease
}
private var cache = HashMap<CacheEntry, Int>()
private fun dfs(g: HashMap<Int, List<Edge>>, flows: IntArray, cur: Int, opened: Long, timeLeft: Int, releaseSum: Int) {
// if run out of time or nothing left to open - stop
if (timeLeft <= 0 || opened == allOpen) {
maxRelease = maxRelease.getMax(releaseSum)
return
}
// if we have already been in current state but didn't improve - stop
val cacheE = CacheEntry(opened, cur, timeLeft)
val cached = cache[cacheE]
if (cached != null && cached >= releaseSum) return
cache[cacheE] = releaseSum
val curFlow = flows[cur]
val shouldOpen = curFlow > 0 && !isOpened(opened, cur)
val openedCur = setOpened(opened, cur)
g[cur]!!.forEach {
if (shouldOpen) {
dfs(g, flows, it.v, openedCur, timeLeft - 1 - 1, releaseSum + (timeLeft - 1) * curFlow)
}
dfs(g, flows, it.v, opened, timeLeft - 1, releaseSum)
}
}
// bitmask manipulation to keep track of opened valves
fun isOpened(n: Long, i: Int): Boolean = ((n shr i) and 1) == 1L
fun setOpened(n: Long, i: Int): Long = (n or (1L shl i))
private fun part2(input: ValvesInput): Int {
maxRelease = 0
bigDfs(input.g, input.flows, start, start, 0L, 26, 0)
return maxRelease
}
private var bigCache = HashMap<BigCacheEntry, Int>()
private fun bigDfs(
g: HashMap<Int, List<Edge>>, flows: IntArray, curMe: Int, curEl: Int, opened: Long, timeLeft: Int, releaseSum: Int
) {
if (timeLeft <= 0 || opened == allOpen) {
maxRelease = maxRelease.getMax(releaseSum)
return
}
// if after opening all closed valves instantly we cant do better - stop
if (closedFlowSum[opened]!! * (timeLeft - 1) + releaseSum <= maxRelease) {
return
}
// since it doesn't matter who exactly in which position, cache both (me, el) and (el, me)
val cacheE = BigCacheEntry(opened, curMe, curEl, timeLeft)
val cached = bigCache[cacheE]
if (cached != null && cached >= releaseSum) return
bigCache[cacheE] = releaseSum
bigCache[BigCacheEntry(opened, curEl, curMe, timeLeft)] = releaseSum
val curFlowMe = flows[curMe]
val makeSenseToOpenMe = curFlowMe > 0 && !isOpened(opened, curMe)
val openedMe = setOpened(opened, curMe)
val releaseMe = (timeLeft - 1) * curFlowMe
val curFlowEl = flows[curEl]
val makeSenseToOpenEl = curFlowEl > 0 && !isOpened(opened, curEl)
val openedEl = setOpened(opened, curEl)
val releaseEl = (timeLeft - 1) * curFlowEl
if (makeSenseToOpenMe && makeSenseToOpenEl && curMe != curEl) {
bigDfs(g, flows, curMe, curEl, openedMe or openedEl, timeLeft - 1, releaseSum + releaseMe + releaseEl)
}
if (makeSenseToOpenMe) {
g[curEl]!!.forEach { el ->
bigDfs(g, flows, curMe, el.v, openedMe, timeLeft - 1, releaseSum + releaseMe)
}
}
if (makeSenseToOpenEl) {
g[curMe]!!.forEach { me ->
bigDfs(g, flows, me.v, curEl, openedEl, timeLeft - 1, releaseSum + releaseEl)
}
}
g[curMe]!!.forEach { me ->
g[curEl]!!.forEach { el ->
bigDfs(g, flows, me.v, el.v, opened, timeLeft - 1, releaseSum)
}
}
}
fun main() {
measure { part1(input()) }
measure { part2(input()) }
}
data class BigCacheEntry(val opened: Long, val curMe: Int, val curEl: Int, val timeLeft: Int)
data class CacheEntry(val opened: Long, val cur: Int, val timeLeft: Int)
data class Edge(val v: Int, val w: Int)
data class ValvesInput(val g: HashMap<Int, List<Edge>>, val flows: IntArray)
// (V)-_(V) okay, dp would've been better after all | 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 5,374 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/nosswald/aoc/days/Day21.kt | 7rebux | 722,943,964 | false | {"Kotlin": 34890} | package de.nosswald.aoc.days
import de.nosswald.aoc.Day
// https://adventofcode.com/2023/day/21
object Day21 : Day<Int>(21, "Step Counter") {
private data class Point(val x: Int, val y: Int) {
fun neighbors(): Set<Point> = buildSet {
add(Point(x + 1, y))
add(Point(x - 1, y))
add(Point(x, y + 1))
add(Point(x, y - 1))
}
}
private fun countSteps(garden: List<CharArray>, start: Point): Map<Point, Int> = buildMap {
val queue = ArrayDeque<Pair<Point, Int>>()
queue.add(Pair(start, 0))
while (queue.isNotEmpty()) {
val (point, steps) = queue.removeFirst()
if (!this.contains(point) && steps <= 64) {
this[point] = steps
queue.addAll(
point
.neighbors()
.filter { (x, y) -> y in garden.indices && x in garden[y].indices }
.filter { (x, y) -> garden[y][x] != '#' }
.filterNot(this::contains)
.map { Pair(it, steps + 1) }
)
}
}
}
override fun partOne(input: List<String>): Int {
val garden = input.map(String::toCharArray)
val start = Point(
x = garden.first { it.contains('S') }.indexOf('S'),
y = garden.indexOfFirst { it.contains('S') }
)
return countSteps(garden, start).values.count { it % 2 == 0 }
}
override fun partTwo(input: List<String>): Int {
TODO("Not yet implemented")
}
// I adjusted the output since there is only a test provided for a maximum of 6 steps
// TODO: Make part functions accept additional options for better test support
override val partOneTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"...........",
".....###.#.",
".###.##..#.",
"..#.#...#..",
"....#.#....",
".##..S####.",
".##..#...#.",
".......##..",
".##.#.####.",
".##..##.##.",
"...........",
) to 42
)
override val partTwoTestExamples: Map<List<String>, Int>
get() = TODO("Not yet implemented")
}
| 0 | Kotlin | 0 | 1 | 398fb9873cceecb2496c79c7adf792bb41ea85d7 | 2,291 | advent-of-code-2023 | MIT License |
src/Day07.kt | rromanowski-figure | 573,003,468 | false | {"Kotlin": 35951} | object Day07 : Runner<Int, Int>(7, 95437, 24933642) {
override fun part1(input: List<String>): Int {
val fs = Directory(null, "")
buildFileSystem(fs, input)
return allDirectories(fs).filter { it.size() <= 100000 }.sumOf { it.size() }
}
private fun buildFileSystem(fs: Directory, input: List<String>) {
var pwd = fs
var prevCommand: Command<*>? = null
input.forEach {
when {
it.startsWith("$") -> when (it.split(" ")[1]) {
"cd" -> {
pwd = Cd(it.split(" ")[2]).also { c -> prevCommand = c }.exec(pwd)
}
"ls" -> prevCommand = Ls
}
else -> {
when (prevCommand) {
Ls -> {
val tokens = it.split(" ")
when (tokens[0]) {
"dir" -> {
pwd.add(Directory(pwd, tokens[1]))
}
else -> {
pwd.add(File(tokens[0].toInt(), tokens[1]))
}
}
}
else -> error("don't know what this output is")
}
}
}
}
}
private fun allDirectories(fs: Directory): Set<Directory> {
val directories = mutableSetOf(fs)
var children = directories.flatMap { it.children }.filterIsInstance<Directory>()
while (children.isNotEmpty()) {
directories.addAll(children)
children = directories.flatMap { it.children }.filterIsInstance<Directory>() - directories.toSet()
}
return directories
}
override fun part2(input: List<String>): Int {
val totalDiskSpace = 70000000
val requiredSpace = 30000000
val fs = Directory(null, "")
buildFileSystem(fs, input)
val spaceNeededToFree = requiredSpace - (totalDiskSpace - fs.size())
return allDirectories(fs).map { it.size() }.filter { it >= spaceNeededToFree }.min()
}
sealed interface Input
sealed interface Command<T> : Input {
fun exec(fs: Directory): T
}
data class Cd(val path: String) : Command<Directory> {
override fun exec(fs: Directory): Directory {
var pwd = fs
when (path) {
"/" -> while (pwd.parent != null) pwd = pwd.parent!!
".." -> pwd = pwd.parent ?: pwd
else -> {
val dir = Directory(pwd, path)
pwd.add(dir)
pwd = dir
}
}
return pwd
}
}
object Ls : Command<Set<Item>> {
override fun exec(fs: Directory): Set<Item> = fs.children
override fun toString() = "ls"
}
sealed interface Item : Input {
fun size(): Int
}
data class File(private val fileSize: Int, val name: String) : Item {
override fun size() = fileSize
}
class Directory(
var parent: Directory? = null,
private val name: String,
val children: MutableSet<Item> = mutableSetOf()
) : Item {
override fun size() = children.sumOf { it.size() }
fun add(item: Item) = children.add(item)
override fun toString(): String {
return if (parent == null) {
name.ifBlank { "/" }
} else {
"$parent$name/"
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6ca5f70872f1185429c04dcb8bc3f3651e3c2a84 | 3,656 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/test/kotlin/io/github/fbiville/solver/SolverTest.kt | fbiville | 129,937,320 | false | null | package io.github.fbiville.solver
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class SolverTest {
@Test
fun `solves problems with maximum 1 move`() {
val plus2 = { n: Number -> (n.toInt() + 2) }.toNamedFunction("plus2")
val times2 = { n: Number -> (n.toInt() * 2) }.toNamedFunction("times2")
val problem = Solver(initialValue = 0,
maxMoves = 1,
targetValue = 2,
operations = listOf(plus2, times2))
val solution = problem.solve() as ValidatedSolution
assertThat(solution.moves)
.containsExactly(
SuccessfulMove(Success(2, plus2)))
}
@Test
fun `solves problems with maximum 2 moves`() {
val plus2 = { n: Number -> (n.toInt() + 2) }.toNamedFunction("plus2")
val times3 = { n: Number -> (n.toInt() * 3) }.toNamedFunction("times3")
val sumDigits = { n: Number -> n.toString().chars().map({ it - '0'.toInt() }).sum() }.toNamedFunction("sumDigits")
val problem = Solver(
initialValue = 7,
maxMoves = 2,
targetValue = 3,
operations = listOf(plus2, times3, sumDigits))
val solution = problem.solve() as ValidatedSolution
assertThat(solution.moves)
.containsExactly(
SuccessfulMove(Success(21, times3)),
SuccessfulMove(Success(3, sumDigits)))
}
@Test
fun `solves problems with maximum n moves`() {
val plus2 = { n: Number -> (n.toInt() + 2) }.toNamedFunction("plus2")
val times3 = { n: Number -> (n.toInt() * 3) }.toNamedFunction("times3")
val sumDigits = { n: Number -> n.toString().chars().map({ it - '0'.toInt() }).sum() }.toNamedFunction("sumDigits")
val problem = Solver(initialValue = 2817,
maxMoves = 4,
targetValue = 168,
operations = listOf(plus2, times3, sumDigits))
val solution = problem.solve() as ValidatedSolution
assertThat(solution.moves)
.containsExactly(
SuccessfulMove(Success(18, sumDigits)),
SuccessfulMove(Success(54, times3)),
SuccessfulMove(Success(56, plus2)),
SuccessfulMove(Success(168, times3)))
}
@Test
fun `selects the shortest solution`() {
val times3 = { n: Number -> (n.toInt() * 3) }.toNamedFunction("times3")
val times9 = { n: Number -> (n.toInt() * 9) }.toNamedFunction("times9")
val problem = Solver(initialValue = 3,
maxMoves = 2,
targetValue = 27,
operations = listOf(times3, times9))
val solution = problem.solve() as ValidatedSolution
assertThat(solution.moves).containsExactly(SuccessfulMove(Success(27, times9)))
}
}
private fun Function1<Number, Number>.toNamedFunction(name: String): NamedFunction = NamedFunction(name, this)
| 4 | Kotlin | 0 | 0 | 490d55d8b6af8fc40704439c19effbcc1a8f9e1b | 3,061 | calculator-solver | Apache License 2.0 |
src/main/kotlin/me/camdenorrb/timorforest/tree/DecisionTree.kt | camdenorrb | 202,772,314 | false | null | package me.camdenorrb.timorforest.tree
import me.camdenorrb.timorforest.node.base.NodeBase
import kotlin.math.pow
class DecisionTree(val header: List<String>, val trainingData: List<List<Any>>) {
var root: NodeBase<*>
init {
root = buildTree(trainingData)
}
fun classCounts(rows: List<List<Any>>): MutableMap<Any, Int> {
val labelCount = mutableMapOf<Any, Int>()
rows.forEach {
val label = it.last()
labelCount[label] = labelCount.getOrDefault(label, 0) + 1
}
return labelCount
}
inner class Question(val column: Int, val value: Any) {
fun match(example: List<Any>): Boolean {
val exampleValue = example[column]
return if (value is Number) {
(exampleValue as Number).toInt() >= value.toInt()
}
else {
value == exampleValue
}
}
override fun toString(): String {
val condition = if (value is Number) ">=" else "=="
return "Is ${header[column]} $condition $value"
}
}
fun gini(rows: List<List<Any>>): Double {
val counts = classCounts(rows)
var impurity = 1.0
counts.forEach { lbl, count ->
val probOfLbl = count / rows.size.toDouble()
impurity -= probOfLbl.pow(2)
}
return impurity
}
fun infoGain(left: List<List<Any>>, right: List<List<Any>>, uncertainty: Double): Double {
val p = left.size.toDouble() / (left.size + right.size)
return uncertainty - p * gini(left) - (1 - p) * gini(right)
}
fun findBestSplit(rows: List<List<Any>>): Pair<Double, Question?> {
var bestGain = 0.0
var bestQuestion: Question? = null
val uncertainty = gini(rows)
val nFeatures = rows[0].size - 1
for (col in 0 until nFeatures) {
rows.map { it[col] }.toSet().forEach { value ->
val question = Question(col, value)
val (trueRows, falseRows) = rows.partition { question.match(it) }
if (trueRows.isEmpty() || falseRows.isEmpty()) {
return@forEach
}
val gain = infoGain(trueRows, falseRows, uncertainty)
if (gain >= bestGain) {
bestGain = gain
bestQuestion = question
}
}
}
return bestGain to bestQuestion
}
private fun buildTree(inputs: List<List<Any>>): NodeBase<*> {
val (gain, question) = findBestSplit(inputs)
if (gain == 0.0 || question == null) {
return Leaf(classCounts(inputs))
}
val (trueRows, falseRows) = inputs.partition { question.match(it) }
val trueBranch = buildTree(trueRows)
val falseBranch = buildTree(falseRows)
return Node(question, trueBranch, falseBranch)
}
/*
fun predict(row: List<Comparable<*>>): Leaf {
var node = root
while (true) {
when(node) {
is Leaf -> return node
is Node -> node = if (node.value.match(row)) node.trueBranch else node.falseBranch
else -> error("Invalid node type ${node::class.simpleName}")
}
}
}*/
fun predict(row: List<Any>): Leaf {
var node = root
while (true) {
when(node) {
is Leaf -> return node
is Node -> node = if (node.value.match(row)) node.trueBranch else node.falseBranch
else -> error("Invalid node type ${node::class.simpleName}")
}
}
}
private fun prettyText(node: NodeBase<*>, indent: String = ""): String {
return when(node) {
is Leaf -> "Predict: ${node.value}".prependIndent(indent)
is Node -> "${node.value} \n--> True: \n${prettyText(node.trueBranch, "$indent ")} \n--> False: \n${prettyText(node.falseBranch, "$indent ")}".prependIndent(indent)
else -> error("Unknown node type!")
}
}
override fun toString(): String {
return prettyText(root)
}
data class Leaf(override val value: Map<Any, Int>) : NodeBase<Map<Any, Int>>
data class Node(override val value: Question, val trueBranch: NodeBase<*>, val falseBranch: NodeBase<*>) : NodeBase<Question>
} | 0 | Kotlin | 0 | 0 | b746f0ca27b587fbff4dcc08d97051f463cac53e | 4,431 | TimorForest | MIT License |
kotlin/src/katas/kotlin/leetcode/regex_matching/v4/RegexMatching.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.regex_matching.v4
import datsok.shouldEqual
import org.junit.jupiter.api.Test
class RegexMatching {
@Test fun `some examples`() {
"".matchRegex("") shouldEqual true
"a".matchRegex("a") shouldEqual true
"ab".matchRegex("ab") shouldEqual true
"a".matchRegex("b") shouldEqual false
"ab".matchRegex("a") shouldEqual false
"a".matchRegex(".") shouldEqual true
"ab".matchRegex("..") shouldEqual true
"ab".matchRegex("a.") shouldEqual true
"ab".matchRegex(".b") shouldEqual true
"abc".matchRegex("..") shouldEqual false
"abc".matchRegex("b..") shouldEqual false
"".matchRegex("a?") shouldEqual true
"a".matchRegex("a?") shouldEqual true
"b".matchRegex("a?") shouldEqual false
"".matchRegex("a*") shouldEqual true
"a".matchRegex("a*") shouldEqual true
"aaa".matchRegex("a*") shouldEqual true
"b".matchRegex("a*") shouldEqual false
"abc".matchRegex(".*") shouldEqual true
}
}
typealias Matcher = (String) -> List<String>
fun char(c: Char): Matcher = { input ->
if (input.firstOrNull() == c) listOf(input.drop(1)) else emptyList()
}
fun anyChar(): Matcher = { input ->
if (input.isNotEmpty()) listOf(input.drop(1)) else emptyList()
}
fun zeroOrOne(matcher: Matcher): Matcher = { input ->
listOf(input) + matcher(input)
}
fun zeroOrMore(matcher: Matcher): Matcher = { input ->
listOf(input) + matcher(input).flatMap(zeroOrMore(matcher))
}
private fun String.matchRegex(regex: String): Boolean {
val matchers = regex.fold(emptyList<Matcher>()) { acc, c ->
when (c) {
'.' -> acc + anyChar()
'?' -> acc.dropLast(1) + zeroOrOne(acc.last())
'*' -> acc.dropLast(1) + zeroOrMore(acc.last())
else -> acc + char(c)
}
}
return matchers
.fold(listOf(this)) { inputs, matcher ->
inputs.flatMap(matcher)
}
.any { it.isEmpty() }
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,038 | katas | The Unlicense |
2022/src/main/kotlin/de/skyrising/aoc2022/day5/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2022.day5
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.chars.CharArrayList
private fun parseInput(input: PuzzleInput): Pair<List<String>, Array<CharArrayList>> {
val splitPoint = input.lines.indexOf("")
val setup = input.lines.subList(0, splitPoint - 1)
val moves = input.lines.subList(splitPoint + 1, input.lines.size)
val width = (setup[0].length + 1) / 4
val stacks = Array(width) { CharArrayList() }
for (depth in setup.size - 1 downTo 0) {
val line = setup[depth]
for (i in 0 until width) {
val char = line[i * 4 + 1]
if (char != ' ') stacks[i].add(char)
}
}
return moves to stacks
}
private fun Array<CharArrayList>.toResult(): String {
val result = StringBuilder()
for (element in this) {
result.append(element.getChar(element.lastIndex))
}
return result.toString()
}
@PuzzleName("Supply Stacks")
fun PuzzleInput.part1(): Any {
val (moves, stacks) = parseInput(this)
for (move in moves) {
val (count, from, to) = move.ints()
repeat(count) {
stacks[to - 1].add(stacks[from - 1].removeChar(stacks[from - 1].lastIndex))
}
}
return stacks.toResult()
}
fun PuzzleInput.part2(): Any {
val (moves, stacks) = parseInput(this)
for (move in moves) {
val (count, from, to) = move.ints()
val indexFrom = stacks[from - 1].size - count
val indexTo = stacks[from - 1].size
stacks[to - 1].addAll(stacks[from - 1].subList(indexFrom, indexTo))
stacks[from - 1].removeElements(indexFrom, indexTo)
}
return stacks.toResult()
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 1,665 | aoc | MIT License |
src/main/kotlin/io/github/pshegger/aoc/y2015/Y2015D6.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2015
import io.github.pshegger.aoc.common.BaseSolver
import io.github.pshegger.aoc.common.Coordinate
import kotlin.math.max
class Y2015D6 : BaseSolver() {
override val year = 2015
override val day = 6
override fun part1(): Int =
parseInput().fold(List(GRID_SIZE * GRID_SIZE) { false }) { acc, instruction ->
instruction.applyToState1(acc)
}.count { it }
override fun part2(): Int =
parseInput().fold(List(GRID_SIZE * GRID_SIZE) { 0 }) { acc, instruction ->
instruction.applyToState2(acc)
}.sum()
private fun parseInput() = readInput {
readLines().map { Instruction.parseString(it) }
}
private data class Instruction(val type: InstructionType, val p1: Coordinate, val p2: Coordinate) {
fun applyToState1(state: List<Boolean>) =
getIndices().fold(state.toMutableList()) { acc, i ->
acc[i] = when (type) {
InstructionType.On -> true
InstructionType.Off -> false
InstructionType.Toggle -> !acc[i]
}
acc
}
fun applyToState2(state: List<Int>) =
getIndices().fold(state.toMutableList()) { acc, i ->
acc[i] = when (type) {
InstructionType.On -> acc[i] + 1
InstructionType.Off -> max(0, acc[i] - 1)
InstructionType.Toggle -> acc[i] + 2
}
acc
}
private fun getIndices(): List<Int> = (p1.x..p2.x)
.flatMap { x ->
(p1.y..p2.y).map { y ->
y * GRID_SIZE + x
}
}
companion object {
fun parseString(str: String): Instruction {
val type = InstructionType.values().first { it.regex.matches(str) }
val groups = type.regex.matchEntire(str)?.groupValues ?: error("That should never happen")
return Instruction(
type,
Coordinate(groups[1].toInt(), groups[2].toInt()),
Coordinate(groups[3].toInt(), groups[4].toInt()),
)
}
}
}
private enum class InstructionType(val regex: Regex) {
On(turnOnRegex),
Off(turnOffRegex),
Toggle(toggleRegex)
}
companion object {
private val turnOnRegex = "turn on (\\d+),(\\d+) through (\\d+),(\\d+)".toRegex()
private val turnOffRegex = "turn off (\\d+),(\\d+) through (\\d+),(\\d+)".toRegex()
private val toggleRegex = "toggle (\\d+),(\\d+) through (\\d+),(\\d+)".toRegex()
private const val GRID_SIZE = 1000
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 2,763 | advent-of-code | MIT License |
src/Day02.kt | baghaii | 573,918,961 | false | {"Kotlin": 11922} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach{
val their = it[0]
val our = it[2]
val score = scoreRound(their, our)
sum += score
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach {
val their = it[0]
val our = it[2]
val score = pickOurs(their, our)
sum += score
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class Outcome {
WIN,
LOSE,
TIE
}
// Part 1 Functions
fun scoreRound(their: Char, our: Char): Int {
val win = when {
(their == 'A' && our == 'X') -> Outcome.TIE
(their == 'A' && our == 'Y') -> Outcome.WIN
(their == 'A' && our == 'Z') -> Outcome.LOSE
(their == 'B' && our == 'X') -> Outcome.LOSE
(their == 'B' && our == 'Y') -> Outcome.TIE
(their == 'B' && our == 'Z') -> Outcome.WIN
(their == 'C' && our == 'X') -> Outcome.WIN
(their == 'C' && our == 'Y') -> Outcome.LOSE
(their == 'C' && our == 'Z') -> Outcome.TIE
else -> Outcome.TIE
}
val matchScore = when (win) {
Outcome.WIN -> 6
Outcome.TIE -> 3
Outcome.LOSE -> 0
}
val selectionScore = when(our) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> 0
}
return matchScore + selectionScore
}
// Part 2 Functions
fun pickOurs(their: Char, our: Char): Int {
val outcome = when (our) {
'X' -> Outcome.LOSE
'Y' -> Outcome.TIE
'Z' -> Outcome.WIN
else -> Outcome.TIE
}
val matchScore = when (outcome) {
Outcome.WIN -> 6
Outcome.TIE -> 3
Outcome.LOSE -> 0
}
val ourSelection = ourChoice(their, outcome)
val selectionScore = when(ourSelection) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> 0
}
return matchScore + selectionScore
}
fun ourChoice(their: Char, outcome: Outcome): Char {
return when {
(their == 'A' && outcome == Outcome.WIN) -> 'Y'
(their == 'A' && outcome == Outcome.TIE) -> 'X'
(their == 'A' && outcome == Outcome.LOSE) -> 'Z'
(their == 'B' && outcome == Outcome.WIN) -> 'Z'
(their == 'B' && outcome == Outcome.TIE) -> 'Y'
(their == 'B' && outcome == Outcome.LOSE) -> 'X'
(their == 'C' && outcome == Outcome.WIN) -> 'X'
(their == 'C' && outcome == Outcome.TIE) -> 'Z'
(their == 'C' && outcome == Outcome.LOSE) -> 'Y'
else -> 'X'
}
} | 0 | Kotlin | 0 | 0 | 8c66dae6569f4b269d1cad9bf901e0a686437469 | 2,825 | AdventOfCode2022 | Apache License 2.0 |
kotlin/src/_0004.kt | yunshuipiao | 179,794,004 | false | null | import org.testng.annotations.Test
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val m = nums1.size
val n = nums2.size
if (m > n) {
return findMedianSortedArrays(nums2, nums1)
}
var low = 0
var high = m
while (low <= high) {
// 针对 nums1 进行 二分查找
val i = low + (high - low).shr(1)
val j = (m + n).shr(1) - i
if (i < m && nums2[j - 1] > nums1[i]) {
low = i + 1
} else if (i > 0 && nums1[i - 1] > nums2[j]) {
high = i - 1
} else {
// 找到想要的 i 值
println(i)
var minRight = 0
minRight = when {
i == m -> nums2[j]
j == n -> nums1[i]
else -> Math.min(nums1[i], nums2[j])
}
if ((m + n) % 2 == 1) {
return minRight * 1.0
}
var maxLeft = 0
maxLeft = when {
i == 0 -> nums2[j - 1]
j == 0 -> nums1[i - 1]
else -> Math.max(nums1[i - 1], nums2[j - 1])
}
return 0.5 * (maxLeft + minRight)
// var maxLeft = 0
// maxLeft = when {
// i == 0 -> nums2[j - 1]
// j == 0 -> nums1[i - 1]
// else -> Math.max(nums1[i - 1], nums2[j - 1])
// }
// if ((m + n) % 2 == 1) {
// return maxLeft * 1.0
// }
// // 偶数逻辑
// var minRight = 0
// minRight = when {
// i == m -> nums2[j]
// j == n -> nums1[i]
// else -> Math.min(nums1[i], nums2[j])
// }
// return 0.5 * (maxLeft + minRight)
}
}
return 0.0
}
fun findMedianSortArray(nums1: ArrayList<Int>): Double {
val m = nums1.size
if (m == 0) {
return 0.0
}
val low = 0
val high = m
val mid = low + (high - low).shr(1)
if (m % 2 == 0) {
return 0.5 * (nums1[mid] + nums1[mid - 1])
} else {
return nums1[mid] * 1.0
}
}
@Test
fun _0004() {
// 10 2 4 6 8 9
val nums1 = IntArray(5)
nums1[0] = 1
nums1[1] = 2
nums1[2] = 3
nums1[3] = 4
nums1[4] = 5
val nums2 = IntArray(1)
nums2[0] = 3
val result = findMedianSortedArrays(nums1, nums2)
// val result = findMedianSortArray(arrayListOf(1, 2))
print(result)
} | 29 | Kotlin | 0 | 2 | 6b188a8eb36e9930884c5fa310517be0db7f8922 | 2,470 | rice-noodles | Apache License 2.0 |
src/main/kotlin/io/nozemi/aoc/solutions/year2021/day03/BinaryDiagnostic.kt | Nozemi | 433,882,587 | false | {"Kotlin": 92614, "Shell": 421} | package io.nozemi.aoc.solutions.year2021.day03
import io.nozemi.aoc.puzzle.Puzzle
import io.nozemi.aoc.solutions.year2021.day03.impl.countBitsInPosition
import io.nozemi.aoc.solutions.year2021.day03.impl.toEpsilonRateBinary
import io.nozemi.aoc.solutions.year2021.day03.impl.toGammaRateBinary
import kotlin.reflect.KFunction0
class BinaryDiagnostic(input: String) : Puzzle<List<String>>(input) {
override fun Sequence<String>.parse(): List<String> = this.toList()
override fun solutions(): List<KFunction0<Any>> = listOf(
::part1,
::part2
)
private fun part1(): Long {
return findPowerConsumption()
}
private fun part2(): Long {
return findLifeSupportRating()
}
fun findPowerConsumption(input: List<String> = this.parsedInput): Long {
val mostCommon = findMostCommonValuesForEachBit(input)
val gammaRate = mostCommon.toGammaRateBinary().toLong(radix = 2)
val epsilonRate = mostCommon.toEpsilonRateBinary().toLong(radix = 2)
return (gammaRate * epsilonRate)
}
fun findLifeSupportRating(input: List<String> = this.parsedInput): Long {
val oxygenGeneratorRating = findMeasureTypeRating(MeasureType.OXYGEN_GENERATOR_RATING, input).toInt(radix = 2)
val co2ScrubberRatingFound = findMeasureTypeRating(MeasureType.CO2_SCRUBBER_RATING, input).toInt(radix = 2)
return (oxygenGeneratorRating * co2ScrubberRatingFound).toLong()
}
/**
* Return a map of bit's position and which was most common for that position in the current List<String>.
*/
fun findMostCommonValuesForEachBit(
input: List<String> = this.parsedInput
): Map<Int, Int> {
// Map<Position, Most Common Bit>
val mostCommon = mutableMapOf<Int, Int>()
val counts = input.countBitsInPosition()
for (i in 0 until counts.size) {
val position = counts[i] ?: Pair(0, 0)
if (position.first >= position.second) mostCommon[i] = 0
if (position.second >= position.first) mostCommon[i] = 1
}
return mostCommon
}
fun findMeasureTypeRating(measureType: MeasureType, input: List<String> = this.parsedInput): String {
var ratings = input
var counts = ratings.countBitsInPosition()
while (ratings.size > 1) {
counts.forEach { count ->
counts = ratings.countBitsInPosition()
if (ratings.size <= 1) return@forEach
val zeroCount = counts[count.key]?.first ?: 0
val oneCount = counts[count.key]?.second ?: 0
ratings = when (measureType) {
/**
* Oxygen Generator Rating Rules
* - Keep the ones with bit that has a majority in the current position.
* - If equal amount of 0s and 1s, keep the ones with 1s in the current position.
*/
MeasureType.OXYGEN_GENERATOR_RATING -> {
if (zeroCount > oneCount) {
ratings.filter { it.toCharArray()[count.key] == '0' }
} else if (oneCount >= zeroCount) {
ratings.filter { it.toCharArray()[count.key] == '1' }
} else {
ratings
}
}
/**
* CO2 Scrubber Rating Rules
* - Keep the ones with bit that has a minority in the current position.
* - If equal amount of 0s and 1s, keep the ones with 0s in the current position.
*/
MeasureType.CO2_SCRUBBER_RATING -> {
if (oneCount < zeroCount) {
ratings.filter { it.toCharArray()[count.key] == '1' }
} else if (zeroCount <= oneCount) {
ratings.filter { it.toCharArray()[count.key] == '0' }
} else {
ratings
}
}
}
}
}
if (ratings.size != 1) return "00000"
return ratings.first()
}
enum class MeasureType {
OXYGEN_GENERATOR_RATING,
CO2_SCRUBBER_RATING
}
} | 0 | Kotlin | 0 | 0 | fc7994829e4329e9a726154ffc19e5c0135f5442 | 4,373 | advent-of-code | MIT License |
src/main/kotlin/me/peckb/aoc/_2015/calendar/day19/Day19.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2015.calendar.day19
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import javax.inject.Inject
import kotlin.Int.Companion.MAX_VALUE
class Day19 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
fun partOne(filename: String) = generatorFactory.forFile(filename).read { input ->
val (replacements, molecule) = loadPartOneInput(input)
molecule.stepForward(replacements).size
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input ->
val data = loadPartTwoInput(input)
val longestReplacement = data.replacements.keys.maxByOrNull { it.length }?.length ?: MAX_VALUE
var molecule = data.molecule
var end = molecule.length
var start = end - 1
var replacements = 0
while(molecule != "e") {
val sequence = molecule.substring(start, end)
data.replacements[sequence]?.let { replacement ->
// we found a replacement, so swap it out and reset our search
molecule = molecule.replace(start, end, replacement)
end = molecule.length
start = end - 1
replacements++
} ?: run {
// either way, we can't add more data to our range and find a replacement
// so remove the last character and try again
if (end - start == longestReplacement || start == 0) {
end--
start = end -1
} else {
start--
}
}
}
replacements
}
private fun loadPartTwoInput(input: Sequence<String>): Data {
val replacements = mutableMapOf<String, String>()
var mainString: String? = null
var loadingReplacements = true
input.forEach { line ->
if (line.isBlank()) {
loadingReplacements = false
} else {
if (loadingReplacements) {
val (origin, destination) = line.split(" => ").let { it.first() to it.last() }
replacements[destination] = origin
} else {
mainString = line
}
}
}
return Data(replacements, mainString!!)
}
private fun loadPartOneInput(input: Sequence<String>): Pair<Map<String, List<String>>, String> {
val replacements = mutableMapOf<String, List<String>>()
var mainString: String? = null
var loadingReplacements = true
input.forEach { line ->
if (line.isBlank()) {
loadingReplacements = false
} else {
if (loadingReplacements) {
val (origin, destination) = line.split(" => ").let { it.first() to it.last() }
replacements.merge(origin, mutableListOf(destination), List<String>::plus)
} else {
mainString = line
}
}
}
return replacements to mainString!!
}
data class Data(val replacements: MutableMap<String, String>, val molecule: String)
}
private fun String.replace(start: Int, end: Int, replacement: String): String {
val newStart = take(start)
val newEnd = takeLast(length - end)
return "$newStart$replacement$newEnd"
}
private fun String.stepForward(replacements: Map<String, List<String>>): Set<String> {
val molecules = mutableSetOf<String>()
replacements.forEach { (source, destinations) ->
destinations.forEach { destination ->
val regex = source.toRegex()
val matchResults = regex.findAll(this)
matchResults.forEach { matchResult ->
molecules.add(replace(matchResult.range.first, matchResult.range.last + 1, destination))
}
}
}
return molecules
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 3,489 | advent-of-code | MIT License |
src/main/kotlin/me/grison/aoc/y2020/Day21.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2020
import me.grison.aoc.*
class Day21 : Day(21, 2020) {
override fun title() = "Allergen Assessment"
override fun partOne(): Any {
val (allergens, ingredients) = load()
val allAllergens = allergens.values.fold(setOf<String>()) { a, b -> a.union(b) }
return (ingredients.keys - allAllergens).sumOf { ingredients[it]!! }
}
override fun partTwo(): Any {
val (allergens, _) = load()
// keep going until all allergens found
while (allergens.values.map { it.size }.maxOrNull()!! > 1) {
// select allergens where there's only one ingredient
for (allergen in allergens.filter { it.value.size == 1 }.keys) {
// for every other allergen
for (allergen2 in (allergens - allergen).keys) {
// remove the already known allergen <-> ingredient
allergens[allergen2] = allergens[allergen2]!! - allergens[allergen]!!
}
}
}
// returns ingredients sorted by allergens
return allergens.map { (all, ing) -> p(all, ing.first()) }
.sortedBy { it.first }
.joinToString(",") { it.second }
}
private fun load(): Pair<MutableMap<String, Set<String>>, MutableMap<String, Int>> {
val allergens = mutableMapOf<String, Set<String>>()
val ingredients = mutableMapOf<String, Int>()
inputList.forEach { line ->
val foodIngredients = line.before(" (").normalSplit(" ").toSet()
foodIngredients.forEach { ing -> ingredients[ing] = (ingredients[ing] ?: 0) + 1 }
val foodAllergens = line.before(")").after(" (contains ").normalSplit(", ")
foodAllergens.forEach { all -> allergens.merge(all, foodIngredients) { prev, new -> prev.intersect(new) } }
}
return p(allergens, ingredients)
}
} | 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 1,916 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/Day04.kt | Jenner-Zhl | 576,294,907 | false | {"Kotlin": 8369} | fun main() {
val regex = Regex("[-,]")
fun processInput(input: List<String>, block: (List<Int>) -> Boolean): Int {
var count = 0
input.forEach {line ->
val numbers = line.split(regex).map { it.toInt() }
if (block(numbers)) {
count++
println(line)
}
}
return count
}
fun part1(input: List<String>): Int {
return processInput(input) {numbers ->
(numbers[0] - numbers[2]) * (numbers[1] - numbers[3]) <= 0
}
}
fun part2(input: List<String>): Int {
return processInput(input) {numbers ->
numbers[0] <= numbers[3] && numbers[1] >= numbers[2]
}
}
// 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")
// part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 5940b844155069e020d1859bb2d3fb06cb820981 | 1,010 | aoc | Apache License 2.0 |
src/com/hlq/leetcode/array/Question349.kt | HLQ-Struggle | 310,978,308 | false | null | package com.hlq.leetcode.array
/**
* @author HLQ_Struggle
* @date 2020/11/08
* @desc LeetCode 349. 两个数组的交集 https://leetcode-cn.com/problems/intersection-of-two-arrays/
*/
fun main() {
val nums1 = IntArray(4)
nums1[0] = 1
nums1[1] = 2
nums1[2] = 2
nums1[3] = 1
val nums2 = IntArray(2)
nums2[0] = 7
nums2[1] = 9
// Set + contains
intersection(nums1, nums2)
// Kotlin intersect
intersection1(nums1, nums2)
intersection2(nums1, nums2)
// 排序 + 双指针
intersection3(nums1, nums2)
}
/**
* 排序 + 双指针
*/
fun intersection3(nums1: IntArray, nums2: IntArray): IntArray {
if (nums1.isEmpty() || nums2.isEmpty()) {
return IntArray(0)
}
var i = 0
var j = 0
var index = 0
var resultSet = hashSetOf<Int>()
nums1.sort()
nums2.sort()
while (i < nums1.size && j < nums2.size) {
if (nums1[i] == nums2[j]) {
resultSet.add(nums1[i])
i++
j++
} else if (nums1[i] < nums2[j]) {
i++
} else if (nums1[i] > nums2[j]) {
j++
}
}
var resultArray = IntArray(resultSet.size)
for (resultNum in resultSet) {
resultArray[index++] = resultNum
}
println(resultArray.asList())
return resultArray
}
/**
* Kotlin intersect
*/
fun intersection2(nums1: IntArray, nums2: IntArray): IntArray {
if (nums1.isEmpty() || nums2.isEmpty()) {
return IntArray(0)
}
return nums1.intersect(nums2.asList()).toIntArray()
}
/**
* Kotlin intersect
*/
fun intersection1(nums1: IntArray, nums2: IntArray): IntArray {
if (nums1.isEmpty() || nums2.isEmpty()) {
return IntArray(0)
}
val tempSet = nums1.asList().intersect(nums2.asList())
var resultArray = IntArray(tempSet.size)
var index = 0
for (result in tempSet) {
resultArray[index++] = result
}
println(resultArray.asList())
return resultArray
}
/**
* Set + contains
*/
fun intersection(nums1: IntArray, nums2: IntArray): IntArray {
if (nums1.isEmpty() || nums2.isEmpty()) {
return IntArray(0)
}
var tempSet = hashSetOf<Int>()
var resultSet = hashSetOf<Int>()
for (num1 in nums1) {
tempSet.add(num1)
}
for (num2 in nums2) {
if (tempSet.contains(num2)) {
resultSet.add(num2)
}
}
var resultIntArray = IntArray(resultSet.size)
var index = 0
for (resultNum in resultSet) {
resultIntArray[index++] = resultNum
}
println(resultIntArray.asList())
return resultIntArray
}
| 0 | Kotlin | 0 | 2 | 76922f46432783218ddd34e74dbbf3b9f3c68f25 | 2,612 | LeetCodePro | Apache License 2.0 |
src/Day01.kt | mikrise2 | 573,939,318 | false | {"Kotlin": 62406} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
var maxSum = Int.MIN_VALUE
var tempSum = 0
for (index in input.indices) {
when {
input[index] == "" -> {
maxSum = max(tempSum, maxSum)
tempSum=0
}
index == input.size - 1 -> {
maxSum = max(tempSum+input[index].toInt(), maxSum)
}
else -> {
tempSum+=input[index].toInt()
}
}
}
return maxSum
}
fun part2(input: List<String>): Int {
val bests = arrayOf(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)
var tempSum = 0
for (index in input.indices) {
when {
input[index] == "" -> {
bests[0] = max(tempSum, bests[0])
bests.sort()
tempSum=0
}
index == input.size - 1 -> {
bests[0] = max(tempSum+input[index].toInt(), bests[0])
}
else -> {
tempSum+=input[index].toInt()
}
}
}
return bests.sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8 | 1,367 | Advent-of-code | Apache License 2.0 |
src/main/kotlin/Day05.kt | SimonMarquis | 724,825,757 | false | {"Kotlin": 30983} | class Day05(private val input: List<String>) {
private val seeds = input.first().substringAfter(":").trim().split(" ").map(String::toLong).also(::println)
private val almanac = input.asSequence().drop(2).foldInPlace(mutableListOf<Conversion>()) { line: String ->
when (line.firstOrNull()) {
in 'a'..'z' -> add(line.toConversion())
in '0'..'9' -> last().instructions.add(line.toInstruction())
}
}.onEach(::println)
private fun String.toConversion() = split("-to-", " ").let { (src, dst) -> Conversion(src, dst) }
private fun String.toInstruction() = split(" ").map { it.toLong() }.let { (src, dst, length) -> Instruction(dst, src, length) }
private data class Conversion(val src: String, val dst: String, val instructions: MutableList<Instruction> = mutableListOf()) {
operator fun contains(number: Long) = instructions.any { number in it }
}
private data class Instruction(val src: Long, val dst: Long, val length: Long) {
operator fun contains(number: Long) = number in (src..<src + length)
fun map(number: Long): Long = number + dst - src
}
fun part1(): Long = seeds.minOf { seed ->
almanac.fold(seed) { acc, conversion ->
conversion.instructions.singleOrNull { acc in it }?.map(acc) ?: acc
}
}
fun part2(): Long = TODO()
}
| 0 | Kotlin | 0 | 1 | 043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e | 1,373 | advent-of-code-2023 | MIT License |
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day19/Day19.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2023.calendar.day19
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.readStringFile
import java.util.*
import javax.inject.Inject
import kotlin.math.max
import kotlin.math.min
class Day19 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(fileName: String): Int {
val parts: MutableList<Part> = mutableListOf()
val workflows: MutableList<Workflow> = mutableListOf()
val acceptedParts = mutableListOf<Part>()
val rejectedParts = mutableListOf<Part>()
readStringFile(fileName).forEach { line ->
if (line.startsWith('{')) {
parsePart(line, parts)
} else if (line != "") {
parseWorkflow(line, workflows)
}
}
workflows.first { it.name == "in" }.queue.addAll(parts)
while (!workflows.all { it.queue.isEmpty() }) {
workflows.forEach { workflow ->
while (!workflow.queue.isEmpty()) {
val part = workflow.queue.removeFirst()
workflow.processPart(part, workflows, acceptedParts, rejectedParts)
}
}
}
return acceptedParts.sumOf { it.total }
}
fun partTwo(fileName: String): Long {
val workflows = readStringFile(fileName)
.filter{ !it.startsWith('{')}
.filter { it!="" }
.plus(listOf("A{}", "R{}"))
.map(::parseWorkflow2)
.associateBy { it.name }
// println(workflows)
return countAccepted(workflows, workflows["in"]!!)
}
fun parseWorkflow(line: String, workflows: MutableList<Workflow>) {
val name = line.substringBefore('{')
val stepConfig = line.substringAfter('{').trim('}')
val steps = mutableListOf<Step>()
stepConfig.split(',')
.forEach {
// println(it)
steps.add(
if (it.contains(':')) {
ConditionalStep(
it[0],
it[1],
it.substring(2).substringBefore(':').toInt(),
it.substringAfter(':')
)
} else {
UnconditionalStep(it)
}
)
}
workflows.add(Workflow(name, steps))
}
fun parsePart(line: String, parts: MutableList<Part>) {
val attributes = line.trim('{', '}').split(',')
val x = attributes.filter { it.startsWith('x') }.first().substringAfter('=').toInt()
val m = attributes.filter { it.startsWith('m') }.first().substringAfter('=').toInt()
val a = attributes.filter { it.startsWith('a') }.first().substringAfter('=').toInt()
val s = attributes.filter { it.startsWith('s') }.first().substringAfter('=').toInt()
parts.add(Part(x, m, a, s))
}
data class Part(val x: Int, val m: Int, val a: Int, val s: Int) {
val total: Int = x + m + a + s
}
private fun countAccepted(
workflows: Map<String, Workflow2>,
workflow: Workflow2,
acceptedPart: AcceptedPart = AcceptedPart(),
): Long {
return when (workflow.name) {
"A" -> acceptedPart.allowedValues()
"R" -> 0
else -> {
var remainingPart = acceptedPart
return workflow.rules.sumOf { rule ->
when (rule) {
is GreaterThan -> {
val limitedPart = remainingPart.adjustGreaterThan(rule.attribute, rule.value + 1)
remainingPart = remainingPart.adjustLessThan(rule.attribute, rule.value)
countAccepted(workflows, workflows[rule.ifTrue]!!, limitedPart)
}
is LessThan -> {
val limitedXmas = remainingPart.adjustLessThan(rule.attribute, rule.value - 1)
remainingPart = remainingPart.adjustGreaterThan(rule.attribute, rule.value)
countAccepted(workflows, workflows[rule.ifTrue]!!, limitedXmas)
}
is UnconditionalRule -> {
countAccepted(workflows, workflows[rule.result]!!, remainingPart)
}
else -> throw RuntimeException("Invalid rule")
}
}
}
}
}
data class Workflow2(val name: String, val rules: List<Rule>)
data class Workflow(val name: String, val steps: List<Step>, val queue: Deque<Part> = ArrayDeque()) {
fun processPart(
part: Part,
workflows: MutableList<Workflow>,
acceptedParts: MutableList<Part>,
rejectedParts: MutableList<Part>
) {
outer@ for (step in steps) {
if (step is UnconditionalStep) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
} else if (step is ConditionalStep) {
when (step.attribute) {
'x' -> {
when (step.condition) {
'<' -> if (part.x < step.value) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
}
'>' -> if (part.x > step.value) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
}
}
}
'm' -> {
when (step.condition) {
'<' -> if (part.m < step.value) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
}
'>' -> if (part.m > step.value) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
}
}
}
'a' -> {
when (step.condition) {
'<' -> if (part.a < step.value) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
}
'>' -> if (part.a > step.value) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
}
}
}
's' -> {
when (step.condition) {
'<' -> if (part.s < step.value) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
}
'>' -> if (part.s > step.value) {
processStep(part, step.action, workflows, acceptedParts, rejectedParts)
break@outer
}
}
}
}
}
}
}
private fun processStep(
part: Part,
action: String,
workflows: MutableList<Workflow>,
acceptedParts: MutableList<Part>,
rejectedParts: MutableList<Part>
) {
if (action == "A")
acceptedParts.add(part)
else if (action == "R")
rejectedParts.add(part)
else workflows.first { it.name == action }.queue.add(part)
}
}
private fun parseWorkflow2(line: String): Workflow2 {
// ex{x>10:one,m<20:two,a>30:R,A}
val name = line.substringBefore('{')
val rules = line.substringAfter('{')
.trim('}')
.split(",")
.map { ruleString ->
if (ruleString.contains(':')) {
val (check, ifTrue) = ruleString.split(':')
when (val operation = check[1]) {
'>' -> GreaterThan(check[0], check.substring(2).toInt(), ifTrue)
'<' -> LessThan(check[0], check.substring(2).toInt(), ifTrue)
else -> throw IllegalArgumentException("Unknown operation $operation")
}
} else {
UnconditionalRule(ruleString)
}
}
return Workflow2(name, rules)
}
open class Step
data class ConditionalStep(val attribute: Char, val condition: Char, val value: Int, val action: String) : Step()
data class UnconditionalStep(val action: String) : Step()
open class Rule
class GreaterThan(val attribute: Char, val value: Int, val ifTrue: String) : Rule()
class LessThan(val attribute: Char, val value: Int, val ifTrue: String) : Rule()
class UnconditionalRule(val result: String) : Rule()
data class AcceptedPart(
val xMin: Int = 1, val xMax: Int = 4000,
val mMin: Int = 1, val mMax: Int = 4000,
val aMin: Int = 1, val aMax: Int = 4000,
val sMin: Int = 1, val sMax: Int = 4000,
) {
fun adjustGreaterThan(attribute: Char, value: Int): AcceptedPart {
return when (attribute) {
'x' -> copy(xMin = max(xMin, value))
'm' -> copy(mMin = max(mMin, value))
'a' -> copy(aMin = max(aMin, value))
's' -> copy(sMin = max(sMin, value))
else -> throw IllegalArgumentException("Unknown attribute: $attribute")
}
}
fun adjustLessThan(attribute: Char, value: Int): AcceptedPart {
return when (attribute) {
'x' -> copy(xMax = min(xMax, value))
'm' -> copy(mMax = min(mMax, value))
'a' -> copy(aMax = min(aMax, value))
's' -> copy(sMax = min(sMax, value))
else -> throw IllegalArgumentException("Unknown attribute: $attribute")
}
}
fun allowedValues(): Long {
return (xMin..xMax).count().toLong() *
(mMin..mMax).count().toLong() *
(aMin..aMax).count().toLong() *
(sMin..sMax).count().toLong()
}
}
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 9,242 | advent-of-code | MIT License |
Collections/GroupBy/src/TaskExtenstionGroupBy.kt | Rosietesting | 373,564,502 | false | {"HTML": 178715, "JavaScript": 147056, "Kotlin": 113135, "CSS": 105840} | fun main () {
/*
Example 1 : groupBy() takes a lambda function and returns a Map
In this map, each key is the lambda result and the corresponding value
is the List of elements on which this result is returned
*/
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.groupBy { it.first().toUpperCase() })
/*
Example 2 Group by with transformation
*/
println(numbers.groupBy(keySelector = { it.first() },
valueTransform = { it.toUpperCase() }))
/*
Example 3 Grouping by : Group elements and then apply an operation to all groups
at one time
*/
val number = listOf("one", "two", "three", "four", "five", "six")
println(number.groupingBy { it.first() }.eachCount())
val words = listOf("bezkoder", "zkoder", "kotlin", "programmingz", "bezcoder", "professional", "zcoder")
val byLength = words.groupBy { it.length }
val byLength2 = words.groupBy { it.length }
.filter {(key, value) -> key == 8 }
val city1 = City ("Bogota")
val city2 = City ("London")
val product1 = Product("Bread", 10.50)
val product2 = Product("Rice", 4.23)
val product3 = Product("potatoes", 1.23)
val product4 = Product("brocoli", 12.60)
val order1 = Order(listOf(product1,product3, product4), true)
val order2 = Order(listOf(product2), true)
val order3 = Order(listOf(product1, product2), true)
val order4 = Order(listOf(product3, product4), true)
val customer1 = Customer("<NAME>", city1, listOf(order1, order2, order3))
val customer2 = Customer("<NAME>", city2, listOf(order1))
val customer3 = Customer("Santi", city2, listOf(order1, order4))
val shop = Shop("Roxipan", listOf(customer2,customer3, customer1))
shop.groupCustomersByAGivenCity(city1)
}
fun Shop.groupCustomersByAGivenCity(city : City): Map<City, List<Customer>> =
this.customers.groupBy { it.city }
.filter { (key,value) -> key == city}
| 0 | HTML | 0 | 0 | b0aa518d220bb43c9398dacc8a6d9b6c602912d5 | 2,008 | KotlinKoans | MIT License |
src/main/kotlin/Day03.kt | alex859 | 573,174,372 | false | {"Kotlin": 80552} | fun main() {
val testInput = readInput("Day03_test.txt")
check(testInput.itemsPriority() == 157)
check(testInput.badgesPriority() == 70)
val input = readInput("Day03.txt")
println(input.itemsPriority())
println(input.badgesPriority())
}
fun String.itemsPriority() = lines().map { it.itemInCommon() }.sumOf { it.priority }
internal fun String.itemInCommon(): Char {
val (compartment1, compartment2) = compartments
val intersect = compartment1.toSet().intersect(compartment2.toSet())
return intersect.first()
}
internal val Char.priority: Int
get() = if (this.isLowerCase()) code - 'a'.code + 1 else code - 'A'.code + 27
internal val String.compartments: Pair<String, String>
get() {
val half = length / 2
return substring(0 until half) to substring(half until length)
}
fun String.badgesPriority(): Int = lines().groups.map { it.badge }.sumOf { it.priority }
internal val List<String>.groups: Iterable<Iterable<String>>
get() = this.chunked(3)
internal val Iterable<String>.badge: Char
get() {
val (first, second, third) = map { it.toSet() }
return first.intersect(second).intersect(third).first()
} | 0 | Kotlin | 0 | 0 | fbbd1543b5c5d57885e620ede296b9103477f61d | 1,198 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/leetcode_problems/medium/K-diffIinArray.kt | MhmoudAlim | 451,633,139 | false | {"Kotlin": 31257, "Java": 586} | package leetcode_problems.medium
import kotlin.math.abs
/*
https://leetcode.com/problems/k-diff-pairs-in-an-array/
* Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
0 <= i, j < nums.length
i != j
|nums[i] - nums[j]| == k
Notice that |val| denotes the absolute value of val.
Example 1:
Input: nums = [3,1,4,1,5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input: nums = [1,2,3,4,5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: nums = [1,3,1,5,4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
1, 3, 1, 5, 4
p1,p2,..,..,..
* */
fun findPairs(nums: IntArray, k: Int): Int {
if (k < 0) return 0
val result = mutableSetOf<Pair<Int, Int>>()
val visited = mutableSetOf<Int>()
for (num in nums) {
if (visited.contains(num - k)) {
result.add(Pair(num - k, num))
}
if (visited.contains(num + k)) {
result.add(Pair(num, num + k))
}
visited += num
}
return result.size
}
fun main() {
val result = findPairs(intArrayOf(1,3,1,5,4), 0)
println(result)
} | 0 | Kotlin | 0 | 0 | 31f0b84ebb6e3947e971285c8c641173c2a60b68 | 1,449 | Coding-challanges | MIT License |
src/main/kotlin/io/steinh/aoc/day05/Almanac.kt | daincredibleholg | 726,426,347 | false | {"Kotlin": 25396} | package io.steinh.aoc.day05
class Almanac(private val sourceData: Input) {
fun lowestLocation(): Long {
val list = mutableListOf<Long>()
sourceData.seeds.forEach {
val soil = getSoilForSeed(it)
val fertilizer = getFertilizerForSoil(soil)
val water = getWaterForFertilizer(fertilizer)
val light = getLightForWater(water)
val temperature = getTemperatureForLight(light)
val humidity = getHumidityForTemperature(temperature)
list.add(getLocationForHumidity(humidity))
}
list.sort()
return list.first()
}
fun lowestLocationForSeedRanges(): Long {
var lowestLocationFound = 0L
sourceData.seeds.chunked(2).forEach { seedRange ->
for(it in seedRange.first()..(seedRange.first() + seedRange.last())) {
val soil = getSoilForSeed(it)
val fertilizer = getFertilizerForSoil(soil)
val water = getWaterForFertilizer(fertilizer)
val light = getLightForWater(water)
val temperature = getTemperatureForLight(light)
val humidity = getHumidityForTemperature(temperature)
val location = getLocationForHumidity(humidity)
lowestLocationFound =
if (lowestLocationFound == 0L || location < lowestLocationFound)
location
else lowestLocationFound
}
}
return lowestLocationFound
}
private fun getSoilForSeed(seed: Long) =
filterFromMapping(seed, sourceData.seedToSoilMappings)
private fun getFertilizerForSoil(soil: Long) =
filterFromMapping(soil, sourceData.soilToFertilizerMappings)
private fun getWaterForFertilizer(fertilizer: Long) =
filterFromMapping(fertilizer, sourceData.fertilizerToWaterMappings)
private fun getLightForWater(water: Long) =
filterFromMapping(water, sourceData.waterToLightMappings)
private fun getTemperatureForLight(light: Long) =
filterFromMapping(light, sourceData.lightToTemperatureMappings)
private fun getHumidityForTemperature(temperature: Long) =
filterFromMapping(temperature, sourceData.temperatureToHumidityMappings)
private fun getLocationForHumidity(humidity: Long) =
filterFromMapping(humidity, sourceData.humidityToLocationMappings)
private fun filterFromMapping(id: Long, mappings: List<Mapping>): Long =
mappings
.filter {
it.sourceRangeStart.contains(id)
}.map {
it.destinationRangeStart.first + (id - it.sourceRangeStart.first)
}.ifEmpty {
listOf(id)
}.first()
}
fun main() {
val rawInput = {}.javaClass.classLoader?.getResource("day05/input.txt")?.readText()!!
val inputProcessor = AlmanacInputProcessor()
val input = inputProcessor.transform(rawInput)
val instance = Almanac(input)
val resultOne = instance.lowestLocation()
println("Result for day 05, part I: $resultOne")
val resultTwo = instance.lowestLocationForSeedRanges()
println("Result for day 05, part II: $resultTwo")
}
| 0 | Kotlin | 0 | 0 | 4aa7c684d0e337c257ae55a95b80f1cf388972a9 | 3,239 | AdventOfCode2023 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumSplits.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
/**
* 1525. Number of Good Ways to Split a String
* @see <a href="https://leetcode.com/problems/number-of-good-ways-to-split-a-string/">Source</a>
*/
fun interface NumSplits {
operator fun invoke(str: String): Int
}
class NumSplitsSplitPointer : NumSplits {
override operator fun invoke(str: String): Int {
val l = IntArray(ALPHABET_LETTERS_COUNT)
val r = IntArray(ALPHABET_LETTERS_COUNT)
var dL = 0
var dR = 0
var res = 0
val s = str.toCharArray()
for (ch in s) dR += if (++r[ch.code - 'a'.code] == 1) 1 else 0
for (i in s.indices) {
dL += if (++l[s[i] - 'a'] == 1) 1 else 0
dR -= if (--r[s[i] - 'a'] == 0) 1 else 0
res += if (dL == dR) 1 else 0
}
return res
}
}
class NumSplitsMap : NumSplits {
override operator fun invoke(str: String): Int {
val left: HashMap<Char, Int> = HashMap()
val right: HashMap<Char, Int> = HashMap()
// put all the characters in the right hashmap and keep track of the count
for (i in str.indices) {
right[str[i]] = right.getOrDefault(str[i], 0) + 1
}
// count the number of times the right is equal to the left, which is the result
var count = 0
// loop through all the characters and add them to the left and remove them from the right
for (element in str) {
val curr: Char = element
left[curr] = left.getOrDefault(curr, 0) + 1
// I put a getOrDefault() here instead of just get() as a "just in case"
// but the "right" should have all the characters
// since we added all characters at the beginning
// adding an if statement increases runtime but getOrDefault() did not
right[curr] = right.getOrDefault(curr, 0) - 1
// if the count is equal to zero then remove the key/value pair
if (right[curr]!! <= 0) {
right.remove(curr)
}
// if the two hashmaps are equal in size,
// which means they have the same amount of keys,
// which means they have the same amount of distinct characters
// increment the count for the result
if (left.size == right.size) {
count++
}
}
return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,082 | kotlab | Apache License 2.0 |
src/day_2.kt | gardnerdickson | 152,621,962 | false | null | import java.io.File
import kotlin.streams.toList
fun main(args: Array<String>) {
val input = "res/day_2_input.txt"
val answer1 = Day2.part1(input)
println("Part 1: $answer1")
val answer2 = Day2.part2(input)
println("Part 2: $answer2")
}
object Day2 {
fun part1(input: String): Int {
val reader = File(input).bufferedReader()
val amounts = reader.lines()
.map { parsePresent(it) }
.map { it.surfaceArea() + it.slack() }
.toList()
return amounts.sum()
}
fun part2(input: String): Int {
val reader = File(input).bufferedReader()
val amounts = reader.lines()
.map { parsePresent(it) }
.map { it.ribbon() + it.bow() }
.toList()
return amounts.sum()
}
private fun parsePresent(dimensions: String): Present {
val components = dimensions.split("x")
return Present(components[0].toInt(), components[1].toInt(), components[2].toInt())
}
}
data class Present(val width: Int, val height: Int, val length: Int) {
fun surfaceArea(): Int {
return 2 * length * width + 2 * width * height + 2 * height * length
}
fun slack(): Int {
val sorted = listOf(width, height, length).sorted()
return sorted[0] * sorted[1]
}
fun ribbon(): Int {
val sorted = listOf(width, height, length).sorted()
return sorted[0] * 2 + sorted[1] * 2
}
fun bow(): Int {
return width * height * length
}
}
| 0 | Kotlin | 0 | 0 | 4a23ab367a87cae5771c3c8d841303b984474547 | 1,557 | advent-of-code-2015 | MIT License |
src/main/kotlin/day7/LuggageRules.kt | lukasz-marek | 317,632,409 | false | {"Kotlin": 172913} | package day7
data class Bag(val color: String)
data class Rule(val describedBag: Bag, val containedBags: Map<Bag, Int>)
private val nonEmptyRulePattern =
Regex("^(\\w+ \\w+) bags contain (.+)\\.")
private val emptyRulePattern = Regex("^(\\w+ \\w+) bags contain no other bags.")
fun parseRule(line: String): Rule =
when {
emptyRulePattern.matches(line) -> {
val (color, _) = emptyRulePattern.matchEntire(line)!!.destructured
Rule(Bag(color), emptyMap())
}
nonEmptyRulePattern.matches(line) -> {
val (color, otherBags) = nonEmptyRulePattern.matchEntire(line)!!.destructured
val containedBags = otherBags.split(",").map { it.trim() }.map { parseContainedBag(it) }.toMap()
Rule(Bag(color), containedBags)
}
else -> throw IllegalArgumentException("'$line' cannot be parsed!")
}
private val singleBagPattern = Regex("^(\\d+) (\\w+ \\w+) bags?$")
private fun parseContainedBag(containedBag: String): Pair<Bag, Int> {
val matched = singleBagPattern.matchEntire(containedBag)!!
val (quantity, color) = matched.destructured
return Bag(color) to quantity.toInt()
}
interface InferenceRunner {
fun inferPossibleContainingBags(bag: Bag): Set<Bag>
}
class InferenceRunnerImpl(private val rules: List<Rule>) : InferenceRunner {
override fun inferPossibleContainingBags(bag: Bag): Set<Bag> = runInference(setOf(bag), emptySet()) - setOf(bag)
private tailrec fun runInference(searchedBags: Set<Bag>, foundBags: Set<Bag>): Set<Bag> =
if (searchedBags.isEmpty()) {
foundBags
} else {
val bagsContainingSearchedBags = rules
.filter { it.containedBags.keys.intersect(searchedBags).isNotEmpty() }
.map { it.describedBag }
.toSet()
runInference(bagsContainingSearchedBags, foundBags + searchedBags)
}
}
interface BagsCounter {
fun countBagsRequiredBy(bag: Bag): Int
}
class BagsCounterImpl(rules: List<Rule>) : BagsCounter {
private val fastRules = rules.map { it.describedBag to it.containedBags }.toMap()
override fun countBagsRequiredBy(bag: Bag): Int = countTotalBags(bag) - 1
private fun countTotalBags(bag: Bag): Int {
val requiredBags = fastRules[bag]!!
return requiredBags.toList()
.fold(1) { acc, pair -> acc + pair.second * countTotalBags(pair.first) }
}
} | 0 | Kotlin | 0 | 0 | a16e95841e9b8ff9156b54e74ace9ccf33e6f2a6 | 2,446 | aoc2020 | MIT License |
src/main/kotlin/08_Registers.kt | barta3 | 112,792,199 | false | null | class Parser {
fun parse(filename: String): ArrayList<Instruction> {
val reader = Parser::class.java.getResource(filename).openStream().bufferedReader()
val instructions = ArrayList<Instruction>()
reader.forEachLine { l ->
val parts = l.split(" ")
if (parts.size != 7) throw IllegalArgumentException("invalid line: $l")
val reg = parts[0]
val op = Operation.valueOf(parts[1].toUpperCase())
val amount = Integer.parseInt(parts[2])
val condReg = parts[4]
val condCom = Comp.from(parts[5])
val condValue = Integer.parseInt(parts[6])
val condition = Condition(condReg, condCom, condValue)
val instruction = Instruction(reg, op, amount, condition)
instructions.add(instruction)
}
return instructions
}
}
data class Instruction(val reg: String,
val operation: Operation,
val amount: Int,
val condition: Condition)
enum class Operation { INC, DEC }
data class Condition(val reg: String, val comp: Comp, val value: Int) {
fun eval(regs: HashMap<String, Int>): Boolean {
if (!regs.containsKey(reg)) {
regs.put(reg, 0)
}
val regValue = regs.get(reg)!!
val contidtion = when (comp) {
Comp.GR -> regValue > value
Comp.GREQ -> regValue >= value
Comp.EQ -> regValue == value
Comp.SMEQ -> regValue <= value
Comp.SM -> regValue < value
Comp.NEQ -> regValue != value
}
return contidtion
}
}
enum class Comp(val s: String) {
GR(">"), GREQ(">="), EQ("=="), SMEQ("<="), SM("<"), NEQ("!=");
companion object {
fun from(findBy: String): Comp = Comp.values().first { it.s == findBy }
}
}
fun run(instructions: ArrayList<Instruction>): HashMap<String, Int> {
var max = 0
val regs = HashMap<String, Int>()
instructions.forEach { i ->
if (i.condition.eval(regs)) {
val amountAbs = if(Operation.DEC == i.operation) (-1) * i.amount else i.amount
regs.merge(i.reg, amountAbs, Math::addExact)
println("Match $i newVals: $regs")
max = Math.max(max, regs.get(i.reg)!!)
} else {
println("No match $i")
}
}
println("Overall Max: $max")
return regs
}
fun main(args: Array<String>) {
// val instructions = Parser().parse("08_input_example.txt")
val instructions = Parser().parse("08_input_part1.txt")
instructions.forEach { l -> println(l) }
val registers = run(instructions)
println(registers)
val maxValue = registers.values.max()
println("Final Max is $maxValue")
}
| 0 | Kotlin | 0 | 0 | 51ba74dc7b922ac11f202cece8802d23011f34f1 | 2,804 | AdventOfCode2017 | MIT License |
src/Day05.kt | tstellfe | 575,291,176 | false | {"Kotlin": 8536} | fun main() {
fun List<String>.createStacks(separator: Int): MutableMap<Int, MutableList<String>> {
val stacks = mutableMapOf<Int, MutableList<String>>()
for (i in separator - 2 downTo 0) {
this[i].let { line ->
var key = 1
line.windowed(size = 3, step = 4, partialWindows = false) { stackValue ->
if (stackValue.isNotBlank()) {
stacks.getOrPut(key) { mutableListOf() }.add(stackValue[1].toString())
}
key++
}
}
}
return stacks
}
fun MutableMap<Int, MutableList<String>>.buildTopString(): String =
this.mapValues { it.value.last() }.values.joinToString("")
fun MutableList<String>.removeLast(n: Int) {
for (i in 1..n) {
this.removeLast()
}
}
fun part1(input: List<String>): String {
val separator = input.indexOf("")
val stacks = input.createStacks(separator)
for (i in separator + 1 until input.size) {
val split = input[i].split(" ")
val amount = split[1].toInt()
val from = stacks[split[3].toInt()]!!
val to = stacks[split[5].toInt()]!!
val stackValues = from.drop(from.size - amount)
to.addAll(stackValues.asReversed())
from.removeLast(amount)
}
return stacks.buildTopString()
}
fun part2(input: List<String>): String {
val separator = input.indexOf("")
val stacks = input.createStacks(separator)
for (i in separator + 1 until input.size) {
val split = input[i].split(" ")
val amount = split[1].toInt()
val from = stacks[split[3].toInt()]!!
val to = stacks[split[5].toInt()]!!
val stackValues = from.drop(from.size - amount)
to.addAll(stackValues)
from.removeLast(amount)
}
return stacks.buildTopString()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val input = readInput("Day05")
println(part2(testInput))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e100ba705c8e2b83646b172d6407475c27f02eff | 1,975 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/days/Day24.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
class Day24 : Day(24) {
override fun partOne(): Any {
val colNum = inputList.first().length - 2
val rowNum = inputList.size - 2
val blizzards = parseBlizzards()
val start = Point(-1, 0)
val fin = Point(rowNum, colNum - 1)
return route(start, fin, 0, blizzards, colNum, rowNum)
}
override fun partTwo(): Any {
val colNum = inputList.first().length - 2
val rowNum = inputList.size - 2
val blizzards = parseBlizzards()
val start = Point(-1, 0)
val fin = Point(rowNum, colNum - 1)
val thereTime = route(start, fin, 0, blizzards, colNum, rowNum)
val backTime = route(fin, start, thereTime, blizzards, colNum, rowNum)
return route(start, fin, backTime, blizzards, colNum, rowNum)
}
private fun route(
start: Point,
fin: Point,
startTime: Int,
blizzards: List<(Int) -> Point>,
colNum: Int,
rowNum: Int
): Int {
return generateSequence(setOf(State(start, startTime))) { states ->
val time = states.first().time
states.flatMap { state ->
listOf(
Point(0, 0),
Point(1, 0), Point(0, 1), Point(-1, 0), Point(0, -1)
).mapNotNull {
val next = state.point + it
if ((next == fin || state.point == next || (next.col in 0 until colNum && next.row in 0 until rowNum)) &&
blizzards.none { it(time + 1) == next }
) next
else null
}
}.toSet().map { State(it, time + 1) }.toSet()
}.takeWhile { it.none { it.point == fin } }.count() + startTime
}
private fun parseBlizzards(): List<(Int) -> Point> {
val colNum = inputList.first().length - 2
val rowNum = inputList.size - 2
return inputList.flatMapIndexed { row, rowChars ->
rowChars.mapIndexedNotNull { col, char ->
when (char) {
'>' -> { time: Int -> Point(row - 1, (col - 1 + time) % colNum) }
'<' -> { time: Int -> Point(row - 1, (col - 1 + time * (colNum - 1)) % colNum) }
'v' -> { time: Int -> Point((row - 1 + time) % rowNum, col - 1) }
'^' -> { time: Int -> Point((row - 1 + time * (rowNum - 1)) % rowNum, col - 1) }
else -> null
}
}
}
}
// private fun printPath(rowNum: Int, colNum: Int, blizzards: List<(Int) -> Point>, finState: State) {
// val start = Point(-1, 0)
// val fin = Point(rowNum, colNum - 1)
// val path = generateSequence(finState) { it.prev }.takeWhile { true }.map { it.point }.toList().reversed()
// for ((step, point) in path.withIndex()) {
// for (row in -1..rowNum) {
// for (col in -1..colNum) {
// if (Point(row, col) == point) print('E')
// else if (Point(row, col) == start || Point(row, col) == fin) print('.')
// else if (row !in 0 until rowNum || col !in 0 until colNum) print("#")
// else {
// print(blizzards.count { it(step) == Point(row, col) })
// }
// }
// println()
// }
// }
// }
data class Point(val row: Int, val col: Int) {
operator fun plus(other: Point) = Point(row + other.row, col + other.col)
}
data class State(val point: Point, val time: Int) {
// val prev: State?
}
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 3,660 | aoc-2022 | Creative Commons Zero v1.0 Universal |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.