path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/days/Day15.kt | jgrgt | 433,952,606 | false | {"Kotlin": 113705} | package days
import util.MutableMatrix
import util.Point
import kotlin.math.abs
class Day15 : Day(15) {
override fun runPartOne(lines: List<String>): Any {
val matrix = MutableMatrix.fromSingleDigits(lines) { c -> c.digitToInt() }
val start = Point(0, 0)
val optimal = aStar(matrix, start, matrix.max())
return optimal.cost
}
override fun runPartTwo(lines: List<String>): Any {
val matrix = MutableMatrix.fromSingleDigits(lines) { c -> c.digitToInt() }
val megaMatrix = toMegaMatrix(matrix)
val start = Point(0, 0)
return aStar(megaMatrix, start, megaMatrix.max()).cost
}
fun toMegaMatrix(matrix: MutableMatrix<Int>): MutableMatrix<Int> {
val additions = listOf(
listOf(0, 1, 2, 3, 4),
listOf(1, 2, 3, 4, 5),
listOf(2, 3, 4, 5, 6),
listOf(3, 4, 5, 6, 7),
listOf(4, 5, 6, 7, 8),
)
val subMatrices = additions.map { row ->
row.map { incr -> matrix.map { max9(it + incr) } }.map { it.items }
}
val longRowLists = subMatrices.flatMap { subMatrixRow ->
toLongRows(subMatrixRow)
}
val megaMatrix = MutableMatrix(longRowLists.map {
it.toMutableList()
}.toMutableList())
return megaMatrix
}
fun toLongRows(subMatrixRow: List<List<List<Int>>>): List<List<Int>> {
return (0 until subMatrixRow[0].size).map {
val r = subMatrixRow.map { sm -> sm[it].toList() }
r.flatten()
}
}
private fun max9(n: Int): Int {
return if (n > 9) {
n - 9
} else {
n
}
}
/**
* Estimated cost to reach end from p
* ....p...
* ....9...
* ....9...
* ....999e
*/
fun heuristicCost(p: Point, end: Point): Int {
val xDistance = abs(p.x - end.x)
val yDistance = abs(p.y - end.y)
return xDistance * 1 + yDistance * 1 - 1 // 1 less for the corner/end itself
}
fun aStar(matrix: MutableMatrix<Int>, start: Point, end: Point): Path {
// Basing myself on Wikipedia, because it's been a while...
// https://en.wikipedia.org/wiki/A*_search_algorithm
val openSet = mutableSetOf<Point>(start)
val cameFrom = mutableMapOf<Point, Point>()
val gScore = mutableMapOf<Point, Int>().withDefault { Int.MAX_VALUE }
gScore[start] = 0
val fScore = mutableMapOf<Point, Int>().withDefault { Int.MAX_VALUE }
fScore[start] = heuristicCost(start, end)
while (openSet.isNotEmpty()) {
val current = openSet.minByOrNull { fScore.getValue(it) }!!
if (current == end) {
val path = reconstructPath(cameFrom, current)
matrix.print(hightlight = { p -> path.contains(p) })
return Path(path, gScore[end]!!)
}
// matrix.print(hightlight = { p -> p == current})
openSet.remove(current)
val neighbours = current.cross().filter { matrix.contains(it) }
neighbours.forEach { neighbour ->
val tentativeGScore = gScore[current]!! + matrix.get(neighbour)
if (tentativeGScore < gScore.getValue(neighbour)) {
cameFrom[neighbour] = current
gScore[neighbour] = tentativeGScore
fScore[neighbour] = tentativeGScore + heuristicCost(neighbour, end)
openSet.add(neighbour)
}
}
}
error("should not reach this...")
}
private fun reconstructPath(cameFrom: MutableMap<Point, Point>, end: Point): List<Point> {
val path = mutableListOf(end)
while (cameFrom.contains(path.last())) {
path.add(cameFrom[path.last()]!!)
}
return path.reversed()
}
data class Path(val points: List<Point>, val cost: Int)
}
| 0 | Kotlin | 0 | 0 | 6231e2092314ece3f993d5acf862965ba67db44f | 3,966 | aoc2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/_0072_EditDistance.kt | ryandyoon | 664,493,186 | false | null | // https://leetcode.com/problems/edit-distance
fun minDistance(word1: String, word2: String): Int {
return minDistance(word1, word2, 0, 0, Array(word1.length) { IntArray(word2.length) { -1 } })
}
private fun minDistance(word1: String, word2: String, index1: Int, index2: Int, memo: Array<IntArray>): Int {
if (word1.length == index1) {
return word2.length - index2
}
if (word2.length == index2) {
return word1.length - index1
}
if (memo[index1][index2] != -1) {
return memo[index1][index2]
}
memo[index1][index2] = if (word1[index1] == word2[index2]) {
minDistance(word1, word2, index1 + 1, index2 + 1, memo)
} else {
val insert = minDistance(word1, word2, index1, index2 + 1, memo)
val remove = minDistance(word1, word2, index1 + 1, index2, memo)
val replace = minDistance(word1, word2, index1 + 1, index2 + 1, memo)
1 + minOf(insert, remove, replace)
}
return memo[index1][index2]
}
| 0 | Kotlin | 0 | 0 | 7f75078ddeb22983b2521d8ac80f5973f58fd123 | 996 | leetcode-kotlin | MIT License |
src/chapter4/section4/ex31_AllPairsShortestPathsOnALine.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter4.section4
/**
* 线图中任意顶点对之间的最短路径
* 给定一幅加权线图(无向连通图,处理两个端点度数为1之外所有顶点的度数为2),
* 给出一个算法在线性时间内对图进行预处理并在常数时间内返回任意两个顶点之间的最短路径。
*
* 解:以一个端点为起点,遍历加权线图,计算每个顶点到起点的距离
* 顶点v到顶点w的距离为顶点w到起点的距离减去顶点v到起点的距离
*/
class LineGraph(val V: Int) {
init {
// 线图至少有两个端点
require(V > 1)
}
// 两个点之间的权重默认为0,V个顶点有V-1条边
private val edges = DoubleArray(V - 1)
fun setWeight(startVertex: Int, weight: Double) {
require(startVertex in 0 until V - 1)
edges[startVertex] = weight
}
fun getWeight(startVertex: Int): Double {
require(startVertex in 0 until V - 1)
return edges[startVertex]
}
}
class LineGraphSP(graph: LineGraph) {
private val dist = DoubleArray(graph.V)
init {
dist[0] = 0.0
for (v in 0 until graph.V - 1) {
dist[v + 1] = dist[v] + graph.getWeight(v)
}
}
fun dist(v: Int, w: Int): Double {
return dist[w] - dist[v]
}
}
fun main() {
val graph = LineGraph(5)
graph.setWeight(0, 1.0)
graph.setWeight(1, 2.0)
graph.setWeight(2, -1.0)
graph.setWeight(3, 3.0)
val sp = LineGraphSP(graph)
for (v in 0 until graph.V) {
for (w in v until graph.V) {
println("v=$v w=$w weight=${sp.dist(v, w)}")
}
}
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,654 | Algorithms-4th-Edition-in-Kotlin | MIT License |
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/PalindromicNew.kt | ahuamana | 627,986,788 | false | null | package com.lukaslechner.coroutineusecasesonandroid.playground.challenges
//Have the function StringChallenge(str) take the str parameter being passed and determine if it is possible to create a palindromic string of minimum length 3 characters by removing 1 or 2 characters
//For example: if str is "abjchba" then you can remove the characters jc to produce "abhba" which is a palindrome.
//For this example your program should return the two characters that were removed with no delimiter and in the order they appear in the string, so jc.
//If 1 or 2 characters cannot be removed to produce a palindrome, then return the string not possible.
//If the input string is already a palindrome, your program should return the string palindrome.
//The input will only contain lowercase alphabetic characters.
//Your program should always attempt to create the longest palindromic substring by removing 1 or 2 characters
// (see second sample test case as an example).
//The 2 characters you remove do not have to be adjacent in the string.
//Examples
//Input: "mmop"
//Output: not possible
//Input: "kjjjhjjj"
//Output: k
private fun stringChallenge(str: String): String {
if (str == str.reversed()) return "palindrome"
//min length 3 characters
if (str.length < 3) return "not possible"
str.indices.forEachIndexed { index, _ ->
//remove 1 character
val newStr = str.removeRange(index, index + 1)
//min length 3 characters
if (newStr.length < 3) return "not possible"
if (newStr == newStr.reversed()) return str[index].toString()
//remove 2 characters
}
//remove 2 characters (not adjacent)
str.indices.forEachIndexed { index, _ ->
val newStr = str.removeRange(index, index + 2)
if (newStr.length < 3) return "not possible"
if (newStr == newStr.reversed()) return str[index].toString() + str[index + 1].toString()
}
//If any of the above conditions are not met, return "not possible"
return "not possible"
}
//test StringChallenge
fun main () {
println(stringChallenge("abh"))
println(stringChallenge("abhba"))
println(stringChallenge("mmop"))
println(stringChallenge("kjjjhjjj"))
println(stringChallenge("abjchba"))
} | 0 | Kotlin | 0 | 0 | 931ce884b8c70355e38e007141aab58687ed1909 | 2,253 | KotlinCorutinesExpert | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2016/2016-07.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2016
import java.io.File
fun main() {
val input = File("src", "com.github.ferinagy.adventOfCode.aoc2015.com.github.ferinagy.adventOfCode.aoc2015.com.github.ferinagy.adventOfCode.aoc2015.com.github.ferinagy.adventOfCode.aoc2015.com.github.ferinagy.adventOfCode.aoc2015.com.github.ferinagy.adventOfCode.aoc2015.com.github.ferinagy.adventOfCode.aoc2015.input-2016-07.txt").readText()
println("Part1:")
println(part1(testInput1))
println(part1(input))
println()
println("Part2:")
println(part2(testInput1))
println(part2(input))
}
private fun part1(input: String) = input.lines().count { it.supportsV7Tls() }
private fun part2(input: String) = input.lines().count { it.supportsV7Ssl() }
private fun String.supportsV7Tls(): Boolean {
val (hyper, normal) = split('[')
.mapIndexed { index, s -> if (index == 0) listOf("", s) else s.split(']') }
.fold(emptyList<String>() to emptyList<String>()) { (l1, l2), (a1, a2) -> l1 + a1 to l2 + a2 }
return normal.any { it.hasAbba() } && hyper.none { it.hasAbba() }
}
private fun String.supportsV7Ssl(): Boolean {
val (hyper, normal) = split('[')
.mapIndexed { index, s -> if (index == 0) listOf("", s) else s.split(']') }
.fold(emptyList<String>() to emptyList<String>()) { (l1, l2), (a1, a2) -> l1 + a1 to l2 + a2 }
val abas = normal.flatMap { it.getAbas() }
return abas.any { aba -> hyper.any { aba.flipAba() in it } }
}
private fun String.hasAbba(): Boolean = (0..length - 4).any { isAbba(it) }
private fun String.isAbba(start: Int): Boolean =
get(start) != get(start + 1) && get(start + 1) == get(start + 2) && get(start) == get(start + 3)
private fun String.getAbas(): List<String> = (0..length - 3).filter { isAba(it) }.map { substring(it, it + 3) }
private fun String.isAba(start: Int): Boolean =
get(start) != get(start + 1) && get(start) == get(start + 2)
private fun String.flipAba() = get(1).toString() + get(0) + get(1)
private const val testInput1 = """abba[mnop]qrst
abcd[bddb]xyyx
aaaa[qwer]tyui
ioxxoj[asdfgh]zxcvbn"""
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,122 | advent-of-code | MIT License |
src/main/kotlin/befaster/solutions/Item.kt | CX-Checkout | 110,842,433 | false | null | package befaster.solutions
sealed abstract class Item(open val price: Price)
object A : Item(50)
object B : Item(30)
object C : Item(20)
object D : Item(15)
object E : Item(40)
object Invalid : Item(-1)
typealias Basket = List<Item>
typealias Price = Int
interface Deal {
val howManyYouNeedToBuy: Int
}
data class NAtPriceOf(val item: Item, override val howManyYouNeedToBuy: Int, val priceOf: Price): Deal {
fun reducedPrice(numberOfItems: Int): Price {
return (numberOfItems % howManyYouNeedToBuy) * item.price + (numberOfItems / howManyYouNeedToBuy) * priceOf
}
}
data class BuyItemGetItemFree(
val whatYouGetForFree: Item,
val whatYouNeedToBuy: Item,
override val howManyYouNeedToBuy: Int,
val howManyYouGetForFree: Int) : Deal {
fun reducedPrice(howManyYouHave: Int, howManyOfOther: Int): Price {
val numberOfDiscounts = howManyOfOther / howManyYouNeedToBuy
val result = ((howManyYouHave - numberOfDiscounts) * whatYouGetForFree.price)
return Math.max(0, result)
}
}
object NoDeal: Deal {
override val howManyYouNeedToBuy: Int = 1
}
val offers = mapOf(
A to listOf(NAtPriceOf(A, 3,130), NAtPriceOf(A, 5, 200)),
B to listOf(BuyItemGetItemFree(B, E, 2, 1), NAtPriceOf(B, 2, 45))
)
class Checkout(basket: Basket) {
companion object {
fun priceFor(items: String): Price = Checkout(Scanner().getBasketFor(items)).total
}
val total: Price = if(basket.contains(Invalid)) -1 else {
val groupedItems = basket.groupBy { it }
val priceForItems = groupedItems.map { group ->
val deals = offers[group.key] ?: listOf(NoDeal)
val reducedPrice = getPriceFor(group.key, group.value.size, deals, groupedItems)
reducedPrice.min()!!
}.sum()
priceForItems
}
fun getPriceFor(item: Item, numberOfItems: Int, deals: List<Deal>, group: Map<Item, List<Item>>): List<Int> {
fun go(list: List<Item>): List<Int> {
return when {
list.isEmpty() -> listOf(0)
else -> (listOf(numberOfItems) + deals.map { it.howManyYouNeedToBuy }).flatMap { howMany ->
deals.map {
when (it) {
is NAtPriceOf -> it.reducedPrice(howMany) + go(list.drop(howMany)).min()!!
is BuyItemGetItemFree -> it.reducedPrice(list.size, group[it.whatYouNeedToBuy].orEmpty().size) + go(list.drop(it.howManyYouNeedToBuy)).min()!!
else -> item.price * howMany + go(list.drop(howMany)).min()!!
}
}
}
}
}
return go(group[item].orEmpty())
}
}
class Scanner {
fun getBasketFor(itemsScanned: String): Basket = itemsScanned.map {
when (it) {
'A' -> A
'B' -> B
'C' -> C
'D' -> D
'E' -> E
else -> Invalid
}
}
} | 0 | Kotlin | 0 | 0 | 9209c4182bee28509835759be2762ba62fb3f92b | 3,018 | rvpk01 | Apache License 2.0 |
src/aoc2022/Day05.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import println
import readInput
import java.util.*
fun main() {
fun part1(input: List<String>): String {
var firstLine = true
var stacks: MutableList<LinkedList<Char>> = mutableListOf()
var stacksNum = 0
var lineIt = input.iterator()
var line = lineIt.next()
while (line.isNotBlank()) {
if ("""( (\d+)( )+)+""".toRegex().matches(line)) {
line = lineIt.next();
continue
}
// nx3 + n-1 = x -> nx4 = x + 1 -> n = (x+1)/4
if (firstLine) {
stacksNum = (line.length + 1) / 4
for (i in 0 until stacksNum) stacks.add(LinkedList<Char>())
firstLine = false
}
val elems = line.replace(" ", "[!]")
.replace(" ", "")
.replace("[", "")
.replace("]", "")
for (i in 0 until stacksNum) {
if (elems[i] != '!') {
stacks[i].addFirst(elems[i])
}
}
line = lineIt.next()
}
val regex = """move (\d+) from (\d+) to (\d+)""".toRegex()
while (lineIt.hasNext()) {
line = lineIt.next()
val matchResult = regex.find(line)
val (num, from, to) = matchResult!!.destructured
for (i in 0 until num.toInt()) {
stacks[to.toInt() - 1].add(stacks[from.toInt() - 1].pollLast())
}
}
val firstLetters = stacks.map { "" + it.pollLast() }
return firstLetters.reduce { acc, s -> acc + s }
}
fun part2(input: List<String>): String {
var firstLine = true
var stacks: MutableList<LinkedList<Char>> = mutableListOf()
var stacksNum = 0
var lineIt = input.iterator()
var line = lineIt.next()
while (line.isNotBlank()) {
if ("""( (\d+)( )+)+""".toRegex().matches(line)) {
line = lineIt.next();
continue
}
// nx3 + n-1 = x -> nx4 = x + 1 -> n = (x+1)/4
if (firstLine) {
stacksNum = (line.length + 1) / 4
for (i in 0 until stacksNum) stacks.add(LinkedList<Char>())
firstLine = false
}
val elems = line.replace(" ", "[!]")
.replace(" ", "")
.replace("[", "")
.replace("]", "")
for (i in 0 until stacksNum) {
if (elems[i] != '!') {
stacks[i].addFirst(elems[i])
}
}
line = lineIt.next()
}
val regex = """move (\d+) from (\d+) to (\d+)""".toRegex()
while (lineIt.hasNext()) {
line = lineIt.next()
val matchResult = regex.find(line)
val (num, from, to) = matchResult!!.destructured
stacks[to.toInt() - 1].addAll(
stacks[from.toInt() - 1].subList(
stacks[from.toInt() - 1].size - num.toInt(),
stacks[from.toInt() - 1].size
)
)
for (i in 0 until num.toInt())
stacks[from.toInt() - 1].pollLast()
}
val firstLetters = stacks.map { "" + it.pollLast() }
return firstLetters.reduce { acc, s -> acc + s }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 3,679 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2016/Day03.kt | tginsberg | 74,924,040 | false | null | /*
* Copyright (c) 2016 by <NAME>
*/
package com.ginsberg.advent2016
/**
* Advent of Code - Day 3: December 3, 2016
*
* From http://adventofcode.com/2016/day/3
*
*/
class Day03(rawInput: String) {
private val inputAsDigits = rawInput.trim().split(Regex("\\s+")).map(String::toInt)
/**
* In your puzzle input, how many of the listed triangles are possible?
*/
fun solvePart1(): Int = countValidTriangles(inputByHorizontal())
/**
* In your puzzle input, and instead reading by columns, how many of the
* listed triangles are possible?
*/
fun solvePart2(): Int = countValidTriangles(inputByVertical())
// Takes advantage of descending sort of the triplets so we can
// just subtract the numbers as a reduction and compare to zero.
private fun countValidTriangles(sides: List<List<Int>>): Int =
sides.filter { it.reduce { a, b -> a - b } < 0 }.size
// Picks out triplets of numbers horizontally
private fun inputByHorizontal(): List<List<Int>> =
(0..inputAsDigits.size-3 step 3).map { row ->
listOf(inputAsDigits[row+0],
inputAsDigits[row+1],
inputAsDigits[row+2]).sortedDescending()
}
// Picks out triplets of numbers vertically. Break the input into groups
// of nine numbers, and pick out three groups of three.
private fun inputByVertical(): List<List<Int>> =
(0..inputAsDigits.size-9 step 9).flatMap { group ->
(0..2).map { col ->
listOf(inputAsDigits[group+col+0],
inputAsDigits[group+col+3],
inputAsDigits[group+col+6]).sortedDescending()
}
}
}
| 0 | Kotlin | 0 | 3 | a486b60e1c0f76242b95dd37b51dfa1d50e6b321 | 1,778 | advent-2016-kotlin | MIT License |
advent-of-code-2022/src/test/kotlin/Day 15 Beacon Exclusion Zone.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | import io.kotest.matchers.shouldBe
import kotlin.math.abs
import kotlin.math.max
import kotlinx.collections.immutable.persistentListOf
import org.junit.jupiter.api.Test
class `Day 15 Beacon Exclusion Zone` {
@Test
fun silverTest() {
amountOfDefinitelyNoBeaconPositions(testInput, 10, true) shouldBe 26
}
@Test
fun silver() {
amountOfDefinitelyNoBeaconPositions(loadResource("day15"), 2000000) shouldBe 5870800
}
private fun Point.tuningFrequency(): Long {
return x.toLong() * 4000000 + y
}
@Test
fun goldTest() {
possibleBeacon(testInput).tuningFrequency() shouldBe 56000011
}
@Test
fun gold() {
possibleBeacon(loadResource("day15")).tuningFrequency() shouldBe 10908230916597
}
private fun possibleBeacon(input: String): Point {
val sensorToBeacon = parse(input)
val start = sensorToBeacon.keys.map { it.y }.average().toInt()
println(start)
val (y, range) =
(0..Int.MAX_VALUE)
.asSequence()
.flatMap { listOf(start + it, start - it) }
.map { row ->
row to
sensorToBeacon
.mapNotNull { (sensor, beacon) ->
val toRow = sensor.distanceTo(y = row)
val toBeacon = sensor.distanceTo(other = beacon)
val onRow = toBeacon - toRow
if (onRow > 0) {
(sensor.x - (onRow))..(sensor.x + onRow)
} else {
null
}
}
.fold(IntRangeSet()) { acc, next -> acc.plus(next) }
}
.first { (_, range) -> range.disjoint }
val x = range.ranges.first().last + 1
return Point(x, y).also {
println("Result: " + it)
sensorToBeacon.forEach { println(it) }
}
}
class IntRangeSet {
val disjoint
get() = ranges.size != 1
var ranges = persistentListOf<IntRange>()
fun plus(other: IntRange): IntRangeSet = apply {
val lastOrNull = ranges.lastOrNull()
if (lastOrNull != null && lastOrNull.first <= other.first && lastOrNull.last >= other.last)
return@apply
ranges =
ranges
.add(other)
.sortedBy { it.first }
.fold(persistentListOf()) { acc, next ->
when {
acc.isNotEmpty() && acc.last().last >= next.first -> {
val union = acc.last().first..max(next.last, acc.last().last)
acc.removeAt(acc.lastIndex).add(union)
}
else -> acc.add(next)
}
}
}
val size: Int
get() = ranges.sumOf { it.last - it.first + 1 }
}
private fun amountOfDefinitelyNoBeaconPositions(
input: String,
row: Int,
print: Boolean = false
): Int {
val sensorToBeacon = parse(input)
val sensorsInRange =
sensorToBeacon.filter { (s, b) -> s.distanceTo(y = row) <= s.distanceTo(b) }
if (print) {
printBeacons(sensorToBeacon, sensorsInRange)
}
val fold =
sensorsInRange
.map { (s, b) ->
val toRow = s.distanceTo(y = row)
val toBeacon = s.distanceTo(b)
val onRow = abs(toRow - toBeacon)
(s.x - (onRow))..(s.x + onRow)
}
.fold(IntRangeSet()) { acc, next -> acc.plus(next) }
val amountOfSensorsOnRow =
sensorToBeacon
.flatMap { (k, v) -> listOf(k, v) }
.filter { it.y == row }
.map { it.x }
.toSet()
.size
return (fold.size - amountOfSensorsOnRow)
}
private fun parse(input: String) =
input
.lines()
.filter { it.isNotBlank() }
.associate { line ->
val (sx, sy, bx, by) = line.split("=", ",", ":").mapNotNull { it.toIntOrNull() }
Point(sx, sy) to Point(bx, by)
}
private fun Point.manhattanCircle(manhattan: Int): Set<Point> {
return (x - manhattan..x + manhattan)
.flatMap { xx -> (y - manhattan..y + manhattan).map { yy -> Point(xx, yy) } }
.filter { (this - it).manhattan() <= manhattan }
.toSet()
}
private fun printBeacons(sensorToBeacon: Map<Point, Point>, sensorsInRange: Map<Point, Point>) {
val sensorToBeaconMap =
sensorToBeacon.flatMap { (sensor, beacon) -> listOf(sensor to "S", beacon to "B") }.toMap()
val inRangeMap =
sensorsInRange
.flatMap { (s, b) -> s.manhattanCircle((s - b).manhattan()) }
.associateWith { "#" }
val outOfRangeMap =
sensorToBeacon
.flatMap { (s, b) -> s.manhattanCircle((s - b).manhattan()) }
.associateWith { "." }
printMap(outOfRangeMap + inRangeMap + sensorToBeaconMap, prefixFun = { "$it".padEnd(3, ' ') })
}
private val testInput =
"""
Sensor at x=2, y=18: closest beacon is at x=-2, y=15
Sensor at x=9, y=16: closest beacon is at x=10, y=16
Sensor at x=13, y=2: closest beacon is at x=15, y=3
Sensor at x=12, y=14: closest beacon is at x=10, y=16
Sensor at x=10, y=20: closest beacon is at x=10, y=16
Sensor at x=14, y=17: closest beacon is at x=10, y=16
Sensor at x=8, y=7: closest beacon is at x=2, y=10
Sensor at x=2, y=0: closest beacon is at x=2, y=10
Sensor at x=0, y=11: closest beacon is at x=2, y=10
Sensor at x=20, y=14: closest beacon is at x=25, y=17
Sensor at x=17, y=20: closest beacon is at x=21, y=22
Sensor at x=16, y=7: closest beacon is at x=15, y=3
Sensor at x=14, y=3: closest beacon is at x=15, y=3
Sensor at x=20, y=1: closest beacon is at x=15, y=3
""".trimIndent()
}
private fun Point.distanceTo(x: Int = this.x, y: Int = this.y): Int {
return abs(this.y - y) + abs(this.x - x)
}
private fun Point.distanceTo(other: Point): Int {
return minus(other).manhattan()
}
| 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 5,921 | advent-of-code | MIT License |
src/Day10.kt | janbina | 112,736,606 | false | null | package day10
import getInput
import kotlin.test.assertEquals
fun main(args: Array<String>) {
val input = getInput(10).readLines().first()
assertEquals(52070, part1(input))
assertEquals("7f94112db4e32e19cf6502073c66f9bb", part2(input))
}
fun part1(input: String): Int {
val lengths = input.split(",").map { it.toInt() }
val hash = knotHash(lengths, 1)
return hash[0] * hash[1]
}
fun part2(input: String): String {
val lengths = input.map { it.toInt() } + listOf(17, 31, 73, 47, 23)
val hash = knotHash(lengths)
return hash.asIterable()
.chunked(16) { it.fold(0) { acc, next -> acc xor next } }
.joinToString(separator = "") { it.toString(16).padStart(2, '0') }
}
fun knotHash(lengths: List<Int>, rounds: Int = 64): IntArray {
val list = IntArray(256) { it }
var currentPosition = 0
var skipSize = 0
repeat(rounds) {
lengths.forEach { length ->
list.reverse(currentPosition, length)
currentPosition += length + skipSize
currentPosition %= list.size
skipSize++
}
}
return list
}
fun IntArray.reverse(start: Int, length: Int) {
if (length > this.size) {
throw IllegalArgumentException()
}
var startPointer = start % this.size
var endPointer = (start + length - 1) % this.size
repeat(length / 2) {
val tmp = this[startPointer]
this[startPointer] = this[endPointer]
this[endPointer] = tmp
startPointer++
endPointer--
if (startPointer >= this.size) startPointer = 0
if (endPointer < 0) endPointer = this.size - 1
}
}
| 0 | Kotlin | 0 | 0 | 71b34484825e1ec3f1b3174325c16fee33a13a65 | 1,662 | advent-of-code-2017 | MIT License |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D14.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
class Y2020D14 : BaseSolver() {
override val year = 2020
override val day = 14
override fun part1(): Long = solve(true)
override fun part2(): Long = solve(false)
private fun solve(isPart1: Boolean): Long {
val memory = mutableMapOf<Long, Long>()
var mask: String? = null
for (line in parseInput()) {
if (line.startsWith("mask = ")) {
mask = line.drop(7)
continue
}
val (addresses, value) = line.toMemorySets(mask, isPart1)
addresses.forEach { memory[it] = value }
}
return memory.values.sum()
}
private fun String.toMemorySets(mask: String?, isPart1: Boolean): Pair<List<Long>, Long> {
val result = setMemoryRegex.matchEntire(this)?.groupValues
?: error("Couldn't parse line as set memory instruction")
val address = result[1].toInt()
val value = result[2].toInt()
return if (isPart1) {
val newValue = value.toBinaryValue().mapIndexed { index, c ->
if (mask == null || mask[index] == 'X') {
c
} else {
mask[index]
}
}.joinToString("").toLong(2)
Pair(listOf(address.toLong()), newValue)
} else {
val maskedAddress = address.toBinaryValue().mapIndexed { index, c ->
when {
mask == null || mask[index] == '0' -> c
mask[index] == '1' -> '1'
else -> 'X'
}
}.joinToString("")
val addresses = calculateFloating(maskedAddress).map { it.toLong(2) }
Pair(addresses, value.toLong())
}
}
private fun calculateFloating(masked: String): List<String> {
for (i in masked.indices) {
if (masked[i] == 'X') {
val prev = masked.take(i)
val next = masked.drop(i + 1)
return calculateFloating("${prev}0$next") + calculateFloating("${prev}1$next")
}
}
return listOf(masked)
}
private fun parseInput() = readInput { readLines() }
private fun Int.toBinaryValue() = String.format("%36s", toString(2)).replace(" ", "0")
companion object {
private val setMemoryRegex = "mem\\[(\\d+)] = (\\d+)".toRegex()
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 2,481 | advent-of-code | MIT License |
src/main/kotlin/year2021/day-03.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2021
import lib.aoc.Day
import lib.aoc.Part
fun main() {
Day(3, 2021, PartA3(), PartB3()).run()
}
open class PartA3 : Part() {
protected lateinit var numbers: List<String>
override fun parse(text: String) {
numbers = text.split("\n")
}
override fun compute(): String {
val gammaRate = numbers[0].indices.map { numbers.mostCommonBitAt(it) }.joinToString("")
val converter = mapOf('0' to '1', '1' to '0')
val epsilonRate = gammaRate.map { converter[it]!! }.joinToString("")
return (gammaRate.toInt(2) * epsilonRate.toInt(2)).toString()
}
protected fun List<String>.mostCommonBitAt(pos: Int): Char {
val numberOf0s = count { it[pos] == '0' }
val numberOf1s = count { it[pos] == '1' }
return if (numberOf1s >= numberOf0s) '1' else '0'
}
override val exampleAnswer: String
get() = "198"
}
class PartB3 : PartA3() {
override fun compute(): String {
val oxygenNumber = filter(mapOf('0' to '0', '1' to '1'))
val scrubberNumber = filter(mapOf('0' to '1', '1' to '0'))
return (oxygenNumber.toInt(2) * scrubberNumber.toInt(2)).toString()
}
private fun filter(converter: Map<Char, Char>): String {
var mutableNumbers = numbers
mutableNumbers[0].indices.map { i: Int ->
val bit = mutableNumbers.mostCommonBitAt(i)
mutableNumbers = mutableNumbers.filter { it[i] == converter[bit] }
if (mutableNumbers.size == 1) {
return mutableNumbers.first()
}
}
return mutableNumbers.first()
}
override val exampleAnswer: String
get() = "230"
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 1,754 | Advent-Of-Code-Kotlin | MIT License |
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/MaxArea.kt | scientificCommunity | 352,868,267 | false | {"Java": 154453, "Kotlin": 69817} | package org.baichuan.sample.algorithms.leetcode.middle
/**
* @author: tk (<EMAIL>)
* @date: 2022/1/10
*
* leetcode 11 盛最多水的容器
* https://leetcode-cn.com/problems/container-with-most-water/
*/
class MaxArea {
/**
* 解题思路(双指针法思路浅析):
* 题目要求找出盛水最多的容器,那么哪些因素会影响到盛水量呢?首先,盛水量完全取决于底*min(左高, 右高),
* 所以,我们可以从底最大的时候开始遍历数组进行计算,这样的好处是当我们从"两边往中间靠的过程"中就不用考虑存在更大的底而对计算结果造成影响了。
* 接下来是应该怎么往中间靠?答案是哪边"更低"哪边往中间靠,为什么呢?因为从高度上来说,决定盛水量的是最低的那一边。只有这一边变大才有可能使得容器的盛水量增加。
* 最后就是循环这个往中间靠的过程了。
*/
fun maxArea(height: IntArray): Int {
var result = 0
var left = 0
var right = height.size - 1
var i = 1
while (left < right) {
val tmp = if (height[left] > height[right]) {
right--
height[right] * ((height.size - i))
} else {
left++
height[left] * ((height.size - i))
}
result = tmp.coerceAtLeast(result)
i++
}
return result
}
} | 1 | Java | 0 | 8 | 36e291c0135a06f3064e6ac0e573691ac70714b6 | 1,496 | blog-sample | Apache License 2.0 |
src/main/kotlin/day16/Day16.kt | Jessevanbekkum | 112,612,571 | false | null | package day16
import util.readLines
fun day16_1(input: String, p: Int): String {
val choreo = readLines(input).joinToString("").split(",")
val start = "abcdefghijklmnop".substring(0, p)
return boogie(start, choreo).joinToString("")
}
fun boogie(start: String, choreo: List<String>): MutableList<Char> {
var dance = start.toMutableList()
val p = start.length
val spin = Regex("s(\\d+)")
val exch = Regex("x(\\d+)/(\\d+)")
val partn = Regex("p(\\w)/(\\w)")
choreo.forEach(
{ s ->
val matchResult1 = spin.matchEntire(s)
if (matchResult1 != null) {
val fromIndex = matchResult1.groupValues[1].toInt()
dance = (dance.takeLast(fromIndex) + dance.take(p - fromIndex)).toMutableList()
}
val matchResult2 = exch.matchEntire(s)?.groupValues?.drop(1)?.map { z -> z.toInt() }
if (matchResult2 != null) {
val a = matchResult2[0]
val b = matchResult2[1]
val swap = dance[a]
dance[a] = dance[b]
dance[b] = swap
}
val mr3 = partn.matchEntire(s)?.groupValues?.drop(1)?.map { z -> z.toCharArray()[0] }
if (mr3 != null) {
val a = mr3[0]
val b = mr3[1]
val pa = dance.indexOf(a)
val pb = dance.indexOf(b)
dance[pa] = b
dance[pb] = a
}
}
)
return dance;
}
fun day16_2(input: String, p: Int, f: Int): String {
val choreo = readLines(input).joinToString("").split(",")
var start = "abcdefghijklmnop".substring(0, p)
(0..f - 1).forEach({
start = boogie(start, choreo).joinToString("")
})
return start
} | 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 1,887 | aoc-2017 | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2021/d11/Day11.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2021.d11
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.grids.Grid
import com.groundsfam.advent.grids.containsPoint
import com.groundsfam.advent.grids.copy
import com.groundsfam.advent.points.Point
import com.groundsfam.advent.points.adjacents
import com.groundsfam.advent.grids.readGrid
import com.groundsfam.advent.timed
import kotlin.io.path.div
class Solution(octopuses: Grid<Int>) {
private val grid = octopuses.copy()
private var steps = 0
private var allFlashStep: Int? = null
fun step(): Int {
var flashes = 0
val didFlash = mutableSetOf<Point>()
val willFlash = ArrayDeque<Point>()
// increment energy level of this octopus
// and add it to willFlash queue if needed
fun increaseEnergy(p: Point) {
grid[p] += 1
if (grid[p] > 9 && p !in didFlash) {
willFlash.add(p)
}
}
// increase energy of all octopuses
grid.pointIndices
.forEach(::increaseEnergy)
while (willFlash.isNotEmpty()) {
val p = willFlash.removeFirst()
if (p !in didFlash) {
// perform flash
flashes++
p.adjacents()
.filter(grid::containsPoint)
.forEach(::increaseEnergy)
didFlash.add(p)
}
}
// reset energy of every octopus that flashed to zero
didFlash.forEach { p ->
grid[p] = 0
}
steps++
if (allFlashStep == null && flashes == grid.gridSize) {
allFlashStep = steps
}
return flashes
}
fun stepUntilAllFlash(): Int {
while (allFlashStep == null) {
step()
}
return allFlashStep!!
}
}
fun main() = timed {
val solution = (DATAPATH / "2021/day11.txt")
.readGrid(Char::digitToInt)
.let(::Solution)
val partOne = (1..100).sumOf {
solution.step()
}
println("Part one: $partOne")
println("Part two ${solution.stepUntilAllFlash()}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,143 | advent-of-code | MIT License |
src/main/kotlin/adventofcode/day4.kt | Kvest | 163,103,813 | false | null | package adventofcode
import java.io.File
import java.text.SimpleDateFormat
private val dateFormat = SimpleDateFormat("yyyyy-MM-dd hh:mm")
fun main(args: Array<String>) {
println(first4(File("./data/day4_1.txt").readLines()))
println(second4(File("./data/day4_2.txt").readLines()))
}
fun first4(data: List<String>): Int {
val total = mutableMapOf<Int, Int>()
val sorted = data.sortedBy { dateFormat.parse(it.substring(1, 17)).time }
var currentId = -1
var startedAt = 0
sorted.forEach {
when {
it.contains("begins shift") -> currentId = it.substring(26, it.indexOf(" ", 26)).toInt()
it.contains("falls asleep") -> startedAt = it.substring(15, 17).toInt()
else -> {
val end = it.substring(15, 17).toInt()
val duration = end - startedAt
total[currentId] = total.getOrDefault(currentId, 0) + duration
}
}
}
val guardId = total.maxBy { it.value }?.key ?: -1
val timeline = IntArray(60) { 0 }
sorted.forEach {
when {
it.contains("begins shift") -> currentId = it.substring(26, it.indexOf(" ", 26)).toInt()
it.contains("falls asleep") -> startedAt = it.substring(15, 17).toInt()
currentId == guardId -> {
val end = it.substring(15, 17).toInt()
(startedAt until end).forEach {
++timeline[it]
}
}
}
}
var max = timeline[0]
var index = 0
timeline.forEachIndexed { i, v ->
if (max < v) {
max = v
index = i
}
}
return guardId * index
}
fun second4(data: List<String>): Int {
val sorted = data.sortedBy { dateFormat.parse(it.substring(1, 17)).time }
val timelines = mutableMapOf<Int, IntArray>()
var max = 0
var maxId = 0
var maxMinute = 0
var currentId = -1
var startedAt = 0
sorted.forEach {
when {
it.contains("begins shift") -> currentId = it.substring(26, it.indexOf(" ", 26)).toInt()
it.contains("falls asleep") -> startedAt = it.substring(15, 17).toInt()
else -> {
val end = it.substring(15, 17).toInt()
timelines.getOrPut(currentId) { IntArray(60) { 0 } }.let { timeline ->
(startedAt until end).forEach {
++timeline[it]
if (max < timeline[it]) {
max = timeline[it]
maxMinute = it
maxId = currentId
}
}
}
}
}
}
return maxId * maxMinute
}
| 0 | Kotlin | 0 | 0 | d94b725575a8a5784b53e0f7eee6b7519ac59deb | 2,750 | aoc2018 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day14.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2015
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.P
import se.saidaspen.aoc.util.ints
fun main() = Day14.run()
object Day14 : Day(2015, 14) {
data class Reindeer(val name: String, val maxSpeed: Int, val stamina: Int, val rest: Int) {
fun distAt(i: Int): Int {
val sprints = i / (stamina + rest)
val rem = i.mod(stamina + rest)
val stub = if (rem < stamina) rem else stamina
return ((sprints * stamina) + stub) * maxSpeed
}
}
private val inp = input.lines().map {
val name = it.split(" ")[0]
val nums = ints(it)
Reindeer(name, nums[0], nums[1], nums[2])
}.toList()
override fun part1(): Any {
return inp.maxOf { it.distAt(2503) }
}
override fun part2(): Any {
val points = mutableMapOf<String, Int>()
for (t in 0 until 2503) {
val winner = inp.map { P(it.name, it.distAt(t)) }.maxByOrNull { it.second }!!.first
points.compute(winner) { _, v -> if (v == null) 0 else v + 1 }
}
return points.values.maxOrNull()!!
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,152 | adventofkotlin | MIT License |
src/iii_conventions/MyDate.kt | baldore | 80,958,181 | false | null | package iii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(other: MyDate): Int {
return when {
year != other.year -> year - other.year
month != other.month -> month - other.month
else -> dayOfMonth - other.dayOfMonth
}
}
}
operator fun MyDate.plus(timeInterval: RepeatedTimeInterval): MyDate =
addTimeIntervals(timeInterval.ti, timeInterval.n)
operator fun MyDate.plus(timeInterval: TimeInterval): MyDate =
addTimeIntervals(timeInterval, 1)
operator fun MyDate.rangeTo(other: MyDate): DateRange =
DateRange(this, other)
data class RepeatedTimeInterval(val ti: TimeInterval, val n: Int)
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
operator fun TimeInterval.times(timesNumber: Int): RepeatedTimeInterval = RepeatedTimeInterval(this, timesNumber)
class DateRange(val start: MyDate, val endInclusive: MyDate): Iterable<MyDate> {
override fun iterator(): Iterator<MyDate> = DateIterator(this)
}
class DateIterator(val dateRange: DateRange): Iterator<MyDate> {
var current = dateRange.start
override fun hasNext(): Boolean = current <= dateRange.endInclusive
override fun next(): MyDate {
val next = current
current = current.nextDay()
return next
}
}
// Solution with operator function
operator fun DateRange.contains(d: MyDate): Boolean = start < d && d <= endInclusive
// Solution with ClosedRange interface
// class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>
| 0 | Kotlin | 0 | 0 | 087fb866e0af72c63d3d75148f68f8c1c864dd02 | 1,631 | kotlin-koans | MIT License |
src/day18/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day18
import util.Point3
import util.boundingCuboid
import util.readInput
import util.shouldBe
import java.util.LinkedList
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 64
testInput.part2() shouldBe 58
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private class Input(
val points: List<Point3>,
) {
val bounds = points.boundingCuboid()
}
private fun List<String>.parseInput(): Input {
val points = map { line ->
val (x, y, z) = line.split(",").map { it.toInt() }
Point3(x, y, z)
}
return Input(points)
}
private fun Input.part1(): Int {
var count = 0
for (p in bounds) {
if (p in points) {
count += p.neighbors().count { it !in points }
}
}
return count
}
private fun Input.part2(): Int {
val outsideArea = floodFill()
var count = 0
for (p in bounds) {
if (p in points) {
count += p.neighbors().count { it !in points && it in outsideArea }
}
}
return count
}
private fun Input.floodFill(): Set<Point3> {
val extendedBounds = bounds.growBy(1)
val expanded = mutableSetOf(extendedBounds.minPos)
val toExpand = LinkedList(expanded)
while (toExpand.isNotEmpty()) {
for (p in toExpand.removeFirst().neighbors()) {
if (p !in extendedBounds || p in expanded || p in points) continue
expanded += p
toExpand += p
}
}
return expanded
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 1,632 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxBoxesInWarehouse.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* Put Boxes Into the Warehouse I
* @see <a href="https://leetcode.com/problems/put-boxes-into-the-warehouse-i">Source</a>
*/
fun interface MaxBoxesInWarehouse {
operator fun invoke(boxes: IntArray, warehouse: IntArray): Int
}
/**
* Approach 1: Add Smallest Boxes to the Rightmost Warehouse Rooms
*/
class MaxBoxesInWarehouseAdd : MaxBoxesInWarehouse {
override operator fun invoke(boxes: IntArray, warehouse: IntArray): Int {
// Preprocess the height of the warehouse rooms to get usable heights
for (i in 1 until warehouse.size) {
warehouse[i] = min(warehouse[i - 1], warehouse[i])
}
// Iterate through boxes from smallest to largest
boxes.sort()
var count = 0
for (i in warehouse.size - 1 downTo 0) {
// Count the boxes that can fit in the current warehouse room
if (count < boxes.size && boxes[count] <= warehouse[i]) {
count++
}
}
return count
}
}
/**
* Approach 2: Add Largest Possible Boxes from Left to Right
*/
class MaxBoxesInWarehouseLPB : MaxBoxesInWarehouse {
override operator fun invoke(boxes: IntArray, warehouse: IntArray): Int {
var i: Int = boxes.size - 1
var count = 0
boxes.sort()
for (room in warehouse) {
// Iterate through boxes from largest to smallest
// Discard boxes that doesn't fit in the current warehouse
while (i >= 0 && boxes[i] > room) {
i--
}
if (i == -1) return count
count++
i--
}
return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,323 | kotlab | Apache License 2.0 |
src/Day11.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | import java.io.File
import java.lang.Exception
import java.util.LinkedList
fun main() {
class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val divisionTest: Long,
val yesMonkey: Int,
val noMonkey: Int
) {
var inspected = 0L
fun calmDown(i: Int) {
items[i] = items[i] / 3
}
fun manageWorry(i: Int) {
items[i] = items[i] % (19 * 2 * 3 * 17 * 13 * 7 * 5 * 11)
}
fun inspectItems(amPanicked: Boolean): List<Pair<Int, Long>> {
val itemsToThrow = mutableListOf<Pair<Int, Long>>()
for (i in items.indices) {
// println(" Monkey takes item ${items[i]}")
items[i] = operation(items[i])
// println(" Your worry level increases to ${items[i]}")
if(amPanicked) {
manageWorry(i)
} else {
calmDown(i)
}
// println(" Your worry level decreases to ${items[i]}")
if (items[i] % divisionTest == 0L) {
// println(" Monkey test returns true")
itemsToThrow.add(Pair(yesMonkey, items[i]))
// println(" Monkey throws item to monkey $yesMonkey")
} else {
// println(" Monkey test returns false")
itemsToThrow.add(Pair(noMonkey, items[i]))
// println(" Monkey throws item to monkey $noMonkey")
}
}
inspected += items.size
items.clear()
return itemsToThrow
}
}
fun parseOperation(line: String): (Long) -> Long {
val tokens = line.split(" = ")[1].split(" ")
return fun(item: Long): Long {
val a = if (tokens[0] == "old") item else tokens[0].toLong()
val b = if (tokens[2] == "old") item else tokens[2].toLong()
return when (tokens[1]) {
"+" -> a + b
"*" -> a * b
else -> {
throw Exception("We don't know this operation " + tokens[1])
}
}
}
}
fun parseMonkey(input: List<String>): Monkey {
val items = input[1].split(": ")[1].split(", ").map { it.toLong() }.toMutableList()
val operation = parseOperation(input[2])
val divisionTest = input[3].split("by ")[1].toLong()
val yesMonkey = input[4].split("monkey ")[1].toInt()
val noMonkey = input[5].split("monkey ")[1].toInt()
return Monkey(items, operation, divisionTest, yesMonkey, noMonkey )
}
fun part1(input: String): Long {
val monkeys = input.split("\n\n")
.map { it.split("\n") }
.map { parseMonkey(it) }
for (i in 0 until 20) {
// println("Round $i")
monkeys.forEachIndexed { index, monkey ->
// println("Monkey $index's turn")
val thrownItems = monkey.inspectItems(false)
for (item in thrownItems) {
monkeys[item.first].items.add(item.second)
}
}
}
val twoMonkeys = monkeys.map { it.inspected }.sorted().takeLast(2)
return twoMonkeys[0] * twoMonkeys[1]
}
fun part2(input: String): Long {
val monkeys = input.split("\n\n")
.map { it.split("\n") }
.map { parseMonkey(it) }
for (i in 0 until 10000) {
// println("Round $i")
monkeys.forEachIndexed { index, monkey ->
// println("Monkey $index's turn")
val thrownItems = monkey.inspectItems(true)
for (item in thrownItems) {
monkeys[item.first].items.add(item.second)
}
}
}
val twoMonkeys = monkeys.map { it.inspected }.sorted().takeLast(2)
return twoMonkeys[0] * twoMonkeys[1]
}
// test if implementation meets criteria from the description, like:
val testInput = File("src", "Day11_test.txt").readText()
// println(part1(testInput))
// println(part2(testInput))
val input = File("src", "Day11.txt").readText()
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 4,330 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ConstructBinaryTree2.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
/**
* 106. Construct Binary Tree from Inorder and Postorder Traversal
* @see <a href="https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal">
* Source</a>
*/
fun interface ConstructBinaryTree2 {
fun buildTree(inorder: IntArray, postorder: IntArray): TreeNode?
}
class ConstructBinaryTree2Recursive : ConstructBinaryTree2 {
override fun buildTree(inorder: IntArray, postorder: IntArray): TreeNode? {
if (inorder.size != postorder.size) return null
val map: HashMap<Int, Int> = HashMap()
for (i in inorder.indices) {
map[inorder[i]] = i
}
return buildBinaryTree(inorder, 0, inorder.size - 1, postorder, 0, postorder.size - 1, map)
}
private fun buildBinaryTree(
inorder: IntArray?,
inorderStart: Int,
inorderEnd: Int,
postorder: IntArray,
postorderStart: Int,
postorderEnd: Int,
map: HashMap<Int, Int>,
): TreeNode? {
if (postorderStart > postorderEnd || inorderStart > inorderEnd) return null
val node = TreeNode(postorder[postorderEnd])
val rootIndex = map.getOrDefault(postorder[postorderEnd], 0)
val leftChild = buildBinaryTree(
inorder,
inorderStart,
rootIndex - 1,
postorder,
postorderStart,
postorderStart + rootIndex - inorderStart - 1,
map,
)
val rightChild = buildBinaryTree(
inorder,
rootIndex + 1,
inorderEnd,
postorder,
postorderStart + rootIndex - inorderStart,
postorderEnd - 1,
map,
)
node.left = leftChild
node.right = rightChild
return node
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,428 | kotlab | Apache License 2.0 |
advent2021/src/main/kotlin/year2021/day09/HeightMap.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2021.day09
fun Pair<Int, Int>.neighbors(maxX: Int, maxY: Int) =
listOf(
first - 1 to second,
first + 1 to second,
first to second - 1,
first to second + 1
).filter { (x, y) ->
x >= 0 && y >= 0 && x < maxX && y < maxY
}
fun Pair<Int, Int>.computeBasin(map: HeightMap): Set<Pair<Int, Int>> {
val basin = mutableSetOf(this)
val workList = mutableListOf(this)
while (workList.isNotEmpty()) {
val current = workList.removeAt(0)
val neighbors = current.neighbors(map.maxX, map.maxY).filter { map[it] != 9 }
workList.addAll(neighbors.filter { it !in basin })
basin += neighbors
}
return basin
}
class HeightMap(input: List<String>) {
private val area: Array<Array<Int>> =
input.map {
it.map(Char::digitToInt).toTypedArray()
}.toTypedArray()
operator fun get(x: Pair<Int, Int>): Int =
area[x.first].let { it[x.second] }
val maxX = area.size
val maxY = area[0].size
val lowPoints
get() = (0 until maxX)
.flatMap { x ->
(0 until maxY).map { y ->
x to y
}
}
.filter { it.neighbors(maxX, maxY)
.all { neighbor -> this[it] < this[neighbor] } }
} | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 1,318 | advent-of-code | Apache License 2.0 |
src/main/kotlin/be/swsb/aoc2021/day8/Day8.kt | Sch3lp | 433,542,959 | false | {"Kotlin": 90751} | package be.swsb.aoc2021.day8
private const val amountOfSignalsToDisplay1 = 2
private const val amountOfSignalsToDisplay4 = 4
private const val amountOfSignalsToDisplay7 = 3
private const val amountOfSignalsToDisplay8 = 7
object Day8 {
fun solve1(input: List<String>): Int {
return input.sumOf { line ->
val digits: List<String> = line.substringAfter("| ").split(" ")
digits.count {
it.length in listOf(
amountOfSignalsToDisplay1,
amountOfSignalsToDisplay4,
amountOfSignalsToDisplay7,
amountOfSignalsToDisplay8
)
}
}
}
fun solve2(input: List<String>): Int {
return input.sumOf { line ->
val (signalPattern, displaysAsString) = line.split("| ")
val displays = displaysAsString.split(" ")
val decoder = deduce(signalPattern).build()
displays.joinToString("") { encodedDisplay -> decoder.decode(encodedDisplay) }.toInt()
}
}
fun deduce(signalPattern: String): DecoderBuilder {
val encodedDigits = signalPattern.split(" ")
val encodedOne = encodedDigits.first { it.count() == 2 }
val encodedSeven = encodedDigits.first { it.count() == 3 }
val encodedFour = encodedDigits.first { it.count() == 4 }
return DecoderBuilder()
.deduceSegmentA(encodedOne, encodedSeven)
.deduceOtherSegments(encodedDigits, encodedFour)
}
}
class DecoderBuilder(private val map: Map<Signal, Segment> = emptyMap()) {
fun with(mapping: Pair<Signal, Segment>): DecoderBuilder {
return DecoderBuilder(map + listOf(mapping).toMap())
}
fun deduceSegmentA(
encodedOne: String,
encodedSeven: String
): DecoderBuilder {
val signalForSegmentA = encodedSeven.diff(encodedOne)
return with(signalForSegmentA[0] to 'a')
}
/*
If we add (overlay) all encoded digits on top of each other, and then add (overlay) the encoded 4 exactly 2 more times we get unique amounts for all segments
The top segment we already know.
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 4 + 4 - segmentA
----
8 10
8 10
9999
4 11
4 11
7777
*/
fun deduceOtherSegments(encodedDigits: List<String>, encodedFour: String): DecoderBuilder {
val occurrencesPerSignal = (encodedDigits + encodedFour + encodedFour)
.joinToString("")
.replace(getSignal('a').toString(), "") //drop the signal for the segment we already know before grouping
.groupBy { it }
.map { (k, v) -> v.count() to k }
.toMap()
return with(occurrencesPerSignal[8]!! to 'b')
.with(occurrencesPerSignal[10]!! to 'c')
.with(occurrencesPerSignal[9]!! to 'd')
.with(occurrencesPerSignal[4]!! to 'e')
.with(occurrencesPerSignal[11]!! to 'f')
.with(occurrencesPerSignal[7]!! to 'g')
}
fun build(): Decoder {
return Decoder(map)
}
fun getSignal(segment: Segment): Signal {
return map.filterValues { it == segment }.keys.first()
}
private fun String.diff(other: String) = this.filter { it !in other.toList() }
}
class Decoder(private val map: Map<Signal, Segment>) {
init {
check(map.keys.containsAll(('a'..'g').toList())) { "Tried building a Decoder with incomplete or incorrect signals: ${map.keys}" }
check(map.values.containsAll(('a'..'g').toList())) { "Tried building a Decoder with incomplete or incorrect segments: ${map.values}" }
}
private val digits: Map<String, String> = listOf(
"abcefg" to "0",
"cf" to "1",
"acdeg" to "2",
"acdfg" to "3",
"bcdf" to "4",
"abdfg" to "5",
"abdefg" to "6",
"acf" to "7",
"abcdefg" to "8",
"abcdfg" to "9",
).toMap()
fun decode(encodedDisplay: CharSequence): Digit {
val decodedDisplay = encodedDisplay.map { map[it] }.sortedBy { it }.joinToString("")
return digits[decodedDisplay]!!
}
}
typealias Digit = String
typealias Signal = Char
typealias Segment = Char
| 0 | Kotlin | 0 | 0 | 7662b3861ca53214e3e3a77c1af7b7c049f81f44 | 4,265 | Advent-of-Code-2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/GetMaximumScore.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <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 java.util.LinkedList
import kotlin.math.max
// Get the Maximum Score
class GetMaximumScore {
fun maxSum(nums1: IntArray, nums2: IntArray): Int {
val map: MutableMap<Int, MutableList<Int>> = HashMap()
for (i in 0 until nums1.size - 1) map.computeIfAbsent(
nums1[i],
) { LinkedList() }.add(nums1[i + 1])
for (i in 0 until nums2.size - 1) map.computeIfAbsent(
nums2[i],
) { LinkedList() }.add(nums2[i + 1])
val memo: MutableMap<Int?, Long?> = HashMap()
return max(greedy(nums1[0], map, memo) % M, greedy(nums2[0], map, memo) % M).toInt()
}
private fun greedy(cur: Int, map: MutableMap<Int, MutableList<Int>>, memo: MutableMap<Int?, Long?>): Long {
if (memo.containsKey(cur)) return memo[cur]!!
if (!map.containsKey(cur)) return cur.toLong()
var maxSum: Long = 0
for (next in map[cur]!!) {
maxSum = max(maxSum, greedy(next, map, memo))
}
maxSum += cur.toLong()
memo[cur] = maxSum
return maxSum
}
companion object {
private const val M = 1e9.toInt() + 7
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,794 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DistributeRepeatingIntegers.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 1655. Distribute Repeating Integers
* @see <a href="https://leetcode.com/problems/distribute-repeating-integers/">Source</a>
*/
fun interface DistributeRepeatingIntegers {
fun canDistribute(nums: IntArray, quantity: IntArray): Boolean
}
class DistributeRepeatingIntegersBottomUp : DistributeRepeatingIntegers {
override fun canDistribute(nums: IntArray, quantity: IntArray): Boolean {
val counts: MutableMap<Int, Int> = HashMap()
for (num in nums) {
counts[num] = counts.getOrDefault(num, 0) + 1
}
var idx = 0
val arrCounts = IntArray(counts.size)
for (key in counts.keys) {
arrCounts[idx++] = counts[key] ?: 0
}
return solve(arrCounts, quantity)
}
private fun solve(counts: IntArray, quantity: IntArray): Boolean {
counts.sort()
quantity.sort()
reverse(quantity)
return solve(counts, quantity, 0)
}
private fun reverse(arr: IntArray) {
var i = 0
while (i + i < arr.size) {
val tmp = arr[i]
arr[i] = arr[arr.size - i - 1]
arr[arr.size - i - 1] = tmp
i++
}
}
private fun solve(counts: IntArray, quantity: IntArray, idx: Int): Boolean {
if (idx >= quantity.size) {
return true
}
for (i in counts.indices) {
if (counts[i] >= quantity[idx]) {
counts[i] -= quantity[idx]
if (solve(counts, quantity, idx + 1)) {
return true
}
counts[i] += quantity[idx]
}
}
return false
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,312 | kotlab | Apache License 2.0 |
advanced-algorithms/kotlin/src/lPIntreeP1LMax.kt | nothingelsematters | 135,926,684 | false | {"Jupyter Notebook": 7400788, "Java": 512017, "C++": 378834, "Haskell": 261217, "Kotlin": 251383, "CSS": 45551, "Vue": 37772, "Rust": 34636, "HTML": 22859, "Yacc": 14912, "PLpgSQL": 10573, "JavaScript": 9741, "Makefile": 8222, "TeX": 7166, "FreeMarker": 6855, "Python": 6708, "OCaml": 5977, "Nix": 5059, "ANTLR": 4802, "Logos": 3516, "Perl": 2330, "Mustache": 1527, "Shell": 1105, "MATLAB": 763, "M": 406, "Batchfile": 399} | import java.io.File
import java.util.Scanner
fun schedulePIntreeP1LMax(
deadlines: MutableList<Int>,
m: Int,
fromTo: Map<Int, Int>,
toFrom: Map<Int, List<Int>>,
): Pair<Int, List<Int>> {
val i = deadlines.indices.find { it !in fromTo }!!
val deque = ArrayDeque<Int>()
deque += i
while (deque.isNotEmpty()) {
val j = deque.removeFirst()
toFrom[j].orEmpty().forEach { k ->
deadlines[k] = minOf(deadlines[k], deadlines[j] - 1)
deque.addLast(k)
}
}
var f = 0
val r = MutableList(deadlines.size) { 0 }
val q = MutableList(deadlines.size) { 0 }
val x = MutableList(deadlines.size) { 0 }
deadlines.asSequence().withIndex().sortedBy { it.value }.map { it.index }.forEach { i ->
val t = maxOf(r[i], f)
x[i] = t
q[t] += 1
if (q[t] == m) {
f = t + 1
}
fromTo[i]?.let { j -> r[j] = maxOf(r[j], t + 1) }
}
val l = deadlines.asSequence().zip(x.asSequence()).maxOf { (d, c) -> c + 1 - d }
return l to x
}
fun main() {
val input = Scanner(File("pintreep1l.in").bufferedReader())
val n = input.nextInt()
val m = input.nextInt()
val deadlines = MutableList(n) { input.nextInt() }
val fromTo = mutableMapOf<Int, Int>()
val toFrom = mutableMapOf<Int, MutableList<Int>>()
repeat(n - 1) {
val from = input.nextInt() - 1
val to = input.nextInt() - 1
fromTo[from] = to
toFrom.getOrPut(to) { mutableListOf() }.add(from)
}
val (lMax, schedule) = schedulePIntreeP1LMax(deadlines, m, fromTo, toFrom)
File("pintreep1l.out").printWriter().use { output ->
output.println(lMax)
schedule.forEach { output.print("$it ") }
}
}
| 0 | Jupyter Notebook | 3 | 5 | d442a3d25b579b96c6abda13ed3f7e60d1747b53 | 1,772 | university | Do What The F*ck You Want To Public License |
problems/2020adventofcode16b/submissions/accepted/Stefan.kt | stoman | 47,287,900 | false | {"C": 169266, "C++": 142801, "Kotlin": 115106, "Python": 76047, "Java": 68331, "Go": 46428, "TeX": 27545, "Shell": 3428, "Starlark": 2165, "Makefile": 1582, "SWIG": 722} | import java.math.BigInteger
import java.util.*
fun main() {
val s = Scanner(System.`in`).useDelimiter("""\s\syour ticket:\s|\s\snearby tickets:\s""")
// Read ranges.
val sRanges = Scanner(s.next()).useDelimiter(""":\s|\sor\s|-|\n""")
val ranges = mutableMapOf<String, Set<IntRange>>()
while (sRanges.hasNext()) {
val name = sRanges.next()
ranges[name] = setOf(sRanges.nextInt()..sRanges.nextInt(), sRanges.nextInt()..sRanges.nextInt())
}
// Read tickets
val myTicket: List<Int> = s.next().split(",").map { it.toInt() }
val sTickets = Scanner(s.next())
val tickets = mutableListOf<List<Int>>()
while (sTickets.hasNext()) {
tickets.add(sTickets.next().split(",").map { it.toInt() })
}
// Determine meaning of fields.
val validTickets = tickets.filter { ticket -> ticket.none { i -> ranges.values.flatten().none { i in it } } }
var possible = mutableMapOf<Int, Set<String>>()
for (i in myTicket.indices) {
possible[i] =
ranges.filter { entry -> validTickets.map { it[i] }.all { nr -> entry.value.any { nr in it } } }.map { it.key }
.toSet()
}
val mapping = mutableMapOf<String, Int>()
while (true) {
val next: Int = possible.keys.firstOrNull { possible[it]!!.size == 1 } ?: break
val name: String = possible[next]!!.first()
mapping[name] = next
possible = possible.mapValues { it.value.filter { n -> n != name }.toSet() }.toMutableMap()
}
println(mapping.filterKeys { it.startsWith("departure") }.map { myTicket[it.value].toBigInteger() }
.reduce(BigInteger::times))
}
| 0 | C | 1 | 3 | ee214c95c1dc1d5e9510052ae425d2b19bf8e2d9 | 1,563 | CompetitiveProgramming | MIT License |
src/Day02.kt | Virendra115 | 573,122,699 | false | {"Kotlin": 2427} | fun main() {
fun part1(input: String): Int {
val list = input.split("\r\n")
var ans =0
for (s in list) {
if (s[0] == 'C' && s[2] == 'X')
ans += 6
else if (s[0]== 'B' && s[2] == 'Z')
ans += 6
else if (s[0] == 'A' && s[2] == 'Y')
ans += 6
else if (s[0] == s[2] - 23)
ans += 3
ans += s[2] - 'W'
}
return ans
}
fun part2(input: String): Int {
val list = input.split("\r\n")
var ans =0
for(s in list) {
ans += if (s[2]== 'X') {
if (s[0] == 'A') 3 else if (s[0] == 'B') 1 else 2
} else if (s[2] == 'Y') {
s[0] - 'A' + 4
} else {
6 + if (s[0] == 'A') 2 else if (s[0] == 'B') 3 else 1
}
}
return ans
}
// test if implementation meets criteria from the description, like:
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 44aff316ffe08d27d23f2f2d8ce7d027a0e64ff8 | 1,075 | AdventOfCode-in-kotlin | Apache License 2.0 |
src/Day09.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | import kotlin.math.absoluteValue
fun main() {
operator fun Pair<Int, Int>.plus(other:Pair<Int, Int>): Pair<Int, Int> {
return Pair(this.first + other.first, this.second + other.second)
}
operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>): Pair<Int, Int> {
return Pair(this.first - other.first, this.second - other.second)
}
fun part1(input: List<String>): Int {
val tailPositions = mutableSetOf<Pair<Int, Int>>()
var head = Pair(0,0)
var tail = Pair(0,0)
tailPositions.add(tail)
for (line in input) {
val inc = when (line[0]) {
'R' -> Pair(1,0)
'L' -> Pair(-1,0)
'U' -> Pair(0,1)
'D' -> Pair(0,-1)
else -> throw IllegalArgumentException("Got unexpected direction $line")
}
val (_, numStr) = line.trim().split(' ')
for (i in 0 until numStr.toInt()) {
head += inc
if ((head.first - tail.first).absoluteValue > 1) {
if (head.second > tail.second) {
tail += inc + Pair(0,1)
} else if (head.second < tail.second) {
tail += inc - Pair(0,1)
} else {
tail += inc
}
tailPositions.add(tail)
} else if ((head.second - tail.second).absoluteValue > 1) {
if (head.first > tail.first) {
tail += inc + Pair(1,0)
} else if (head.first < tail.first) {
tail += inc - Pair(1,0)
} else {
tail += inc
}
tailPositions.add(tail)
}
}
}
return tailPositions.size
}
fun part2(input: List<String>): Int {
val tailPositions = mutableSetOf<Pair<Int, Int>>()
var rope = MutableList(10) { Pair(0,0) }
tailPositions.add(rope[9])
for (line in input) {
val inc = when (line[0]) {
'R' -> Pair(1,0)
'L' -> Pair(-1,0)
'U' -> Pair(0,1)
'D' -> Pair(0,-1)
else -> throw IllegalArgumentException("Got unexpected direction $line")
}
val (_, numStr) = line.trim().split(' ')
for (i in 0 until numStr.toInt()) {
rope[0] += inc
for (ix in 1 until rope.size) {
var head = rope[ix-1]
var tail = rope[ix]
if ((head.first - tail.first).absoluteValue > 1) {
val first = (head.first - tail.first) / 2
val second = when {
(head.second > tail.second) -> 1
(head.second < tail.second) -> -1
else -> 0
}
rope[ix] += Pair(first, second)
} else if ((head.second - tail.second).absoluteValue > 1) {
val second = (head.second - tail.second) / 2
val first = when {
(head.first > tail.first) -> 1
(head.first < tail.first) -> -1
else -> 0
}
rope[ix] += Pair(first, second)
} else {
break
}
}
tailPositions.add(rope.last())
}
}
return tailPositions.size
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"R 4\n",
"U 4\n",
"L 3\n",
"D 1\n",
"R 4\n",
"D 1\n",
"L 5\n",
"R 2\n",
)
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = listOf(
"R 5\n",
"U 8\n",
"L 8\n",
"D 3\n",
"R 17\n",
"D 10\n",
"L 25\n",
"U 20\n",
)
println(part2(testInput2))
val input = readInput("day9")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 4,381 | 2022-aoc-kotlin | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year19/Day17.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year19
import com.grappenmaker.aoc.*
fun PuzzleSet.day17() = puzzle(17) {
val prog = input.split(",").map(String::toLong)
val grid = prog.programResults()
.joinToString("") { it.toInt().toChar().toString() }.trim().lines().asCharGrid()
with(grid) {
partOne = points.filter { p ->
this[p] == '#' && p.adjacentSides().all { this[it] == '#' }
}.sumOf { (x, y) -> x * y }.s()
val dirs = listOf('^', '>', 'v', '<').zip(enumValues<Direction>()).toMap()
val starting = points.single { this[it] in dirs }
val startingDir = dirs.getValue(this[starting])
data class Node(val loc: Point, val dir: Direction, val dirChange: Int, val amount: Int)
fun Point.isValid() = this@with[this] != '.'
val path = generateSequence(Node(starting, startingDir, 0, 0)) { (curr, currDir) ->
listOf(-1, 1).mapNotNull { dd ->
val dir = currDir.next(dd)
generateSequence(curr) { it + dir }.takeWhile { it in this && it.isValid() }.lastOrNull()
?.let { p -> Node(p, dir, dd, p manhattanDistanceTo curr) }
}.maxByOrNull { it.amount }
}.drop(1).takeUntil { it.loc.adjacentSides().count { p -> p.isValid() } > 1 }.toList()
// Regex magic by u/Sephibro
// https://www.reddit.com/r/adventofcode/comments/ebr7dg/comment/fb7ymcw/?utm_source=share&utm_medium=web2x&context=3
val pathCommand = path.joinToString(",") { "${if (it.dirChange == -1) "L" else "R"},${it.amount}" }
val joined = "$pathCommand,"
val regex = """^(.{1,21})\1*(.{1,21})(?:\1|\2)*(.{1,21})(?:\1|\2|\3)*$""".toRegex()
val (a, b, c) = regex.matchEntire(joined)!!.groupValues.drop(1).map { it.removeSuffix(",") }
val seq = pathCommand.replace(a, "A").replace(b, "B").replace(c, "C")
partTwo = (listOf(2L) + prog.drop(1)).evalProgram(
(listOf(seq, a, b, c, "n").joinToString("\n") + "\n").map { it.code.toLong() }).s()
}
// Why manually? IDK
// val commands = (listOf(
// "A,B,A,C,A,A,C,B,C,B",
// "L,12,L,8,R,12",
// "L,10,L,8,L,12,R,12",
// "R,12,L,8,L,10",
// "n"
// ).joinToString("\n") + "\n").map { it.code.toLong() }
// partTwo = (listOf(2L) + prog.drop(1)).evalProgram(commands).s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,365 | advent-of-code | The Unlicense |
src/main/kotlin/leetcode/Problem834.kt | Magdi | 390,731,717 | false | null | package leetcode
/**
* https://leetcode.com/problems/sum-of-distances-in-tree/
*/
class Problem834 {
private val graph = HashMap<Int, HashSet<Int>>()
fun sumOfDistancesInTree(n: Int, edges: Array<IntArray>): IntArray {
edges.forEach { (x, y) ->
graph.getOrPut(x) { hashSetOf(y) }.apply {
this.add(y)
}
graph.getOrPut(y) { hashSetOf(x) }.apply {
this.add(x)
}
}
val ans = IntArray(n) { 0 }
val cnt = IntArray(n) { 1 }
cntForParent(0, -1, ans, cnt)
cntForAllNodes(0, -1, ans, cnt, n)
return ans
}
private fun cntForParent(cur: Int, parent: Int, ans: IntArray, cnt: IntArray) {
graph[cur]?.forEach { adj ->
if (parent != adj) {
cntForParent(adj, cur, ans, cnt)
cnt[cur] += cnt[adj]
ans[cur] += ans[adj] + cnt[adj]
}
}
}
private fun cntForAllNodes(cur: Int, parent: Int, ans: IntArray, cnt: IntArray, n: Int) {
graph[cur]?.forEach { adj ->
if (parent != adj) {
ans[adj] = ans[cur] - cnt[adj] + (n - cnt[adj])
cntForAllNodes(adj, cur, ans, cnt, n)
}
}
}
} | 0 | Kotlin | 0 | 0 | 63bc711dc8756735f210a71454144dd033e8927d | 1,280 | ProblemSolving | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ArrayPairSum.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <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
fun interface PairSumStrategy {
operator fun invoke(arr: IntArray): Int
}
class PairSumSort1 : PairSumStrategy {
override operator fun invoke(arr: IntArray): Int {
arr.sort()
val list = arr.toList()
val chunks = list.chunked(2)
var res = 0
for (chunk in chunks) {
res += kotlin.math.min(chunk.first(), chunk.last())
}
return res
}
}
class PairSumSort2 : PairSumStrategy {
override operator fun invoke(arr: IntArray): Int {
arr.sort()
var res = 0
var i = 0
while (i < arr.size) {
res += arr[i]
i += 2
}
return res
}
}
class PairSumSort3 : PairSumStrategy {
override operator fun invoke(arr: IntArray): Int {
arr.sort()
return arr.toList().chunked(2) { it.minOrNull() ?: 0 }.sum()
}
}
class PairSumOdd : PairSumStrategy {
override operator fun invoke(arr: IntArray): Int {
val exist = IntArray(MAX_ARR_SIZE)
for (i in arr.indices) {
exist[arr[i] + ARR_HELPER]++
}
var sum = 0
var isOdd = true
for (i in exist.indices) {
while (exist[i] > 0) {
if (isOdd) {
sum += i - ARR_HELPER
}
isOdd = !isOdd
exist[i]--
}
}
return sum
}
companion object {
private const val MAX_ARR_SIZE = 20001
private const val ARR_HELPER = 10000
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,168 | kotlab | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day06.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2021
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.ints
import se.saidaspen.aoc.util.rotate
import java.util.*
import java.util.Collections.rotate
fun main() = Day06.run()
object Day06 : Day(2021, 6) {
private val fish = ints(input).toMutableList()
override fun part1() = simulateFish2(fish, 80)
override fun part2() = simulateFish2(fish, 256)
private fun simulateFish2(fish: MutableList<Int>, days: Int): Long {
val list = MutableList<Long>(9){0}
fish.forEach { list[it]++ }
repeat(days){
list.rotate(-1)
list[6] += list[8]
}
return list.sum()
}
// Original solution
private fun simulateFish(
fish: MutableList<Int>,
days: Int
): Long {
var fishCount = fish.groupingBy { it }.eachCount().map { it.key to it.value.toLong() }.toMap().toMutableMap()
for (d in 0 until days) {
val newFish = mutableMapOf<Int, Long>().withDefault { 0 }
for ((age, cnt) in fishCount.entries) {
if (age == 0) {
newFish[6] = newFish.getValue(6) + cnt
newFish[8] = newFish.getValue(8) + cnt
} else {
newFish[age - 1] = newFish.getValue(age - 1) + cnt
}
}
fishCount = newFish
}
return fishCount.values.sum()
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,445 | adventofkotlin | MIT License |
src/io/github/samfoy/aoc2022/day2/Day02.kt | samfoy | 572,820,967 | false | {"Kotlin": 7330} | package io.github.samfoy.aoc2022.day2
import io.github.samfoy.aoc2022.asLines
import io.github.samfoy.aoc2022.getInputForDay
suspend fun main() {
fun part1(input: List<String>) = input
.map { it.split(" ") }
.sumOf { gameScore(it) + shapeScore(it.last()) }
fun part2(input: List<String>) = input
.map { replace(it.split(" ")) }
.sumOf { gameScore(it) + shapeScore(it.last()) }
val input = getInputForDay(2).asLines()
println(part1(input))
println(part2(input))
}
fun replace(input: List<String>): List<String?> {
val first = input.first()
return when (input.last()) {
"X" -> listOf(first, losers[first])
"Y" -> listOf(first, ties[first])
"Z" -> listOf(first, winners[first])
else -> listOf(null)
}
}
val winners = mapOf(
Pair("A", "Y"),
Pair("B", "Z"),
Pair("C", "X")
)
val ties = mapOf(
Pair("A", "X"),
Pair("B", "Y"),
Pair("C", "Z")
)
val losers = mapOf(
Pair("A", "Z"),
Pair("B", "X"),
Pair("C", "Y")
)
fun gameScore(input: List<String?>) = when (input) {
listOf("A", "X"), listOf("B", "Y"), listOf("C", "Z") -> 3
listOf("A", "Z"), listOf("B", "X"), listOf("C", "Y") -> 0
listOf("A", "Y"), listOf("B", "Z"), listOf("C", "X") -> 6
else -> 0
}
fun shapeScore(input: String?) = when (input) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
} | 0 | Kotlin | 0 | 0 | 521310dbeb802c6f259c6a5e7906778a94a48d29 | 1,406 | kotlinAOC2022 | Apache License 2.0 |
mantono-kotlin/src/main/kotlin/com/mantono/aoc/day04/Day4.kt | joelfak | 433,981,631 | true | {"Python": 390591, "C#": 189476, "Rust": 166608, "C++": 127941, "F#": 68551, "Haskell": 60413, "Nim": 46562, "Kotlin": 29504, "REXX": 13854, "OCaml": 12448, "Go": 11995, "C": 9751, "Swift": 8043, "JavaScript": 1750, "CMake": 1107, "PowerShell": 866, "AppleScript": 493, "Shell": 255} | package com.mantono.aoc.day04
import com.mantono.aoc.AoC
import com.mantono.aoc.Part
@AoC(4, Part.A)
fun computePasswords1(input: String): Int {
return createSequence(input)
.filter(::isOnlyIncreasing)
.filter(::hasRepeatedNumber)
.filter { it.length == 6 }
.count()
}
@AoC(4, Part.B)
fun computePasswords2(input: String): Int {
return createSequence(input)
.filter(::isOnlyIncreasing)
.filter(::hasOnlyRepeatedTwice)
.filter { it.length == 6 }
.count()
}
fun createSequence(input: String): Sequence<String> {
val inputs: List<String> = input.trim().split("-")
val from: Int = inputs[0].toInt()
val to: Int = inputs[1].toInt()
return (from until to).asSequence().map { it.toString() }
}
fun hasRepeatedNumber(n: String): Boolean = n
.zipWithNext() { a, b -> a == b }
.any { it }
fun isOnlyIncreasing(n: String): Boolean = n
.zipWithNext { a, b -> a <= b }
.all { it }
fun hasOnlyRepeatedTwice(n: String): Boolean {
val occurrences: Map<Int, List<Int>> = n.asSequence()
.map { it.toString().toInt() }
.mapIndexed { index, number -> number to index }
.groupBy({ it.first }, { it.second })
return occurrences
.filter { it.value.size == 2 }
.filter { it.value[0] + 1 == it.value[1] }
.any()
} | 0 | Python | 0 | 0 | d5031078c53c181835b4bf86458b360542f0122e | 1,356 | advent_of_code_2019 | Apache License 2.0 |
src/Day01.kt | Misano9699 | 572,108,457 | false | null | fun main() {
fun listOfCalories(listOfElves: List<List<String>>): List<Int> = listOfElves.map { elf ->
elf.sumOf { it.toInt() }
}
fun part1(input: List<String>): Int {
return listOfCalories(input.splitIntoSublists("")).maxOf { it }
}
fun part2(input: List<String>): Int {
return listOfCalories(input.splitIntoSublists("")).sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
val input = readInput("Day01")
check(part1(testInput).also { println("Answer test input part1: $it") } == 24000)
println("Answer part1: " + part1(input))
check(part2(testInput).also { println("Answer test input part2: $it") } == 45000)
println("Answer part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | adb8c5e5098fde01a4438eb2a437840922fb8ae6 | 828 | advent-of-code-2022 | Apache License 2.0 |
src/day02/Day02.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day02
import readInput
private enum class Selection(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
companion object {
fun from(item: Char): Selection? = when (item) {
'A' -> ROCK
'B' -> PAPER
'C' -> SCISSORS
else -> null
}
}
}
fun main() {
// X: Rock
// Y: Paper
// Z: Scissors
fun part1(input: List<String>): Int {
var score = 0
input.forEach {
val first = Selection.from(it[0]) ?: return@forEach
val second = when (it[2]) {
'X' -> Selection.ROCK
'Y' -> Selection.PAPER
'Z' -> Selection.SCISSORS
else -> null
} ?: return@forEach
val result = when {
first == second -> 3
second == Selection.ROCK && first == Selection.SCISSORS -> 6
second.ordinal - first.ordinal == 1 -> 6
else -> 0
}
score += second.score + result
}
return score
}
// X: Lose
// Y: Draw
// Z: Win
fun part2(input: List<String>): Int {
var score = 0
input.forEach {
val first = Selection.from(it[0]) ?: return@forEach
val result = when (it[2]) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> null
} ?: return@forEach
val second = when (result) {
0 -> if (first.ordinal == 0) {
Selection.SCISSORS
} else {
Selection.values()[first.ordinal - 1]
}
3 -> first
6 -> if (first.ordinal == Selection.values().lastIndex) {
Selection.ROCK
} else {
Selection.values()[first.ordinal + 1]
}
else -> null
} ?: return@forEach
score += second.score + result
}
return score
}
val testInput = readInput("day02/Day02_test")
println(part1(testInput))
println(part2(testInput))
} | 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 2,177 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/aoc2020/Day16.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2020
import days.Day
class Day16: Day(2020, 16) {
override fun partOne(): Any {
val ranges = parseRanges(inputList.takeWhile { it.isNotBlank() })
val rawRanges = ranges.values
return inputList.subList(inputList.indexOf("nearby tickets:")+1, inputList.size).map {
it.split(",").map { it.toInt() }.filter { value ->
rawRanges.none { it.contains(value) }
}.sum()
}.sum()
}
fun parseRanges(list: List<String>): Map<String,Set<Int>> {
val result = mutableMapOf<String,Set<Int>>()
list.forEach {
Regex("(.*): (\\d+)-(\\d+) or (\\d+)-(\\d+)").matchEntire(it)?.destructured?.let {
(name, rangeOneStart, rangeOneEnd, rangeTwoStart, rangeTwoEnd) ->
result[name] = mutableSetOf<Int>().plus(rangeOneStart.toInt()..rangeOneEnd.toInt())
.plus(rangeTwoStart.toInt()..rangeTwoEnd.toInt())
}
}
return result
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
fun calculatePartTwo(list: List<String>): Long {
val ranges = parseRanges(list.takeWhile { it.isNotBlank() })
val validTickets = list.subList(list.indexOf("nearby tickets:")+1, list.size).filter {
it.split(",").map { it.toInt() }.none { value ->
ranges.values.none { it.contains(value) }
}
}
val validRangeNamesForColumns = mutableMapOf<Int,MutableList<String>>()
var done = false
var index = 0
val myTicket = list[list.indexOf("your ticket:")+1]!!
var currentTicket = myTicket
while (!done) {
currentTicket.split(",").forEachIndexed { column, s ->
val value = s.toInt()
if (validRangeNamesForColumns[column] == null) {
validRangeNamesForColumns[column] = mutableListOf<String>().apply {
addAll(ranges.keys)
}
}
validRangeNamesForColumns[column] = validRangeNamesForColumns[column]?.minus(ranges.entries.filterNot { entry ->
entry.value.contains(value)
}.map { it.key })?.toMutableList() ?: error("Oops")
}
do {
// check to see if any name only appears once in all the columns
var entitiesRemoved = false
ranges.keys.filter { rangeName ->
validRangeNamesForColumns.filterValues { it.contains(rangeName) }.size == 1
}.forEach { uniqueRangeName ->
validRangeNamesForColumns.filter {
it.value.contains(uniqueRangeName)
}.forEach {
entitiesRemoved = it.value.removeIf { it != uniqueRangeName }
}
}
// check for single valid name for column
validRangeNamesForColumns.filter {
it.value.size == 1
}.flatMap {
it.value
}.forEach { toRemove ->
validRangeNamesForColumns.forEach { entry ->
if (entry.value.size > 1) {
entitiesRemoved = entitiesRemoved or entry.value.remove(toRemove)
}
}
}
} while(entitiesRemoved)
if (validRangeNamesForColumns.filter { it.value.size > 1 }.isEmpty()) {
done = true
} else {
currentTicket = validTickets[index]
index++
}
}
val myIntTicket = myTicket.split(",").map { it.toInt() }
// now we have our column names, find our ticket "code"
return validRangeNamesForColumns.filter {
it.value[0]?.startsWith("departure") ?: false
}.map { entry ->
myIntTicket[entry.key]!!.toLong()
}.reduce { acc, i -> acc * i }
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 4,072 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/Day02.kt | sherviiin | 575,114,981 | false | {"Kotlin": 14948} | import java.lang.IllegalArgumentException
import java.lang.UnsupportedOperationException
fun main() {
rockPaperScissors(listOf("A Y", "B X", "C Z"), false)
rockPaperScissors(readInput("Day02"), false)
rockPaperScissors(listOf("A Y", "B X", "C Z"), true)
rockPaperScissors(readInput("Day02"), true)
}
fun rockPaperScissors(input: List<String>, secondPartStrategy: Boolean) {
val score = input.sumOf {
val signs = it.split(" ")
val myHand =
if (secondPartStrategy) {
Hand.createHandFor(signs[0], ExpectedResult.create(signs[1]))
} else {
Hand.fromString(signs[1])
}
Game(Hand.fromString(signs[0]), myHand).play()
}
println(score)
}
sealed class Hand {
object Rock : Hand()
object Paper : Hand()
object Scissor : Hand()
companion object {
fun fromString(string: String): Hand {
return when (string) {
"A" -> Rock
"B" -> Paper
"C" -> Scissor
"X" -> Rock
"Y" -> Paper
"Z" -> Scissor
else -> throw IllegalArgumentException()
}
}
fun createHandFor(opponent: String, expectedResult: ExpectedResult): Hand {
return when (fromString(opponent)) {
Paper -> {
when (expectedResult) {
ExpectedResult.WIN -> Scissor
ExpectedResult.DRAW -> Paper
ExpectedResult.LOSE -> Rock
}
}
Rock -> when (expectedResult) {
ExpectedResult.WIN -> Paper
ExpectedResult.DRAW -> Rock
ExpectedResult.LOSE -> Scissor
}
Scissor -> when (expectedResult) {
ExpectedResult.WIN -> Rock
ExpectedResult.DRAW -> Scissor
ExpectedResult.LOSE -> Paper
}
}
}
}
}
enum class ExpectedResult {
WIN,
DRAW,
LOSE;
companion object {
fun create(string: String): ExpectedResult {
return when (string) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw UnsupportedOperationException()
}
}
}
}
data class Game(val elf: Hand, val me: Hand) {
fun play(): Int {
var point = 0
point += when (me) {
Hand.Rock -> 1
Hand.Paper -> 2
Hand.Scissor -> 3
}
point += when (me) {
Hand.Rock -> {
when (elf) {
Hand.Rock -> 3
Hand.Paper -> 0
Hand.Scissor -> 6
}
}
Hand.Paper -> {
when (elf) {
Hand.Rock -> 6
Hand.Paper -> 3
Hand.Scissor -> 0
}
}
Hand.Scissor -> {
when (elf) {
Hand.Rock -> 0
Hand.Paper -> 6
Hand.Scissor -> 3
}
}
}
return point
}
}
| 0 | Kotlin | 0 | 1 | 5e52c1b26ab0c8eca8d8d93ece96cd2c19cbc28a | 3,318 | advent-of-code | Apache License 2.0 |
2020/day24/day24.kt | flwyd | 426,866,266 | false | {"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398} | /*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package day24
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
import kotlin.time.measureTimedValue
/* Input: non-delimited lines consisting of e, w, se, sw, ne, nw instructions to move in those
six directions of a hexagonal grid, with each move list starting at the same tile. The final tile
is flipped over. */
/* Tiles are oriented with rows going east-west, northeast-southwest, southeast-northwest.
This can be represented by an x/y grid where each row is offset by ± half a tile. */
enum class Direction(val deltaWest: Float, val deltaNorth: Float) {
EAST(-1.0f, 0.0f),
WEST(1.0f, 0.0f),
SOUTHEAST(-0.5f, -1.0f),
SOUTHWEST(0.5f, -1.0f),
NORTHEAST(-0.5f, 1.0f),
NORTHWEST(0.5f, 1.0f)
}
data class HexTile(val west: Float, val north: Float) {
fun neighbors() = Direction.values().map { HexTile(west + it.deltaWest, north + it.deltaNorth) }
operator fun plus(dir: Direction) = HexTile(west + dir.deltaWest, north + dir.deltaNorth)
}
fun directionSequence(line: String) = sequence {
var i = 0
while (i < line.length) {
when (line[i]) {
'e' -> yield(Direction.EAST)
'w' -> yield(Direction.WEST)
's' -> when (line[++i]) {
'e' -> yield(Direction.SOUTHEAST)
'w' -> yield(Direction.SOUTHWEST)
else -> error("Unexpected direction in $line")
}
'n' -> when (line[++i]) {
'e' -> yield(Direction.NORTHEAST)
'w' -> yield(Direction.NORTHWEST)
else -> error("Unexpected direction in $line")
}
else -> error("Unexpected direction in $line")
}
i++
}
}
/* Steps through each indicated direction and returns the identified tile. */
fun findTile(line: String) = directionSequence(line).fold(HexTile(0f, 0f), HexTile::plus)
/* Output: number of tiles which have been flipped an odd number of times after all input lines have
been followed. */
object Part1 {
fun solve(input: Sequence<String>): String {
return input.map(::findTile).groupingBy { it }.eachCount().filterValues { it % 2 == 1 }.count()
.toString()
}
}
/* Output: Once the initial state from part 1 is established, run 100 rounds with the following
game-of-life type rules: flipped tiles remain flipped if they're adjacent to 1 or 2 other flipped
tiles; unflipped tiles are flipped if they're adjacent to 2 flipped tiles. */
object Part2 {
fun solve(input: Sequence<String>): String {
var flipped =
input.map(::findTile).groupingBy { it }.eachCount().filterValues { it % 2 == 1 }.keys.toSet()
repeat(100) {
val adjacent = flipped.flatMap { black -> black.neighbors().map { it to black } }
.groupingBy { it.first }
.eachCount()
flipped = flipped.filter { adjacent[it] ?: 0 in 1..2 }.toSet() +
adjacent.filterValues { it == 2 }.keys
}
return flipped.size.toString()
}
}
@ExperimentalTime
@Suppress("UNUSED_PARAMETER")
fun main(args: Array<String>) {
val lines = generateSequence(::readLine).toList()
print("part1: ")
TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
print("part2: ")
TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
}
| 0 | Julia | 1 | 5 | f2d6dbb67d41f8f2898dbbc6a98477d05473888f | 3,529 | adventofcode | MIT License |
src/main/kotlin/com/github/pjozsef/rumorsimulation/util/GraphUtils.kt | pjozsef | 124,445,433 | false | null | package com.github.pjozsef.rumorfx.util
import com.github.pjozsef.rumorfx.datastructure.Graph
import java.util.*
val <T> Graph<T>.DELTA: Int
get() = this.nodeNeighbourCounts().max() ?: 0
val <T> Graph<T>.delta: Int
get() = this.nodeNeighbourCounts().min() ?: 0
fun <T> Graph<T>.conductance(): Double {
val nodes = this.nodes.toSet()
val graphVolume_2 = nodes.volume(this) / 2.0
data class SetWithVolume(val set: Set<T>, val volume: Int)
return nodes.powerSet().map {
SetWithVolume(it, it.volume(this))
}.filter {
0 < it.volume && it.volume <= graphVolume_2
}.map {
this.cutSize(it.set).toDouble() / it.volume.toDouble()
}.min() ?: 0.0
}
fun <T> Graph<T>.vertexExpansion(): Double {
val nodes = this.nodes.toSet()
val n_2 = nodes.size.toDouble() / 2
return nodes.powerSet().filter {
it.isNotEmpty() && it.size <= n_2
}.map {
it.vertexExpansion(this)
}.min() ?: 0.0
}
fun <T> Set<T>.boundary(graph: Graph<T>): Set<T> {
val nodes = graph.nodes.toMutableSet()
nodes.removeAll(this)
return nodes.filter { graph.getNeighbours(it).intersect(this).isNotEmpty() }.toSet()
}
fun <T> Set<T>.boundarySize(graph: Graph<T>): Int = this.boundary(graph).size
fun <T> Set<T>.vertexExpansion(graph: Graph<T>): Double = this.boundarySize(graph).toDouble() / this.size
fun <T> Graph<T>.nodeNeighbourCounts(): List<Int> = this.nodes.map { getNeighbours(it).size }
fun <T> Set<T>.powerSet(): Collection<Set<T>> {
tailrec fun <T> iter(set: List<T>, ps: Collection<List<T>>): Collection<List<T>> {
return if (set.isEmpty()) {
ps
} else {
iter(set.tail, ps + ps.map { it + set.head })
}
}
val result = iter(this.toList(), mutableListOf(ArrayList<T>()))
return result.map { it.toSet() }
}
fun <T> Set<T>.volume(graph: Graph<T>): Int {
return this.map { graph.getNeighbours(it).size }.sum()
}
fun <T> Graph<T>.cut(fromSet: Set<T>): Collection<Pair<T, T>> {
val toSet = this.nodes.toMutableSet()
toSet.removeAll(fromSet)
return this.edges.filter {
fromSet.contains(it.first) && toSet.contains(it.second)
|| fromSet.contains(it.second) && toSet.contains(it.first)
}
}
fun <T> Graph<T>.cutSize(set: Set<T>): Int = this.cut(set).size
val <T> List<T>.tail: List<T>
get() = drop(1)
val <T> List<T>.head: T
get() = first() | 0 | Kotlin | 0 | 0 | d83e474a8f8bbf745e7cde553cba1087f51d9c90 | 2,421 | rumor-spread-simulation | MIT License |
src/Day04.kt | WhatDo | 572,393,865 | false | {"Kotlin": 24776} | fun main() {
val input = readInput("Day04")
val rangePairs = input.map(::mapPairs)
val fullOverlapping = rangePairs
.filter { (r1, r2) -> hasFullOverlap(r1, r2) }
.onEach { (r1, r2) -> println("$r1 and $r2 is fully overlapping") }
println("There are ${fullOverlapping.size} overlaps")
val partialOverlapping = rangePairs
.filter { (r1, r2) -> hasPartialOverlap(r1, r2) }
.onEach { (r1, r2) -> println("$r1 and $r2 is partially overlapping") }
println("There are ${partialOverlapping.size} partial overlaps")
}
private fun hasPartialOverlap(range1: IntRange, range2: IntRange) = range1.contains(range2) || range2.contains(range1)
private fun hasFullOverlap(range1: IntRange, range2: IntRange) =
range1.fullyContains(range2) || range2.fullyContains(range1)
private fun mapPairs(row: String): Pair<IntRange, IntRange> {
return row.split(",")
.map { range ->
val (low, high) = range.split("-").map { it.toInt() }
low..high
}.let { (first, second) -> first to second }
} | 0 | Kotlin | 0 | 0 | 94abea885a59d0aa3873645d4c5cefc2d36d27cf | 1,076 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2018/calendar/day06/Day06.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2018.calendar.day06
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import kotlin.Int.Companion.MAX_VALUE
import kotlin.Int.Companion.MIN_VALUE
import kotlin.math.abs
class Day06 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::point) { input ->
val points = input.toList()
val area = generateArea(points)
val pointsToIgnore = points.filter { (x, y) ->
x == area.left || x == area.right || y == area.top || y == area.bottom
}.toSet()
val counts = mutableMapOf<Point, Int>()
forPoints(area) { x, y ->
val distances = points.map { it to abs(x - it.x) + abs(y - it.y) }.sortedBy { it.second }
val (closest, secondClosest) = distances.take(2)
if (closest.second < secondClosest.second) counts.merge(closest.first, 1, Int::plus)
}
counts.filterNot { pointsToIgnore.contains(it.key) }.maxOf { it.value }
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::point) { input ->
val points = input.toList()
val area = generateArea(points)
var pointsWithinRegion = 0
forPoints(area) { x, y ->
val distanceSum = points.sumOf { point -> abs(x - point.x) + abs(y - point.y) }
if (distanceSum < DISTANCE) pointsWithinRegion++
}
pointsWithinRegion
}
private fun generateArea(points: List<Point>): Area {
var top = MAX_VALUE
var bottom = MIN_VALUE
var left = MAX_VALUE
var right = MIN_VALUE
points.forEach { (x, y) ->
top = minOf(y, top)
bottom = maxOf(y, bottom)
left = minOf(x, left)
right = maxOf(x, right)
}
return Area(top, bottom, left, right)
}
private fun forPoints(area: Area, handler: (x: Int, y: Int) -> Unit) {
(area.top..area.bottom).forEach { y ->
(area.left..area.right).forEach { x ->
handler(x, y)
}
}
}
private fun point(line: String) = line.split(", ").let { (x, y) -> Point(x.toInt(), y.toInt()) }
private data class Point(val x: Int, val y: Int)
private data class Area(val top: Int, val bottom: Int, val left: Int, val right: Int)
companion object {
private const val DISTANCE = 10_000
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 2,311 | advent-of-code | MIT License |
src/Day05.kt | mhuerster | 572,728,068 | false | {"Kotlin": 24302} | fun main() {
// TODO: parse start state from file
val sampleInitialState = mutableMapOf(
1 to "ZN",
2 to "MCD",
3 to "P",
)
val initialState = mutableMapOf(
1 to "NRGP",
2 to "JTBLFGDC",
3 to "MSV",
4 to "LSRCZP",
5 to "PSLVCWDQ",
6 to "CTNWDMS",
7 to "HDGWP",
8 to "ZLPHSCMV",
9 to "RPFLWGZ",
)
val instructionPattern = "move\\s(\\d+)\\D+(\\d+)\\D+(\\d+)".toRegex()
fun parseInstruction(instruction: String): List<Int> {
val matches = instructionPattern.find(instruction)!!
val (a, b, c) = matches.destructured
val components = listOf(a, b, c) // TODO: get rid of intermediate vals
return (components.map { it.toInt() })
}
fun executeInstruction9000(instruction: List<Int>, stacks: MutableMap<Int, String>): MutableMap<Int, String> {
val (quantity, fromStackIndex, toStackIndex) = instruction
val fromStack = stacks.get(fromStackIndex)
val toStack = stacks.get(toStackIndex)
val cratesToMove = fromStack!!.takeLast(quantity).reversed()
val newToStack = toStack!!.plus(cratesToMove)
val newFromStack = fromStack.dropLast(quantity)
val changedStacks = mapOf(
fromStackIndex to newFromStack,
toStackIndex to newToStack
)
val newStacks = stacks.plus(changedStacks).toMutableMap()
return(newStacks)
}
fun executeInstruction9001(instruction: List<Int>, stacks: MutableMap<Int, String>): MutableMap<Int, String> {
val (quantity, fromStackIndex, toStackIndex) = instruction
val fromStack = stacks.get(fromStackIndex)
val toStack = stacks.get(toStackIndex)
val cratesToMove = fromStack!!.takeLast(quantity)
val newToStack = toStack!!.plus(cratesToMove)
val newFromStack = fromStack.dropLast(quantity)
val changedStacks = mapOf(
fromStackIndex to newFromStack,
toStackIndex to newToStack
)
val newStacks = stacks.plus(changedStacks).toMutableMap()
return(newStacks)
}
fun part1(input: List<String>, initialState: MutableMap<Int, String>): String {
var newStacks = initialState
for (line in input) {
if (instructionPattern.matches(line)) {
val instruction = (parseInstruction(line))
newStacks = executeInstruction9000(instruction, newStacks)
}
}
return(newStacks.values.map { it.last() }.joinToString(""))
}
fun part2(input: List<String>, initialState: MutableMap<Int, String>): String {
var newStacks = initialState
for (line in input) {
if (instructionPattern.matches(line)) {
val instruction = (parseInstruction(line))
newStacks = executeInstruction9001(instruction, newStacks)
}
}
return(newStacks.values.map { it.last() }.joinToString(""))
}
val testInput = readInput("Day05_sample")
val input = readInput("Day05")
// test if implementation meets criteria from the description, like:
println(part1(testInput, sampleInitialState))
check(part1(testInput, sampleInitialState) == "CMZ")
println(part1(input, initialState))
// check(part2(testInput)
println(part2(testInput, sampleInitialState))
check(part2(testInput, sampleInitialState) == "MCD")
println(part2(input, initialState))
} | 0 | Kotlin | 0 | 0 | 5f333beaafb8fe17ff7b9d69bac87d368fe6c7b6 | 3,196 | 2022-advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DiffWaysToCompute.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
/**
* 241. Different Ways to Add Parentheses
* @see <a href="https://leetcode.com/problems/different-ways-to-add-parentheses/">Source</a>
*/
fun interface DiffWaysToCompute {
fun compute(expression: String): List<Int>
}
class DiffWaysToComputeRecursive : DiffWaysToCompute {
// function to get the result of the operation
operator fun invoke(x: Int, y: Int, op: Char): Int {
if (op == '+') return x + y
if (op == '-') return x - y
return if (op == '*') x * y else 0
}
override fun compute(expression: String): List<Int> {
val results: MutableList<Int> = ArrayList()
if (expression.isBlank()) return results
var isNumber = true
for (i in expression.indices) {
// check if current character is an operator
if (!Character.isDigit(expression[i])) {
// if current character is not a digit then
// exp is not purely a number
isNumber = false
// list of first operands
val left = compute(expression.substring(0, i))
// list of second operands
val right = compute(expression.substring(i + 1))
// performing operations
for (x in left) {
for (y in right) {
val value = invoke(x, y, expression[i])
results.add(value)
}
}
}
}
if (isNumber) results.add(Integer.valueOf(expression))
return results
}
}
class DiffWaysToComputeDivideAndConquer : DiffWaysToCompute {
override fun compute(expression: String): List<Int> {
if (expression.isEmpty()) return emptyList()
return mutableListOf<Int>().apply {
expression.toCharArray().forEachIndexed { index, char ->
if (char in listOf('+', '-', '*')) {
val left = expression.substring(0, index)
val right = expression.substring(index + 1)
val leftNums = compute(left)
val rightNums = compute(right)
leftNums.forEach { num1 ->
rightNums.forEach { num2 ->
add(char.calculate(num1, num2))
}
}
}
}
if (isEmpty()) add(expression.toInt())
}
}
private fun Char.calculate(num1: Int, num2: Int) = when (this) {
'+' -> num1 + num2
'-' -> num1 - num2
'*' -> num1 * num2
else -> throw IllegalArgumentException("Symbol is not allowed")
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,332 | kotlab | Apache License 2.0 |
src/main/kotlin/g2201_2300/s2242_maximum_score_of_a_node_sequence/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2201_2300.s2242_maximum_score_of_a_node_sequence
// #Hard #Array #Sorting #Graph #Enumeration
// #2023_06_27_Time_844_ms_(100.00%)_Space_72.5_MB_(100.00%)
class Solution {
fun maximumScore(scores: IntArray, edges: Array<IntArray>): Int {
// store only top 3 nodes (having highest scores)
val graph = Array(scores.size) { IntArray(3) }
for (a in graph) {
a.fill(-1)
}
for (edge in edges) {
insert(edge[0], graph[edge[1]], scores)
insert(edge[1], graph[edge[0]], scores)
}
var maxScore = -1
for (edge in edges) {
val u = edge[0]
val v = edge[1]
val score = scores[u] + scores[v]
for (i in 0..2) {
// if neighbour is current node, skip
if (graph[u][i] == -1 || graph[u][i] == v) {
continue
}
for (j in 0..2) {
// if neighbour is current node or already choosen node, skip
if (graph[v][j] == -1 || graph[v][j] == u) {
continue
}
if (graph[v][j] == graph[u][i]) {
continue
}
maxScore = Math.max(maxScore, score + scores[graph[u][i]] + scores[graph[v][j]])
}
}
}
return maxScore
}
private fun insert(n: Int, arr: IntArray, scores: IntArray) {
if (arr[0] == -1) {
arr[0] = n
} else if (arr[1] == -1) {
if (scores[arr[0]] < scores[n]) {
arr[1] = arr[0]
arr[0] = n
} else {
arr[1] = n
}
} else if (arr[2] == -1) {
if (scores[arr[0]] < scores[n]) {
arr[2] = arr[1]
arr[1] = arr[0]
arr[0] = n
} else if (scores[arr[1]] < scores[n]) {
arr[2] = arr[1]
arr[1] = n
} else {
arr[2] = n
}
} else {
if (scores[arr[1]] < scores[n]) {
arr[2] = arr[1]
arr[1] = n
} else if (scores[arr[2]] < scores[n]) {
arr[2] = n
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,338 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/day03/Day03.kt | Malo-T | 575,370,082 | false | null | package day03
private val itemPriorities: Map<Char, Int> = (('a'..'z') + ('A'..'Z')).mapIndexed { i, c -> c to i + 1 }.toMap()
private typealias RuckSack = Pair<Set<Char>, Set<Char>>
class Day03 {
fun parse(input: String): List<RuckSack> =
input.lines().map { line ->
RuckSack(
first = line.substring(0, line.length / 2).toSet(),
second = line.substring(line.length / 2).toSet()
)
}
fun part1(parsed: List<RuckSack>): Int =
parsed.map { (first, second) -> first.intersect(second).first() }
.sumOf { itemPriorities[it]!! }
fun part2(parsed: List<RuckSack>): Int =
parsed.map { it.first + it.second }
.windowed(size = 3, step = 3) { (first, second, third) ->
first.intersect(second).intersect(third).first()
}
.sumOf { itemPriorities[it]!! }
}
| 0 | Kotlin | 0 | 0 | f4edefa30c568716e71a5379d0a02b0275199963 | 913 | AoC-2022 | Apache License 2.0 |
library/src/main/kotlin/io/github/tomplum/libs/extensions/CollectionExtensions.kt | TomPlum | 317,517,927 | false | {"Kotlin": 161096} | package io.github.tomplum.libs.extensions
import kotlin.math.pow
/**
* Returns the product of all the integers in the given list.
*/
fun List<Int>.product(): Int = if (isNotEmpty()) reduce { product, next -> product * next } else 0
fun List<Long>.product(): Long = if (isNotEmpty()) reduce { product, next -> product * next } else 0
/**
* Converts the [IntArray] into its decimal equivalent.
* This assumes the array contains only 1s and 0s.
* @return The decimal representation.
*/
fun IntArray.toDecimal(): Long = reversed()
.mapIndexed { i, bit -> if (bit == 1) 2.0.pow(i) else 0 }
.sumOf { integer -> integer.toLong() }
/**
* For two sets A and B, the Cartesian product of A and B is denoted by A×B and defined as:
* A×B = { (a,b) | aϵA and bϵB }
*
* Put simply, the Cartesian Product is the multiplication of two sets to form the set of all ordered pairs.
* This function returns the cartesian product of itself and the given set, meaning A and B are [this] and [other].
*
* @see cartesianProductQuadratic for a variant that returns the product of itself.
*/
fun <S, T> List<S>.cartesianProduct(other: List<T>): List<Pair<S, T>> = this.flatMap { value ->
List(other.size){ i -> Pair(value, other[i]) }
}
/**
* For two sets A and B, the Cartesian product of A and B is denoted by A×B and defined as:
* A×B = { (a,b) | aϵA and bϵB }
*
* Put simply, the Cartesian Product is the multiplication of two sets to form the set of all ordered pairs.
* This function returns the cartesian product of itself, meaning both A and B are simply [this].
*
* @see cartesianProductCubic for a variant that accepts another set.
*/
fun <T> List<T>.cartesianProductQuadratic(): List<Pair<T, T>> = this.flatMap { value ->
List(this.size){ i -> Pair(value, this[i]) }
}
/**
* For three sets A, B and C, the Cartesian product of A, B and C is denoted by A×B×C and defined as:
* A×B×C = { (p, q, r) | pϵA and qϵB and rϵC }
*
* Put simply, the Cartesian Product is the multiplication of three sets to form the set of all ordered pairs.
* This function returns the cartesian product of itself and the given sets, meaning that A, B & C are all [this].
*
* @see cartesianProductQuadratic for a variation that simply finds the product of itself.
*/
fun <T> List<T>.cartesianProductCubic(): List<Triple<T, T, T>> = cartesianProduct(this, this, this).map { set ->
Triple(set[0], set[1], set[2])
}
/**
* For three sets A, B and C, the Cartesian product of A, B and C is denoted by A×B×C and defined as:
* A×B×C = { (p, q, r) | pϵA and qϵB and rϵC }
*
* Put simply, the Cartesian Product is the multiplication of three sets to form the set of all ordered pairs.
* This function returns the cartesian product of itself and the given sets, meaning both A, B and C are [this],
* [second] and [third] respectively.
*/
fun <T> List<T>.cartesianProductCubic(second: List<T>, third: List<T>): List<Triple<T, T, T>> =
cartesianProduct(this, second, third).map { set -> Triple(set[0], set[1], set[2]) }
/**
* Finds the Cartesian Product of any number of given [sets].
*/
private fun <T> cartesianProduct(vararg sets: List<T>): List<List<T>> = sets.fold(listOf(listOf())) { acc, set ->
acc.flatMap { list -> set.map { element -> list + element } }
}
/**
* Produces a list of all distinct pairs of elements from the given collection.
* Pairs are considered distinct irrespective of their order.
*
* For example, given a collection of [A, B, C]:
* - [A, A] is NOT considered distinct
* - [A, B] and [B, A] are considered equal
* - The output for this collection would be [[A, B], [A, C], [B, C]].
*
* @return A list of all distinct pairs of elements.
*/
fun <T> Collection<T>.distinctPairs(): List<Pair<T, T>> = this.flatMapIndexed { i, element ->
this.drop(i + 1).map { otherElement ->
element to otherElement
}
}
/**
* Splits a collection based on the given [predicate].
* @param predicate A boolean predicate to determine when to split the list.
* @return A collection of collections after splitting.
*/
fun <T> Collection<T>.split(predicate: (element: T) -> Boolean): Collection<Collection<T>> {
var i = 0
val data = mutableMapOf<Int, List<T>>()
var current = mutableListOf<T>()
this.forEachIndexed { index, element ->
if (index == this.size - 1) {
current.add(element)
data[i] = current
} else if (predicate(element)) {
data[i] = current
i++
current = mutableListOf()
} else {
current.add(element)
}
}
return data.values.toList()
}
/**
* Calculates the lowest common multiple of
* all the long values of this given list.
*/
fun List<Long>.lcm(): Long {
if (this.isNotEmpty()) {
var result = this[0]
this.forEachIndexed { i, _ -> result = lcm(result, this[i]) }
return result
}
throw IllegalArgumentException("Cannot find the LCM of an empty list.")
}
private fun lcm(a: Long, b: Long) = a * (b / gcd(a, b))
private fun gcd(a: Long, b: Long): Long {
var n1 = a
var n2 = b
while (n1 != n2) {
if (n1 > n2) n1 -= n2 else n2 -= n1
}
return n1
} | 2 | Kotlin | 0 | 0 | c026ab7ae982c34db4f5fbebf3f79b0b8c717ee5 | 5,233 | advent-of-code-libs | Apache License 2.0 |
2022/kotlin/src/Day01.kt | tomek0123456789 | 573,389,936 | false | {"Kotlin": 5085} | fun main() {
fun part1(input: List<String>): Int {
var max = 0
var current = 0
for (calories in input) {
if (calories == "") {
if (max < current) {
max = current
}
current = 0
} else {
current += calories.toInt()
}
}
return max
}
fun part2(input: List<String>): Int {
val maxSet = setOf(-1, -2, -3).toMutableSet()
var current = 0
for (calories in input) {
if (calories == "") {
if (maxSet.min() < current) {
maxSet.remove(maxSet.min())
maxSet.add(current)
}
current = 0
} else {
current += calories.toInt()
}
}
return maxSet.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
// check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5ee55448242ec79475057f43d34f19ae05933eba | 1,174 | aoc | Apache License 2.0 |
src/day20/Day20.kt | gautemo | 317,316,447 | false | null | package day20
import shared.Point
import shared.getText
import shared.separateByBlankLine
import kotlin.math.sqrt
fun cornerTilesMultiplied(map: TileMap): Long{
return map.xy[Point(0,0)]!!.id * map.xy[Point(map.length-1,0)]!!.id * map.xy[Point(map.length-1,map.length-1)]!!.id * map.xy[Point(0,map.length-1)]!!.id
}
fun findImage(input: String): TileMap{
val tiles = toTiles(input)
val length = sqrt(tiles.size.toDouble()).toInt()
val tileCombinations = tiles.flatMap { allTileCombinations(it) }
val map = TileMap(length)
val testedCombinations = mutableListOf<Map<Point, Tile>>()
while(!map.isFull()){
places@for(y in 0 until map.length){
for(x in 0 until map.length){
val toTry = tileCombinations.find {
val xyNow = map.xy.toMutableMap()
xyNow[Point(x,y)] = it
!map.xy.any { (_, t) -> t.id == it.id } && !testedCombinations.contains(xyNow) && it.fits(map.xy[Point(x-1, y)], map.xy[Point(x, y-1)])
}
if(toTry != null){
map.add(Point(x,y), toTry)
}else{
testedCombinations.add(map.xy.toMap())
map.wipe()
break@places
}
}
}
}
return map
}
fun allTileCombinations(tile: Tile): List<Tile>{
return listOf(
tile,
Tile(tile.input, 0, true),
Tile(tile.input, 1),
Tile(tile.input, 1, true),
Tile(tile.input, 2),
Tile(tile.input, 2, true),
Tile(tile.input, 3),
Tile(tile.input, 3, true)
)
}
fun toTiles(input: String) = separateByBlankLine(input).map { Tile(it) }
data class Tile(val input: String, var rotated: Int = 0, var flipped: Boolean = false){
val id = input.lines()[0].split(" ")[1].trimEnd(':').toLong()
val pixels: String
init {
var rotatedFlippedPixels = input.replace(input.lines()[0] + "\n", "")
repeat(rotated){
var newRotated = ""
for(x in rotatedFlippedPixels.lines().indices){
for(y in rotatedFlippedPixels.lines().size - 1 downTo 0){
newRotated += rotatedFlippedPixels.lines()[y][x]
}
if(x < rotatedFlippedPixels.lines().size - 1) {
newRotated += "\n"
}
}
rotatedFlippedPixels = newRotated
}
if(flipped){
var newFlipped = ""
for((i, line) in rotatedFlippedPixels.lines().withIndex()){
newFlipped += line.reversed()
if(i < rotatedFlippedPixels.lines().size - 1) {
newFlipped += "\n"
}
}
rotatedFlippedPixels = newFlipped
}
pixels = rotatedFlippedPixels
}
fun fits(left: Tile?, up: Tile?) = (left == null || left.right() == left()) && (up == null || up.down() == up())
fun up() = pixels.lines()[0]
fun down() = pixels.lines().last()
fun left() = pixels.lines().map { it.first() }.joinToString("")
fun right() = pixels.lines().map { it.last() }.joinToString("")
fun pixelsWithoutFrame(): String{
var img = ""
for((i, line) in pixels.lines().withIndex()){
if(i != 0 && i != pixels.lines().size - 1){
img += line.substring(1, line.length-1)
if(i < pixels.lines().size - 2) {
img += "\n"
}
}
}
return img
}
}
class TileMap(val length: Int){
val xy = mutableMapOf<Point, Tile>()
fun add(point: Point, tile: Tile){
xy[point] = tile
}
fun wipe(){
xy.clear()
}
fun isFull() = xy.size == length * length
fun getImage(): String{
val tileHeight = xy[Point(0,0)]!!.pixelsWithoutFrame().lines().size
val img = MutableList(length * tileHeight){""}
for(y in 0 until length){
for(x in 0 until length){
for((i, line) in xy[Point(x,y)]!!.pixelsWithoutFrame().lines().withIndex()){
img[y*tileHeight+i] += line
}
}
}
return img.joinToString("\n")
}
}
fun main(){
val input = getText("day20.txt")
val map = findImage(input)
val result = cornerTilesMultiplied(map)
println(result)
val waterRoughness = waterRoughness(map)
println(waterRoughness)
}
fun monsterPattern(): List<Point>{
val monster = """
#
# ## ## ###
# # # # # #
""".lines().filter { it.isNotBlank() }
val points = mutableListOf<Point>()
for(y in monster.indices) {
for(x in monster[0].indices){
if(monster[y][x] == '#'){
points.add(Point(x,y))
}
}
}
return points
}
fun countMonsters(img: String): Int{
var count = 0
val monsterPoints = monsterPattern()
val monsterWidth = monsterPoints.map { it.x }.max()!!
val monsterHeight = monsterPoints.map { it.y }.max()!!
for(y in 0 until img.lines().size - monsterHeight){
for(x in 0 until img.lines().size - monsterWidth){
val found = monsterPattern().all { img.lines()[it.y + y][it.x + x] == '#' }
if(found) count++
}
}
return count
}
fun waterRoughness(map: TileMap): Int{
val img = map.getImage()
val tileCombinations = allTileCombinations(Tile("Complete 1:\n$img"))
val maxMonstersFound = tileCombinations.map { countMonsters(it.pixels) }.max()!!
return img.count { it == '#' } - monsterPattern().size * maxMonstersFound
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 5,716 | AdventOfCode2020 | MIT License |
common/src/main/kotlin/combo/bandit/ga/BanditGeneticOperators.kt | rasros | 148,620,275 | false | null | package combo.bandit.ga
import combo.ga.SelectionOperator
import combo.math.normInvCdf
import combo.math.permutation
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sqrt
import kotlin.random.Random
class EliminationChain(vararg val eliminators: SelectionOperator<BanditCandidates>) : SelectionOperator<BanditCandidates> {
init {
require(eliminators.isNotEmpty())
}
override fun select(candidates: BanditCandidates, rng: Random): Int {
for (e in eliminators) {
val el = e.select(candidates, rng)
if (el >= 0) return el
}
return -1
}
}
/**
* This eliminates the first candidate/bandit that is proven to be significantly worse than another.
* @param alpha significance level to used to calculate z-value.
*/
class SignificanceTestElimination(alpha: Float = 0.05f) : SelectionOperator<BanditCandidates> {
init {
require(alpha > 0.0f && alpha < 1.0f)
}
val z = normInvCdf(1 - alpha / 2)
override fun select(candidates: BanditCandidates, rng: Random): Int {
var maxCI = Float.NEGATIVE_INFINITY
var minCI = Float.POSITIVE_INFINITY
val perm = permutation(candidates.nbrCandidates, rng)
for (i in perm) {
val e = candidates.estimators[candidates.instances[i]]!!
if (e.nbrWeightedSamples < candidates.minSamples) continue
val ci = z * e.standardDeviation / sqrt(e.nbrWeightedSamples)
val lower = e.mean - ci
val upper = e.mean + ci
maxCI = max(lower, maxCI)
minCI = min(upper, minCI)
if ((candidates.maximize && upper < maxCI) || (!candidates.maximize && lower > minCI))
return i // This candidate is eliminated
if ((candidates.maximize && maxCI > minCI) || (!candidates.maximize && minCI < maxCI))
break // Previous candidate is eliminated
}
if (minCI.isNaN() || maxCI.isNaN() || minCI >= maxCI) return -1
for (i in perm) {
val instance = candidates.instances[i]
val e = candidates.estimators[instance]
if (e == null || e.nbrWeightedSamples < candidates.minSamples) continue
if (candidates.maximize) {
val upper = e.mean + z * e.standardDeviation / sqrt(e.nbrWeightedSamples)
if (upper < maxCI)
return i
} else {
val lower = e.mean - z * e.standardDeviation / sqrt(e.nbrWeightedSamples)
if (lower > minCI)
return i
}
}
throw IllegalArgumentException()
}
}
/**
* This eliminates the candidate/bandit with smallest number of plays.
*/
class SmallestCountElimination : SelectionOperator<BanditCandidates> {
override fun select(candidates: BanditCandidates, rng: Random): Int {
var min = Float.POSITIVE_INFINITY
var minIx = -1
for (i in candidates.instances.indices) {
val n = candidates.estimators[candidates.instances[i]]!!.nbrWeightedSamples
if (n >= candidates.minSamples && n < min) {
min = n
minIx = i
}
}
return minIx
}
} | 0 | Kotlin | 1 | 2 | 2f4aab86e1b274c37d0798081bc5500d77f8cd6f | 3,252 | combo | Apache License 2.0 |
src/main/kotlin/Day17.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | import kotlin.reflect.KClass
fun main() {
val input = readFileAsList("Day17")
println(Day17.part1(input))
println(Day17.part2(input))
}
object Day17 {
private const val chamberWidth = 7
private val downMovementVector = Vector2d(0, -1)
fun part1(input: List<String>): Long {
val jetMovements = parseJetPattern(input)
return simulate(jetMovements, 2_022)
}
fun part2(input: List<String>): Long {
val jetMovements = parseJetPattern(input)
return simulate(jetMovements, 1_000_000_000_000)
}
private fun simulate(jetMovements: JetMovements, numberOfRocks: Long): Long {
val rockSource = RockSource()
val fallenRocks = LinkedHashSet<Rock>()
var currentRock = rockSource.next(Vector2d(2, 3))
val seen = LinkedHashMap<State, Pair<Int, Int>>()
var currentState = State(MinusRock::class, 0, listOf())
var cycleStart: State? = null
seen[currentState] = 0 to 0
while (fallenRocks.size < numberOfRocks) {
val (jetDirection, jetIndex) = jetMovements.next()
if (fallenRocks.contains(currentRock)) {
val currentHighestPoint = calculateHighestPoint(fallenRocks)
currentRock = rockSource.next(Vector2d(2, currentHighestPoint + 3))
val groupBy = fallenRocks.groupBy { it.position.x }
val sortedByDescending = groupBy
.entries
.sortedBy { it.key }
val map = sortedByDescending
.map { pointList -> pointList.value.maxBy { point -> point.position.y + point.height } }
val ceiling = map
.let {
it.map { point -> currentHighestPoint - (point.position.y + point.height) }
}
currentState = State(currentRock::class, jetIndex, ceiling)
if (seen.contains(currentState)) {
cycleStart = currentState
break
}
seen[currentState] = fallenRocks.size to currentHighestPoint
}
val isCollisionVertical = checkCollisionMany(currentRock, fallenRocks, jetDirection.vector)
if (!isCollisionVertical && jetDirection == JetDirection.LEFT && currentRock.position.x > 0) {
currentRock.position = currentRock.position + jetDirection.vector
} else if (!isCollisionVertical && jetDirection == JetDirection.RIGHT && (currentRock.position.x + currentRock.width) < chamberWidth) {
currentRock.position = currentRock.position + jetDirection.vector
}
var isCollisionDown = checkCollision(currentRock, null, downMovementVector)
if (!isCollisionDown) {
isCollisionDown = checkCollisionMany(currentRock, fallenRocks, downMovementVector)
}
if (isCollisionDown) {
fallenRocks.add(currentRock)
continue
}
currentRock.position = currentRock.position + downMovementVector
}
if (cycleStart != null) {
val (rockCountCycleStart, heightBeforeCycle) = seen[cycleStart]!!
val (rockCountCycleEnd, cycleEndHeight) = seen.values.last()
val cycleSize = rockCountCycleEnd - rockCountCycleStart + 1
val cycleHeightDiff = cycleEndHeight - heightBeforeCycle
val remainingRocks = numberOfRocks - fallenRocks.size
val cyclesRemaining = remainingRocks / cycleSize
val remainder = remainingRocks % cycleSize
val heightTroughCycles = cyclesRemaining * cycleHeightDiff
val remainderKey = seen.keys.toList()[rockCountCycleStart + remainder.toInt()]
val (_, remainderHeight) = seen[remainderKey]!!
val heightThroughRemainderRocks = remainderHeight - heightBeforeCycle
return cycleEndHeight + heightTroughCycles + heightThroughRemainderRocks
}
return calculateHighestPoint(fallenRocks).toLong()
}
private fun checkCollisionMany(
currentRock: Rock,
fallenRocks: MutableSet<Rock>,
position: Position2d
): Boolean {
var isCollision = false
for (fallenRock in fallenRocks.reversed()) {
isCollision = checkCollision(currentRock, fallenRock, position)
if (isCollision) {
break
}
}
return isCollision
}
private fun calculateHighestPoint(fallenRocks: MutableSet<Rock>): Int {
val maxByOrNull = fallenRocks.maxByOrNull { it.position.y + it.height } ?: return 0
return maxByOrNull.position.y + maxByOrNull.height
}
private fun parseJetPattern(input: List<String>): JetMovements {
val jetPattern = input[0]
.split("")
.filter { it.isNotBlank() }
.map { JetDirection.fromString(it) }
return JetMovements(jetPattern)
}
private fun checkCollision(rock: Rock, otherRock: Rock?, movementVector: Position2d): Boolean {
val nextRockVector = rock.position + movementVector
if (nextRockVector.y < 0) {
return true
}
if (otherRock == null) {
return false
}
for (rockShapeVector in rock.shape) {
for (otherRockShapeVector in otherRock.shape) {
val absoluteRockShapeVector = nextRockVector + rockShapeVector
val absoluteOtherRockShapeVector = otherRock.position + otherRockShapeVector
if (absoluteRockShapeVector distanceTo absoluteOtherRockShapeVector == 0) {
return true
}
}
}
return false
}
abstract class Rock {
abstract val shape: List<Vector2d>
abstract val width: Int
abstract val height: Int
abstract var position: Position2d
}
class MinusRock(override var position: Position2d) : Rock() {
override val width = 4
override val height = 1
override val shape = listOf(
Vector2d(0, 0),
Vector2d(1, 0),
Vector2d(2, 0),
Vector2d(3, 0),
)
}
class PlusRock(override var position: Position2d) : Rock() {
override val width = 3
override val height = 3
override val shape = listOf(
Vector2d(1, 0),
Vector2d(0, 1),
Vector2d(1, 1),
Vector2d(2, 1),
Vector2d(1, 2),
)
}
class LRock(override var position: Position2d) : Rock() {
override val width = 3
override val height = 3
override val shape = listOf(
Vector2d(0, 0),
Vector2d(1, 0),
Vector2d(2, 0),
Vector2d(2, 1),
Vector2d(2, 2),
)
}
class IRock(override var position: Position2d) : Rock() {
override val width = 1
override val height = 4
override val shape = listOf(
Vector2d(0, 0),
Vector2d(0, 1),
Vector2d(0, 2),
Vector2d(0, 3),
)
}
class BlockRock(override var position: Position2d) : Rock() {
override val width = 2
override val height = 2
override val shape = listOf(
Vector2d(0, 0),
Vector2d(0, 1),
Vector2d(1, 0),
Vector2d(1, 1),
)
}
enum class JetDirection(val vector: Vector2d) {
LEFT(Vector2d(-1, 0)),
RIGHT(Vector2d(1, 0));
companion object {
fun fromString(s: String): JetDirection {
if (s == "<") {
return LEFT
}
if (s == ">") {
return RIGHT
}
throw RuntimeException()
}
}
}
class RockSource {
private var index = 0
fun next(startingPosition: Position2d): Rock {
index++
if (index % 5 == 1) {
return MinusRock(startingPosition)
}
if (index % 5 == 2) {
return PlusRock(startingPosition)
}
if (index % 5 == 3) {
return LRock(startingPosition)
}
if (index % 5 == 4) {
return IRock(startingPosition)
}
if (index % 5 == 0) {
return BlockRock(startingPosition)
}
throw RuntimeException()
}
}
class JetMovements(private val pattern: List<JetDirection>) : Iterator<JetMovement> {
private var index = 0
override fun hasNext(): Boolean {
return true
}
override fun next(): JetMovement {
val jetDirection = pattern[index]
index++
if (index !in pattern.indices) {
index = 0
}
return JetMovement(jetDirection, index)
}
}
data class JetMovement(val direction: JetDirection, val index: Int)
data class State(val rock: KClass<out Rock>, val jetIndex: Int, val ceiling: List<Int>)
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 9,254 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | AndreiShilov | 572,661,317 | false | {"Kotlin": 25181} | import java.util.Stack
fun main() {
fun moveHead(head: Pair<Int, Int>, direction: String) =
when (direction) {
"R" -> Pair(head.first, head.second + 1)
"L" -> Pair(head.first, head.second - 1)
"U" -> Pair(head.first + 1, head.second)
"D" -> Pair(head.first - 1, head.second)
else -> throw NotImplementedError("Boom")
}
fun moveTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
if (head == tail) return tail // same spot
val i = head.first - tail.first //row
val j = head.second - tail.second //column
if (head.first == tail.first) {
if (j > 1) return Pair(tail.first, tail.second + 1)
if (j < -1) return Pair(tail.first, tail.second - 1)
}
if (head.second == tail.second) {
if (i > 1) return Pair(tail.first + 1, tail.second)
if (i < -1) return Pair(tail.first - 1, tail.second)
}
if (i > 1 && j == 1) return Pair(tail.first + 1, tail.second + 1)
if (i < -1 && j == 1) return Pair(tail.first - 1, tail.second + 1)
if (i == 1 && j > 1) return Pair(tail.first + 1, tail.second + 1)
if (i == 1 && j < -1) return Pair(tail.first + 1, tail.second - 1)
if (i > 1 && j == -1) return Pair(tail.first + 1, tail.second - 1)
if (i < -1 && j == -1) return Pair(tail.first - 1, tail.second - 1)
if (i == -1 && j > 1) return Pair(tail.first - 1, tail.second + 1)
if (i == -1 && j < -1) return Pair(tail.first - 1, tail.second - 1)
if (i > 1 && j > 1) return Pair(tail.first + 1, tail.second + 1)
if (i < -1 && j < -1) return Pair(tail.first - 1, tail.second - 1)
if (i > 1 && j < -1) return Pair(tail.first + 1, tail.second - 1)
if (i < -1 && j > 1) return Pair(tail.first - 1, tail.second + 1)
return tail
}
fun part1(input: List<String>): Int {
val tailUniquePositions = mutableSetOf<Pair<Int, Int>>()
var head = Pair(0, 0)
var tail = Pair(0, 0)
tailUniquePositions.add(tail)
for (line in input) {
val (direction, distance) = line.split(" ")
val dInt = distance.toInt()
repeat(dInt) {
head = moveHead(head, direction)
tail = moveTail(head, tail)
tailUniquePositions.add(tail)
}
}
println(tailUniquePositions.size)
return tailUniquePositions.size
}
fun part2(input: List<String>): Int {
val tailUniquePositions = mutableSetOf<Pair<Int, Int>>()
val rope = List(10) { Pair(0, 0) }.toMutableList()
for (line in input) {
val (direction, distance) = line.split(" ")
val dInt = distance.toInt()
println("Times $dInt")
repeat(dInt) {
rope[0] = moveHead(rope[0], direction)
for (i in 0 until rope.size - 1) {
val tail = rope[i + 1]
rope[i + 1] = moveTail(rope[i], tail)
}
tailUniquePositions.add(rope.last())
}
println(rope)
}
return tailUniquePositions.size
}
// test if implementation meets criteria from the description, like:
check(part1(readInput("Day09_test")) == 13)
check(part2(readInput("Day09_test")) == 1)
check(part2(readInput("Day09_test_extended")) == 36)
val input = readInput("Day09")
println("Part 1 = ${part1(input)}")
println("Part 2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 852b38ab236ddf0b40a531f7e0cdb402450ffb9a | 3,621 | aoc-2022 | Apache License 2.0 |
src/day17/Day17.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day17
import Runner
import kotlin.math.max
import kotlin.math.min
fun main() {
Day17Runner().solve()
}
class Day17Runner : Runner<Long>(
day = 17,
expectedPartOneTestAnswer = 3068,
expectedPartTwoTestAnswer = 1514285714288
) {
override fun partOne(input: List<String>, test: Boolean): Long {
val directions = jetDirections(input)
val shapes = RockShapeType.values().map { type -> type.toRockShape() }
return dropRocks(
number = 2022,
shapes = shapes,
directions = directions
).sum() + 1
}
private fun dropRocks(
number: Int,
shapes: List<RockShape>,
directions: List<JetDirection>
) : List<Long> {
val cave = Cave()
val heightIncreases = mutableListOf<Long>()
var jetNumber = 0
repeat(number) { rockNumber ->
val shape = shapes[rockNumber % shapes.size]
var fallingRock = shape.toFallingRock(cave.rockStartingHeight())
do {
val direction = directions[jetNumber % directions.size]
fallingRock = fallingRock.fall()
if (cave.rockCanBePushed(fallingRock, direction)) {
fallingRock = fallingRock.push(direction)
}
jetNumber++
} while (cave.rockCanFall(fallingRock))
val currentHeight = cave.highestRock() ?: 0
cave.addFallenRock(fallingRock)
val newHeight = cave.highestRock()!!
heightIncreases.add(newHeight - currentHeight)
}
return heightIncreases
}
override fun partTwo(input: List<String>, test: Boolean): Long {
val directions = jetDirections(input)
val shapes = RockShapeType.values().map { type -> type.toRockShape() }
val initialHeightIncreases = dropRocks(
number = 10000,
shapes = shapes,
directions = directions
)
val totalRocks = 1000000000000
val commonSequence = initialHeightIncreases.findCommonHeightSequence()
val sequenceCountForTotalRocks = totalRocks / commonSequence.sequence.length
val rocksRemainingAfterLastSequence = (totalRocks - commonSequence.startIndex) % sequenceCountForTotalRocks
val overallSequenceScore = sequenceCountForTotalRocks * commonSequence.sequence.map { c -> c.toString().toLong() }.sum()
val beforeFirstSequenceScore = initialHeightIncreases.subList(0, commonSequence.startIndex).sum()
val remainingPartialSequence = commonSequence.sequence.substring(0, rocksRemainingAfterLastSequence.toInt())
val afterLastFullSequenceScore = remainingPartialSequence.map { c -> c.toString().toLong() }.sum() + 1
return beforeFirstSequenceScore + overallSequenceScore + afterLastFullSequenceScore
}
/*
* Mostly a fluke?
*
* Both the test and input data do not have a repeating sequence initially, so reverse the string and attempt
* to find a repeating sequence by comparing a substring to splits of the overall string, if more than one substring
* is found within the splits the sequence repeats.
*
* This only works when the initial generated number of rock falls is >= ~5400, unsure why
*/
private fun List<Long>.findCommonHeightSequence() : CommonHeightSequence = joinToString("").let { source ->
val reversed = source.reversed()
var currentIndex = source.length
var substring = reversed.substring(0, currentIndex)
var windowed = reversed.windowed(substring.length, substring.length)
var found = windowed.count { it == substring }
while (found < 2) {
substring = reversed.substring(0, currentIndex)
windowed = reversed.windowed(substring.length, substring.length)
found = windowed.count { it == substring }
if (found < 2) {
currentIndex--
}
}
val startIndex = source.length - found * substring.length
return CommonHeightSequence(
sequence = substring.reversed(),
startIndex = startIndex
)
}
private fun Cave.rockStartingHeight() : Long {
return highestRock()
?.let { height -> height + 5 }
?: 4
}
private fun Cave.highestRock() : Long? {
val lastStacks = stacks.mapNotNull { stack ->
stack.lastOrNull { space -> space is Rock }?.y?.toLong()
}
return lastStacks.maxOrNull()
}
private fun Cave.addFallenRock(rock: FallingRock) {
val toFill = rock.spacesToFill()
toFill.forEach { space ->
val currentSpace = stacks[space.x].getOrNull(space.y)
when {
currentSpace == null -> stacks[space.x].add(space)
space is Rock -> stacks[space.x][space.y] = space
!(space is Empty && currentSpace is Rock) -> stacks[space.x][space.y] = space
}
}
}
private fun FallingRock.spacesToFill() : List<Space> {
fun fill(verticalSpace: Int) : List<Space> = buildList {
repeat(7) { x ->
val yMin = area.minOf { rock -> rock.y }
(yMin..yMin + verticalSpace).forEach { y ->
add(area.get(x = x, y = y) ?: Empty(x = x, y = y))
}
}
}
return when (type) {
RockShapeType.Horizontal -> fill(0)
RockShapeType.Cross -> fill(2)
RockShapeType.Corner -> fill(2)
RockShapeType.Vertical -> fill(3)
RockShapeType.Square -> fill(1)
}
}
private fun List<Rock>.get(x: Int, y: Int) : Rock? {
return firstOrNull { rock -> rock.x == x && rock.y == y }
}
private fun FallingRock.push(direction: JetDirection) : FallingRock {
val newArea = when (direction) {
JetDirection.Left -> {
val xMin = area.minOf { rock -> rock.x }
if (xMin > 0) {
area.map { rock ->
rock.copy(x = rock.x - 1, y = rock.y )
}
} else {
area
}
}
JetDirection.Right -> {
val xMax = area.maxOf { rock -> rock.x }
if (xMax < 6) {
area.map { rock ->
rock.copy(x = rock.x + 1, y = rock.y)
}
} else {
area
}
}
}
return FallingRock(area = newArea, type = type)
}
private fun FallingRock.fall() : FallingRock {
return FallingRock(
area = area.map { rock ->
rock.copy(x = rock.x , y = rock.y - 1)
},
type = type
)
}
private fun RockShape.toFallingRock(startingHeight: Long) : FallingRock {
return FallingRock(
area = area.map { rock ->
rock.copy(
x = rock.x + 2,
y = rock.y + startingHeight.toInt()
)
}.toMutableList(),
type = type
)
}
private fun Cave.rockCanFall(rock: FallingRock) : Boolean {
return rock.area.fold(true) { acc, r ->
if (!acc) {
false
} else {
if (r.y == 0) {
false
} else {
getSpace(x = r.x, y = r.y - 1)?.let { space -> space is Empty } ?: true
}
}
}
}
private fun Cave.rockCanBePushed(rock: FallingRock, nextDirection: JetDirection) : Boolean {
return rock.area.fold(true) { acc, r ->
val nextX = when (nextDirection) {
JetDirection.Left -> max(0, r.x - 1)
JetDirection.Right -> min(6, r.x + 1)
}
if (!acc) {
false
} else {
getSpace(x = nextX, y = r.y)?.let { space -> space is Empty } ?: true
}
}
}
private fun Cave.getSpace(x: Int, y: Int) : Space? {
return stacks[x].getOrNull(y)
}
private fun jetDirections(input: List<String>) : List<JetDirection> {
return input.first().map { c ->
when (c) {
'<' -> JetDirection.Left
'>' -> JetDirection.Right
else -> throw RuntimeException()
}
}
}
private fun RockShapeType.toRockShape() : RockShape {
return RockShape(
area = when (this) {
RockShapeType.Horizontal -> {
buildList {
add(Rock(x = 0, y = 0))
add(Rock(x = 1, y = 0))
add(Rock(x = 2, y = 0))
add(Rock(x = 3, y = 0))
}
}
RockShapeType.Cross -> {
buildList {
add(Rock(x = 1, y = 0))
add(Rock(x = 0, y = 1))
add(Rock(x = 1, y = 1))
add(Rock(x = 2, y = 1))
add(Rock(x = 1, y = 2))
}
}
RockShapeType.Corner -> {
buildList {
add(Rock(x = 0, y = 0))
add(Rock(x = 1, y = 0))
add(Rock(x = 2, y = 0))
add(Rock(x = 2, y = 1))
add(Rock(x = 2, y = 2))
}
}
RockShapeType.Vertical -> {
buildList {
add(Rock(x = 0, y = 0))
add(Rock(x = 0, y = 1))
add(Rock(x = 0, y = 2))
add(Rock(x = 0, y = 3))
}
}
RockShapeType.Square -> {
buildList {
add(Rock(x = 0, y = 0))
add(Rock(x = 1, y = 0))
add(Rock(x = 0, y = 1))
add(Rock(x = 1, y = 1))
}
}
},
type = this
)
}
}
enum class JetDirection {
Left, Right
}
enum class RockShapeType {
Horizontal, Cross, Corner, Vertical, Square
}
data class FallingRock(
val area: List<Rock>,
val type: RockShapeType
)
data class RockShape(
val area : List<Rock>,
val type: RockShapeType
)
sealed class Space(
open val x: Int,
open val y: Int
)
data class Rock(
override val x: Int,
override val y: Int
) : Space(x = x, y = y)
data class Empty(
override val x: Int,
override val y: Int
) : Space(x = x, y = y)
data class CommonHeightSequence(
val sequence: String,
val startIndex: Int
)
data class Cave(
val stacks: List<MutableList<Space>> = buildList { repeat(7) { add(mutableListOf()) } }
) | 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 11,100 | advent-of-code | Apache License 2.0 |
src/main/kotlin/g1901_2000/s1916_count_ways_to_build_rooms_in_an_ant_colony/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1901_2000.s1916_count_ways_to_build_rooms_in_an_ant_colony
// #Hard #Dynamic_Programming #Math #Tree #Graph #Topological_Sort #Combinatorics
// #2023_06_20_Time_2564_ms_(100.00%)_Space_94.2_MB_(100.00%)
import java.math.BigInteger
class Solution {
private lateinit var graph: Array<MutableList<Int>?>
private lateinit var fact: LongArray
fun waysToBuildRooms(prevRoom: IntArray): Int {
val n = prevRoom.size
graph = Array(n) { mutableListOf<Int>() }
fact = LongArray(prevRoom.size + 10)
fact[1] = 1
fact[0] = fact[1]
for (i in 2 until fact.size) {
fact[i] = fact[i - 1] * i
fact[i] %= MOD.toLong()
}
for (i in 1 until prevRoom.size) {
val pre = prevRoom[i]
graph[pre]?.add(i)
}
val res = dfs(0)
return (res[1] % MOD).toInt()
}
private fun dfs(root: Int): LongArray {
val res = longArrayOf(1, 0)
var cnt = 0
val list: MutableList<LongArray> = ArrayList()
for (next in graph[root]!!) {
val v = dfs(next)
cnt += v[0].toInt()
list.add(v)
}
res[0] += cnt.toLong()
var com: Long = 1
for (p in list) {
val choose = c(cnt, p[0].toInt())
cnt -= p[0].toInt()
com = com * choose
com %= MOD.toLong()
com = com * p[1]
com %= MOD.toLong()
}
res[1] = com
return res
}
private fun c(i: Int, j: Int): Long {
val mod: Long = 1000000007
val prevRoom = fact[i]
val b = fact[i - j] % mod * (fact[j] % mod) % mod
val value = BigInteger.valueOf(b)
val binverse = value.modInverse(BigInteger.valueOf(mod)).toLong()
return prevRoom * (binverse % mod) % mod
}
companion object {
private const val MOD = 1000000007
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,936 | LeetCode-in-Kotlin | MIT License |
2022/src/test/kotlin/Day21.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import kotlin.reflect.KFunction
private sealed interface Monkey21 {
var monkeys: Map<String, Monkey21>
val yell: Long
}
private data class NumMonkey21(val num: Long) : Monkey21 {
override lateinit var monkeys: Map<String, Monkey21>
override val yell = num
}
private data class OpMonkey21(val name1: String, val name2: String, val op: (Long, Long) -> Long) : Monkey21 {
override lateinit var monkeys: Map<String, Monkey21>
override val yell by lazy { op(monkeys[name1]!!.yell, monkeys[name2]!!.yell) }
fun revertYell(yell: Long, num: Long, r: Boolean = false) = when ((op as KFunction<*>).name) {
"plus" -> yell - num
"minus" -> if (r) yell + num else num - yell
"times" -> yell / num
"div" -> if (r) yell * num else num / yell
else -> throw IllegalStateException()
}
}
class Day21 : StringSpec({
"puzzle part 01" {
val monkeys = getMonkeys()
monkeys.onEach { it.value.monkeys = monkeys }
val number = monkeys["root"]!!.yell
number shouldBe 145167969204648
}
"puzzle part 02" {
val monkeys = getMonkeys()
monkeys.onEach { it.value.monkeys = monkeys }
val root = monkeys["root"]!! as OpMonkey21
val name = if (monkeys.hasHuman(root.name1)) root.name1 else root.name2
val number = root.revertYell(root.yell, monkeys[name]!!.yell)
val humanYell = monkeys.findHuman(monkeys[name]!!, number)
humanYell shouldBe 3330805295850
}
})
private fun Map<String, Monkey21>.findHuman(monkey: Monkey21, yell: Long): Long {
if (monkey !is OpMonkey21) throw IllegalStateException()
val name1HasHuman = this.hasHuman(monkey.name1)
val name = if (name1HasHuman) monkey.name1 else monkey.name2
val otherYell = this[if (name1HasHuman) monkey.name2 else monkey.name1]!!.yell
val number = monkey.revertYell(yell, otherYell, name1HasHuman)
if (name == "humn") return number
return findHuman(this[name]!!, number)
}
private fun Map<String, Monkey21>.hasHuman(name: String): Boolean {
if (name == "humn") return true
return when (val monkey = this[name]!!) {
is OpMonkey21 -> hasHuman(monkey.name1) || hasHuman(monkey.name2)
is NumMonkey21 -> false
}
}
private fun getMonkeys() = getPuzzleInput("day21-input.txt")
.map {
val s = it.split(": ")
val name = s.first()
val num = s.last().toLongOrNull()
if (num != null)
name to NumMonkey21(num)
else {
val op = it[11]
val s1 = s.last().split(' ')
when (op) {
'+' -> name to OpMonkey21(s1.first(), s1.last(), Long::plus)
'-' -> name to OpMonkey21(s1.first(), s1.last(), Long::minus)
'*' -> name to OpMonkey21(s1.first(), s1.last(), Long::times)
'/' -> name to OpMonkey21(s1.first(), s1.last(), Long::div)
else -> throw IllegalArgumentException(op.toString())
}
}
}
.toMap()
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 3,119 | adventofcode | MIT License |
src/main/kotlin/de/nilsdruyen/aoc/Day04.kt | nilsjr | 571,758,796 | false | {"Kotlin": 15971} | package de.nilsdruyen.aoc
fun main() {
fun part1(input: List<String>): Int = input.toPairRanges().count { ranges ->
val firstInSecond = ranges.first.all { it in ranges.second }
val secondInFirst = ranges.second.all { it in ranges.first }
firstInSecond || secondInFirst
}
fun part2(input: List<String>): Int = input.toPairRanges().count { ranges ->
ranges.first.any { it in ranges.second }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input)) // 444
println(part2(input)) // 801
}
private fun List<String>.toPairRanges(): List<Pair<IntRange, IntRange>> {
return map {
val (firstPair, secondPair) = it.split(",")
val (from1, to1) = firstPair.split("-").map(String::toInt)
val (from2, to2) = secondPair.split("-").map(String::toInt)
val rangeOne = from1..to1
val rangeTwo = from2..to2
rangeOne to rangeTwo
}
} | 0 | Kotlin | 0 | 0 | 1b71664d18076210e54b60bab1afda92e975d9ff | 1,080 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2020/Day21.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2020
import com.nibado.projects.advent.*
object Day21 : Day {
private val values = resourceRegex(2020, 21, "([a-z ]+) \\(contains ([a-z, ]+)\\)").map { (_, ing, all) ->
ing.split(" ").toSet() to all.split(", ").toSet()
}
private val allergens : Map<String, String> by lazy {
val allergens = values.flatMap { (_,a) -> a }.toSet()
val allergenMap = allergens.map { allergen ->
allergen to values.filter { (_,a) ->a.contains(allergen) }.map { (i) -> i }.reduce { a, b -> a.intersect(b) }
}.toMap().toMutableMap()
while(allergenMap.any { it.value.size > 1 }) {
allergenMap.filter { it.value.size == 1 }.forEach { (_, single) ->
allergenMap.filter { it.value.size > 1 }.forEach { (a, _) ->
allergenMap[a] = allergenMap[a]!! - single
}
}
}
allergenMap.map { (a, i) -> a to i.first() }.toMap()
}
override fun part1() : Int {
val safe = values.flatMap { it.first }.toSet() - allergens.map { it.value }
return values.flatMap { it.first.map { if(safe.contains(it)) 1 else 0 } }.sum()
}
override fun part2() : String = allergens.entries.sortedBy { (a, _) -> a }.joinToString(",") { (_, i) -> i}
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,315 | adventofcode | MIT License |
src/main/kotlin/net/voldrich/aoc2021/Day11.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2021
import net.voldrich.BaseDay
import kotlin.math.max
import kotlin.math.min
// link to task
fun main() {
Day11().run()
}
class Day11 : BaseDay() {
override fun task1() : Int {
val inputNums = input.lines().map { line -> line.trim().toCharArray().map { it.digitToInt() }.toMutableList() }.toMutableList()
val grid = OctopusGrid(inputNums)
return (1..100).sumOf { grid.simulateFlashStep() }
}
override fun task2() : Int {
val inputNums = input.lines().map { line -> line.trim().toCharArray().map { it.digitToInt() }.toMutableList() }.toMutableList()
val grid = OctopusGrid(inputNums)
var step = 1
while (grid.simulateFlashStep() != grid.totalOctopusCount()) {
step++
}
return step
}
class OctopusGrid(private val grid: MutableList<MutableList<Int>>) {
private val sx = grid.size
private val sy = grid[0].size
fun simulateFlashStep() : Int {
val flashedPoints = HashSet<Point>()
for (y in 0 until sx) {
for (x in 0 until sy) {
testFlash(y,x, flashedPoints)
}
}
flashedPoints.forEach {
grid[it.y][it.x] = 0
}
return flashedPoints.size
}
private fun testFlash(y: Int, x : Int, flashedPoints : HashSet<Point>) {
val p = Point(y,x)
if (flashedPoints.contains(p)) {
return
}
grid[y][x] += 1
if (grid[y][x] > 9) {
flash(p, flashedPoints)
}
}
private fun flash(point: Point, flashedPoints : HashSet<Point>) {
flashedPoints.add(point)
for (y in max(point.y - 1, 0) .. min(point.y + 1, sy - 1)) {
for (x in max(point.x - 1, 0) .. min(point.x + 1, sx - 1)) {
testFlash(y,x, flashedPoints)
}
}
}
fun totalOctopusCount(): Int {
return sx * sy
}
}
data class Point(val y: Int, val x: Int)
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 2,159 | advent-of-code | Apache License 2.0 |
src/main/day2/Day02.kt | Derek52 | 572,850,008 | false | {"Kotlin": 22102} | package main.day2
import main.readInput
fun main() {
val input = readInput("day2/day2")
//testAlg()
val firstHalf = false
if (firstHalf) {
println(part1(input))
} else {
println(part2(input))
}
}
fun part1(input: List<String>) : Int {
var opponent = Throw.ROCK
var me = Throw.ROCK
var score = 0
for (line in input) {
val opponentThrow = line[0]
val meThrow = line[2]
opponent = when (opponentThrow) {
'A' -> Throw.ROCK
'B' -> Throw.PAPER
else -> Throw.SCISSORS
}
me = when (meThrow) {
'X' -> Throw.ROCK
'Y' -> Throw.PAPER
else -> Throw.SCISSORS
}
if (me == opponent) {
score += 3
} else if ((me.value-1 == opponent.value) || (me == Throw.ROCK && opponent == Throw.SCISSORS)) {
score += 6
}
score += when (me) {
Throw.ROCK -> 1
Throw.PAPER -> 2
Throw.SCISSORS -> 3
}
}
return score
}
enum class Throw(val value: Int) {
ROCK(1), PAPER(2), SCISSORS(3)
}
enum class Strategy(val points: Int) {
LOSE(0), DRAW(3), WIN(6)
}
fun part2(input: List<String>) : Int {
var strat = Strategy.LOSE
var opponentThrow = Throw.ROCK
var myThrow = Throw.ROCK
var score = 0
for (line in input) {
val opponent = line[0]
val me = line[2]
opponentThrow = when (opponent) {
'A' -> Throw.ROCK
'B' -> Throw.PAPER
else -> Throw.SCISSORS
}
strat = when (me) {
'X' -> Strategy.LOSE
'Y' -> Strategy.DRAW
else -> Strategy.WIN
}
score += strat.points
when(strat) {
Strategy.LOSE -> myThrow = getLoser(opponentThrow)
Strategy.DRAW -> myThrow = opponentThrow
Strategy.WIN -> myThrow = getWinner(opponentThrow)
}
score += myThrow.value
}
return score
}
fun getWinner(pick: Throw) : Throw {
return when (pick) {
Throw.ROCK -> Throw.PAPER
Throw.PAPER -> Throw.SCISSORS
Throw.SCISSORS -> Throw.ROCK
}
}
fun getLoser(pick: Throw) : Throw {
return when (pick) {
Throw.ROCK -> Throw.SCISSORS
Throw.PAPER -> Throw.ROCK
Throw.SCISSORS -> Throw.PAPER
}
}
fun testAlg() {
//tests part 1.
val a = listOf<String>("A X")
val b = listOf<String>("A Y")
val c = listOf<String>("A Z")
val d = listOf<String>("B X")
val e = listOf<String>("B Y")
val f = listOf<String>("B Z")
val g = listOf<String>("C X")
val h = listOf<String>("C Y")
val i = listOf<String>("C Z")
println("Part1(${a[0]}) = ${part1(a)} should be 4")
println("Part1(${b[0]}) = ${part1(b)} should be 8")
println("Part1(${c[0]}) = ${part1(c)} should be 3")
println("Part1(${d[0]}) = ${part1(d)} should be 1")
println("Part1(${e[0]}) = ${part1(e)} should be 3")
println("Part1(${f[0]}) = ${part1(f)} should be 9")
println("Part1(${g[0]}) = ${part1(g)} should be 7")
println("Part1(${h[0]}) = ${part1(h)} should be 2")
println("Part1(${i[0]}) = ${part1(i)} should be 6")
} | 0 | Kotlin | 0 | 0 | c11d16f34589117f290e2b9e85f307665952ea76 | 3,260 | 2022AdventOfCodeKotlin | Apache License 2.0 |
src/year2022/23/Day23.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`23`
import java.util.Collections
import readInput
data class Point(
val x: Int,
val y: Int
)
enum class Direction {
N, S, W, E,
NE, NW, SE, SW
}
fun parseInput(input: List<String>): Set<Point> {
return input.mapIndexed { y, line ->
line.split("")
.filter { it.isNotEmpty() }
.mapIndexedNotNull { x, cell ->
if (cell == "#") {
Point(x, y)
} else {
null
}
}
}
.flatten()
.toSet()
}
fun Point.calculateNewPosition(
direction: Direction
): Point {
return when (direction) {
Direction.N -> Point(y = y - 1, x = x)
Direction.S -> Point(y = y + 1, x = x)
Direction.W -> Point(y = y, x = x - 1)
Direction.E -> Point(y = y, x = x + 1)
Direction.NE -> Point(y = y - 1, x = x + 1)
Direction.NW -> Point(y = y - 1, x = x - 1)
Direction.SE -> Point(y = y + 1, x = x + 1)
Direction.SW -> Point(y = y + 1, x = x - 1)
}
}
fun Point.proposeMovement(direction: Direction): Point {
return when (direction) {
Direction.N, Direction.S, Direction.W, Direction.E -> calculateNewPosition(direction)
else -> error("!! Illegal direction $direction")
}
}
fun processElf(
grid: Set<Point>,
elf: Point,
listOfMovements: List<Pair<List<Direction>, Direction>>
): Point? {
/**
* If all points around current are empty - just don't move
*/
if (Direction.values().all { elf.calculateNewPosition(it) !in grid }) return null
/**
* Find new direction to move
*/
val newDir = listOfMovements.firstOrNull { (checkDirections, _) ->
checkDirections.all { elf.calculateNewPosition(it) !in grid }
}?.second
return if (newDir == null) {
null
} else {
elf.proposeMovement(newDir)
}
}
fun processRount(
points: Set<Point>,
listOfMovements: List<Pair<List<Direction>, Direction>>
): Set<Point> {
/**
* Part 1 of round
* Create set of not moving points and map of proposed movements
*/
val finalPointsPosition = mutableSetOf<Point>()
val proposedMovingPointMap = mutableMapOf<Point, MutableList<Point>>()
points.forEach { currentElf ->
val proposedPoint = processElf(points, currentElf, listOfMovements)
if (proposedPoint == null) {
finalPointsPosition.add(currentElf)
} else {
if (proposedMovingPointMap.containsKey(proposedPoint)) {
proposedMovingPointMap[proposedPoint]!!.add(currentElf)
} else {
proposedMovingPointMap[proposedPoint] = mutableListOf(currentElf)
}
}
}
/**
* Part 2 of round
* If points proposed positions collapses - just don't move them
*/
proposedMovingPointMap.forEach { (proposedPoint, prevPoints) ->
when (prevPoints.size) {
0 -> error("Illegal state $proposedPoint $prevPoints")
1 -> finalPointsPosition.add(proposedPoint)
else -> finalPointsPosition.addAll(prevPoints)
}
}
return finalPointsPosition
}
/**
* Helper method to print grid of all points in current set
*/
fun Set<Point>.printGrid() {
val minX = minOf { it.x }
val minY = minOf { it.y }
val maxX = maxOf { it.x }
val maxY = maxOf { it.y }
(minY..maxY).forEach { y ->
(minX..maxX).forEach { x ->
val pointToPrint = if (Point(x, y) in this) {
"#"
} else {
"."
}
print(pointToPrint)
}
println()
}
println()
}
fun Set<Point>.countAnswer(): Int {
val minX = minOf { it.x }
val minY = minOf { it.y }
val maxX = maxOf { it.x }
val maxY = maxOf { it.y }
val xWidth = maxX - minX + 1
val yHeight = maxY - minY + 1
return xWidth * yHeight - count()
}
private fun createInitialListOfDirections(): MutableList<Pair<List<Direction>, Direction>> {
return mutableListOf(
listOf(Direction.N, Direction.NE, Direction.NW) to Direction.N,
listOf(Direction.S, Direction.SE, Direction.SW) to Direction.S,
listOf(Direction.W, Direction.NW, Direction.SW) to Direction.W,
listOf(Direction.E, Direction.NE, Direction.SE) to Direction.E
)
}
fun main() {
fun part1(input: List<String>): Int {
val listOfMovements = createInitialListOfDirections()
var currentGrid = parseInput(input)
repeat(10) {
currentGrid = processRount(currentGrid, listOfMovements)
Collections.rotate(listOfMovements, -1)
}
return currentGrid.countAnswer()
}
fun part2(input: List<String>): Int {
var currentGrid = parseInput(input)
var prevGrid: Set<Point> = emptySet()
var count = 0
val listOfMovements = createInitialListOfDirections()
while (currentGrid != prevGrid) {
prevGrid = currentGrid
currentGrid = processRount(currentGrid, listOfMovements)
Collections.rotate(listOfMovements, -1)
count++
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day23_test")
val part1Test = part1(testInput)
val part2Test = part2(testInput)
println(part1Test)
check(part1Test == 110)
println(part2Test)
check(part2Test == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 5,621 | KotlinAdventOfCode | Apache License 2.0 |
src/main/kotlin/suggestions/KtSuggestions.kt | hermannhueck | 46,933,495 | false | {"Java": 53536, "Scala": 43388, "Kotlin": 4114} | @file:JvmName("KtSuggestions")
package suggestions
private val MAX_WORDS = 13
private data class Suggestion(val text: String) {
override fun toString() = text
}
private val INPUT = listOf("The", "moon", "is", "not", "a", "planet", "and", "also", "not", "a", "star", ".",
"But", ",", "I", "digress", "we", "people", "are", "so", "irrational", ".")
private val STOPWORDS = setOf("The", "a", "is")
fun main(args: Array<String>) {
makeSuggestions(maxWords(args), INPUT, STOPWORDS).forEach(::println)
}
private fun maxWords(args: Array<String>): Int {
if (args.isEmpty())
return MAX_WORDS
try {
val maxWords = Integer.parseInt(args[0])
return if (maxWords < 1) 1 else maxWords
} catch (e: NumberFormatException) {
return MAX_WORDS
}
}
private fun makeSuggestions(maxWords: Int,
words: List<String>,
stopWords: Set<String>): List<Suggestion> {
val purged = words
.filter { e -> !stopWords.contains(e) }
.filter { e -> e.matches("\\w+".toRegex()) }
val maxWords2 = if (maxWords > purged.size) purged.size else maxWords
println("----- maxWords = " + maxWords2)
println("----- purged.size = " + purged.size)
println("----- purged = " + purged)
return suggestions(maxWords2, purged)
.map(::Suggestion)
}
private fun suggestions(maxWords: Int, words: List<String>): MutableList<String> {
var suggestions = mutableListOf<String>()
for (i in 0..words.size - maxWords + 1 - 1) {
suggestions.addAll(combinations(i, words, maxWords))
}
return suggestions
}
private fun combinations(index: Int, words: List<String>, maxWords: Int): List<String> {
var combinations = mutableListOf<String>()
for (i in 0..maxWords - 1) {
val word = words[index + i]
val newWord = if (i == 0) word else combinations[i - 1] + " " + word
combinations.add(newWord)
}
return combinations
}
| 0 | Java | 0 | 0 | 4ff6af70ecec5847652fb593b9d70cde7db5256d | 2,006 | BrainTwisters | Apache License 2.0 |
src/main/kotlin/aoc2023/Day15.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2023
import AoCDay
import util.illegalInput
// https://adventofcode.com/2023/day/15
object Day15 : AoCDay<Int>(
title = "Lens Library",
part1ExampleAnswer = 1320,
part1Answer = 495972,
part2ExampleAnswer = 145,
part2Answer = 245223,
) {
private fun hash(string: String) = string.fold(initial = 0) { cur, char -> ((cur + char.code) * 17) and 0xFF }
private sealed interface Step {
val lensLabel: String
class Remove(override val lensLabel: String) : Step
class ReplaceOrAdd(override val lensLabel: String, val lensFocalLength: Int) : Step
}
private fun parseStep(input: String) = when (val last = input.last()) {
'-' -> Step.Remove(lensLabel = input.dropLast(1))
in '1'..'9' -> {
if (input[input.length - 2] != '=') illegalInput(input)
Step.ReplaceOrAdd(lensLabel = input.dropLast(2), lensFocalLength = last - '0')
}
else -> illegalInput(input)
}
override fun part1(input: String) = input.split(',').sumOf(::hash)
override fun part2(input: String): Int {
val boxes = List(256) { LinkedHashMap<String, Int>() }
for (step in input.split(',').map(::parseStep)) {
val box = boxes[hash(step.lensLabel)]
when (step) {
is Step.Remove -> box.remove(step.lensLabel)
is Step.ReplaceOrAdd -> box[step.lensLabel] = step.lensFocalLength
}
}
return boxes.withIndex().sumOf { (boxIndex, box) ->
box.values.withIndex().sumOf { (lensIndex, lensFocalLength) ->
(boxIndex + 1) * (lensIndex + 1) * lensFocalLength
}
}
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 1,699 | advent-of-code-kotlin | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem124/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem124
import com.hj.leetcode.kotlin.common.model.TreeNode
/**
* LeetCode page: [124. Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/description/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(H) where N and H are the number of nodes and height of root;
*/
fun maxPathSum(root: TreeNode?): Int {
return root?.let {
var maxPathSum = it.`val`
postOrderTraversal(it) { subTreePathSum ->
maxPathSum = maxOf(maxPathSum, subTreePathSum.maxIncludeRoot)
}
maxPathSum
} ?: throw IllegalArgumentException()
}
private fun postOrderTraversal(
root: TreeNode,
sideEffect: (subTreePathSum: TreePathSum) -> Unit
): TreePathSum {
return if (root.isLeaf()) {
TreePathSum(root.`val`, root.`val`)
} else {
val leftPathSum = root.left?.let { postOrderTraversal(it, sideEffect) }
val rightPathSum = root.right?.let { postOrderTraversal(it, sideEffect) }
val maxEndAtRoot = root.`val` + maxOf(
0,
leftPathSum?.maxEndAtRoot ?: 0,
rightPathSum?.maxEndAtRoot ?: 0
)
val maxIncludeRoot = maxOf(
maxEndAtRoot, root.`val` + (leftPathSum?.maxEndAtRoot ?: 0) + (rightPathSum?.maxEndAtRoot ?: 0)
)
TreePathSum(maxEndAtRoot, maxIncludeRoot)
}.also(sideEffect)
}
private data class TreePathSum(val maxEndAtRoot: Int, val maxIncludeRoot: Int)
private fun TreeNode.isLeaf() = left == null && right == null
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,692 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day05.kt | timlam9 | 573,013,707 | false | {"Kotlin": 9410} | import java.util.*
fun main() {
fun part1(input: List<String>): String {
val stacks = List(9) {
Stack<Char>()
}
input.take(8).reversed().map { line ->
line.forEachIndexed { index, char ->
if (char.isLetter()) {
stacks[index / 4].push(char)
}
}
}
input.drop(10).map { line ->
line.split(" ").mapIndexedNotNull { index, command -> if (index % 2 != 0) command.toInt() else null }
}.forEach { (move, from, to) ->
repeat(move) {
stacks[to - 1].push(stacks[from - 1].pop())
}
}
return stacks.joinToString("") { it.peek().toString() }
}
fun part2(input: List<String>): String {
val stacks = List(9) {
Stack<Char>()
}
input.take(8).reversed().map { line ->
line.forEachIndexed { index, char ->
if (char.isLetter()) {
stacks[index / 4].push(char)
}
}
}
input.drop(10).map { line ->
line.split(" ").mapIndexedNotNull { index, command -> if (index % 2 != 0) command.toInt() else null }
}.forEach { (move, from, to) ->
val tempStack = Stack<Char>()
repeat(move) {
tempStack.push(stacks[from - 1].pop())
}
tempStack.reversed().forEach {
stacks[to - 1].push(it)
}
}
return stacks.joinToString("") { it.peek().toString() }
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 7971bea39439b363f230a44e252c7b9f05a9b764 | 1,683 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day15.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
import utils.Bounds
import utils.Coordinates
import kotlin.math.absoluteValue
import kotlin.system.measureTimeMillis
val parseSensor = "Sensor at x=([-\\d]+), y=([-\\d]+): closest beacon is at x=([-\\d]+), y=([-\\d]+)".toRegex()
class Sensor(val pos: Coordinates, val beacon: Coordinates) {
val distance = (beacon - pos).length()
fun projectToRow(y: Int): IntRange? {
val distanceToRow = (pos.y - y).absoluteValue
val projectedWidth = distance - distanceToRow
if (projectedWidth < 0) { return null }
return IntRange(pos.x - projectedWidth, pos.x + projectedWidth)
}
fun covers(other: Coordinates) =
(other - pos).length() <= distance
fun justOutOfRange(): Sequence<Coordinates> = sequence {
val extent = distance + 1
for(x in 0..extent) {
yield(pos + Coordinates(x, extent - x))
yield(pos + Coordinates(x, x- extent ))
yield(pos + Coordinates(-x, extent - x))
yield(pos + Coordinates(-x, x- extent ))
}
}
}
fun main() {
val testInput = """Sensor at x=2, y=18: closest beacon is at x=-2, y=15
Sensor at x=9, y=16: closest beacon is at x=10, y=16
Sensor at x=13, y=2: closest beacon is at x=15, y=3
Sensor at x=12, y=14: closest beacon is at x=10, y=16
Sensor at x=10, y=20: closest beacon is at x=10, y=16
Sensor at x=14, y=17: closest beacon is at x=10, y=16
Sensor at x=8, y=7: closest beacon is at x=2, y=10
Sensor at x=2, y=0: closest beacon is at x=2, y=10
Sensor at x=0, y=11: closest beacon is at x=2, y=10
Sensor at x=20, y=14: closest beacon is at x=25, y=17
Sensor at x=17, y=20: closest beacon is at x=21, y=22
Sensor at x=16, y=7: closest beacon is at x=15, y=3
Sensor at x=14, y=3: closest beacon is at x=15, y=3
Sensor at x=20, y=1: closest beacon is at x=15, y=3""".split("\n")
fun part1(input: List<String>, row: Int = 10): Int {
val sensors = input.parsedBy(parseSensor) {
val (x1, y1, x2, y2) = it.destructured.toList().map { it.toInt() }
Sensor(Coordinates(x1, y1), Coordinates(x2, y2))
}
val ret: Int
val time = measureTimeMillis {
val beacons = sensors.filter { it.beacon.y == row }.map { it.beacon.x }.toSet()
val ranges: List<IntRange>
val projectTime = measureTimeMillis{
ranges = sensors
.map { it.projectToRow(row) }
.filterNotNull().toList()
}
println("Projecting took $projectTime ms")
val sorted = ranges.sortedBy { it.first }
var x = sorted[0].first
var count = 0
for (range in sorted) {
if (x < range.first) x = range.first
while(x<=range.last) {
if (x !in beacons) count++
x++
}
}
ret = count
}
println("Took $time ms")
return ret
}
fun part2(input: List<String>, size: Int = 20): Long {
val sensors = input.parsedBy(parseSensor) {
val (x1, y1, x2, y2) = it.destructured.toList().map { it.toInt() }
Sensor(Coordinates(x1, y1), Coordinates(x2, y2))
}
val bounds = Bounds(Coordinates(0,0), Coordinates(size, size))
val beacon = sensors.flatMap { it.justOutOfRange() }
.filter { it in bounds }
.filter { sensors.none { sensor -> sensor.covers(it) } }.first()
println(beacon)
return beacon.y + (beacon.x * 4_000_000L)
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 26)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 15).toList()
println(part1(puzzleInput, 2000000))
println(part2(testInput))
println(part2(puzzleInput,4000000))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 3,965 | aoc-2022-kotlin | Apache License 2.0 |
src/day03/Day03.kt | wickenico | 573,048,677 | false | {"Kotlin": 7731} | package day03
import readInput
fun main() {
println(part1(readInput("day03", "input")))
println(part2(readInput("day03", "input")))
}
private fun calculatePriority(char: Char): Int {
return if (char.code >= 92) {
char.code - 96
} else {
char.code - 38
}
}
private fun calculatePriority(backpacks: List<String>): Int {
return calculatePriority(backpacks.map { it.toCharArray().toSet() }.reduce { acc, backpack -> backpack.intersect(acc) }.first())
}
fun part1(backpacks: List<String>): Int {
return backpacks.sumOf { calculatePriority(it.chunked(it.length / 2)) }
}
fun part2(backpacks: List<String>): Int {
return backpacks.windowed(3, step = 3).sumOf { calculatePriority(it) }
}
| 0 | Kotlin | 0 | 0 | 00791dc0870048b08092e38338cd707ce0f9706f | 734 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2018/calendar/day15/GameDijkstra.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2018.calendar.day15
import me.peckb.aoc._2018.calendar.day15.GameDijkstra.SpaceWithPath
import me.peckb.aoc.pathing.Dijkstra
import me.peckb.aoc.pathing.DijkstraNodeWithCost
class GameDijkstra(val gameMap: List<List<Space>>) : Dijkstra<Space, Path, SpaceWithPath> {
override fun Space.withCost(cost: Path) = SpaceWithPath(this, cost)
override fun minCost() = Path(emptyList(), Int.MIN_VALUE)
override fun maxCost() = Path(emptyList(), Int.MAX_VALUE)
override fun Path.plus(cost: Path) = cost
inner class SpaceWithPath(private val space: Space, private val path: Path) :
DijkstraNodeWithCost<Space, Path> {
override fun neighbors(): List<DijkstraNodeWithCost<Space, Path>> {
val u = gameMap[space.y - 1][space.x]
val l = gameMap[space.y][space.x - 1]
val r = gameMap[space.y][space.x + 1]
val d = gameMap[space.y + 1][space.x]
val emptySpaces = listOf(u, l, r, d).filterIsInstance<Space.Empty>()
return emptySpaces.map { emptySpace ->
val (x, y) = emptySpace.x to emptySpace.y
SpaceWithPath(emptySpace, Path(path.steps.plus(Point(x, y))))
}
}
override fun node() = space
override fun cost() = path
override fun compareTo(other: DijkstraNodeWithCost<Space, Path>): Int {
// DEV NOTE: referencing the parent classes path comparator doubles our runtime,
// compared to creating it ourself
return when (val pathComp = path.compareTo(other.cost())) {
0 -> {
when (val yComp = path.steps.last().y.compareTo(other.cost().steps.last().y)) {
0 -> path.steps.last().x.compareTo(other.cost().steps.last().x)
else -> yComp
}
}
else -> pathComp
}
}
}
}
data class Path(val steps: List<Point>, val cost: Int = steps.size) : Comparable<Path> {
override fun compareTo(other: Path) = cost.compareTo(other.cost)
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 1,917 | advent-of-code | MIT License |
y2016/src/main/kotlin/adventofcode/y2016/Day16.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
object Day16 : AdventSolution(2016, 16, "Dragon Checksum ") {
override fun solvePartOne(input: String) = fillDisk(input, 272).checksum()
override fun solvePartTwo(input: String) = fillDisk(input, 35651584).checksum()
}
private fun fillDisk(inputValue: String, size: Int): BooleanArray {
val initial = BooleanArray(inputValue.length) { inputValue[it] == '1' }
val disk = generateSequence(initial, BooleanArray::dragon)
.first { it.size >= size }
return disk.copyOf(size)
}
private fun BooleanArray.dragon(): BooleanArray {
val doubled = this.copyOf(this.size * 2 + 1)
for (i in indices) doubled[doubled.lastIndex - i] = !this[i]
return doubled
}
private fun BooleanArray.checksum(): String =
generateSequence(this) { it.diff() }
.first { it.size % 2 != 0 }
.map { if (it) '1' else '0' }
.fold(StringBuilder(), StringBuilder::append)
.toString()
private fun BooleanArray.diff() = BooleanArray(this.size / 2) { this[it * 2] == this[it * 2 + 1] }
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,131 | advent-of-code | MIT License |
src/main/kotlin/days/Day10.kt | wmichaelshirk | 315,495,224 | false | null | package days
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.roundToLong
class Day10 : Day(10) {
private val inputData = inputList.map(String::toInt).sorted()
private val fullList = listOf(0) + inputData + listOf(inputData.last() + 3)
override fun partOne(): Int? {
val foo = fullList
.zipWithNext()
.map { it.second - it.first }
.groupingBy { it }
.eachCount()
return foo[3]?.let { foo[1]?.times(it) }
}
override fun partTwo(): Long {
val foo = fullList
.asSequence()
.windowed(3)
.map { Pair(it[1] - it[0], it[2] - it[1])}
.map {
!(it.first == 3 || it.second == 3 || (
it.first == 2 && it.second == 2
))
}
.fold(listOf<Pair<Boolean, Int>>()) {
acc, pair -> if (acc.isEmpty()) listOf(Pair(pair, 1))
else if (acc.last().first == pair) {
acc.dropLast(1)
.plus(Pair(acc.last().first, acc.last().second + 1))
} else {
acc.plus(Pair(pair, 1))
}
}
.filter { it.first }
.map { it.second }
.groupBy { it }
val power = ((foo[2]?.count() ?: 0) * 2) +
(foo[1]?.count() ?: 0)
val number = (2.0).pow(power)
return (number * ((7.0).pow(foo[3]?.count() ?: 0))).roundToLong()
}
}
| 0 | Kotlin | 0 | 0 | b36e5236f81e5368f9f6dbed09a9e4a8d3da8e30 | 1,545 | 2020-Advent-of-Code | Creative Commons Zero v1.0 Universal |
2015/src/main/kotlin/com/koenv/adventofcode/Day21.kt | koesie10 | 47,333,954 | false | null | package com.koenv.adventofcode
object Day21 {
public fun getMaxGoldSpentAndLose(input: String): Int {
return getGoldSpent(input, 0, { lhs, rhs -> lhs > rhs}, { it <= 0})
}
public fun getMinGoldSpent(input: String): Int {
return getGoldSpent(input, Integer.MAX_VALUE, { lhs, rhs -> lhs < rhs}, { it > 0})
}
private fun getGoldSpent(input: String, initialValue: Int, operator: (Int, Int) -> Boolean, checkOperator: (Int) -> Boolean): Int {
val result = BOSS_REGEX.find(input)!!
val boss = Boss(result[1].toInt(), result[2].toInt(), result[3].toInt())
val weapons = listOf(
Weapon(8, 4),
Weapon(10, 5),
Weapon(25, 6),
Weapon(40, 7),
Weapon(74, 8)
)
val armors = listOf(
Armor(0, 0),
Armor(13, 1),
Armor(31, 2),
Armor(53, 3),
Armor(75, 4),
Armor(102, 5)
)
val damageRings = listOf(
Ring(0, 0, 0),
Ring(25, 1, 0),
Ring(50, 2, 0),
Ring(100, 3, 0)
)
val armorRings = listOf(
Ring(0, 0, 0),
Ring(20, 0, 1),
Ring(40, 0, 2),
Ring(80, 0, 3)
)
var best = initialValue
for (weapon in weapons) {
for (armor in armors) {
for (ring1 in damageRings) {
for (ring2 in armorRings) {
if (ring1 != ring2) {
val playerDamage = weapon.damage + ring1.damage
val playerArmor = armor.armor + ring2.armor
if (execute(boss, playerDamage, playerArmor, checkOperator)) {
val cost = weapon.cost + armor.cost + ring1.cost + ring2.cost
if (operator(cost, best)) {
best = cost
}
}
}
}
}
}
}
return best
}
private fun execute(boss: Boss, playerDamage: Int, playerArmor: Int, checkOperator: (Int) -> Boolean): Boolean {
var bossHp = boss.hp;
var playerHp = 100;
while (bossHp > 0 && playerHp > 0) {
bossHp -= Math.max(playerDamage - boss.armor, 1)
if (bossHp <= 0) {
break;
}
playerHp -= Math.max(boss.damage - playerArmor, 1)
}
return checkOperator(playerHp)
}
data class Boss(val hp: Int, val damage: Int, val armor: Int)
data class Weapon(val cost: Int, val damage: Int)
data class Armor(val cost: Int, val armor: Int)
data class Ring(val cost: Int, val damage: Int, val armor: Int)
val BOSS_REGEX = "Hit Points: (\\d+)\\s+Damage: (\\d+)\\s+Armor: (\\d+)".toRegex()
} | 0 | Kotlin | 0 | 0 | 29f3d426cfceaa131371df09785fa6598405a55f | 3,018 | AdventOfCode-Solutions-Kotlin | MIT License |
player/greedy.kt | arukuka | 167,334,074 | true | {"HTML": 96461, "C++": 41603, "JavaScript": 31527, "Python": 17524, "Kotlin": 6069, "CSS": 5843, "Makefile": 2251} | import java.util.*
import java.io.*
import kotlin.math.*
const val SEARCHDEPTH = 7
const val SPEEDLIMIT = 1000
const val searchDepth = SEARCHDEPTH
const val speedLimitSquared = SPEEDLIMIT * SPEEDLIMIT
var nextSeq = 1
data class IntVec(val x : Int, val y : Int) {
operator fun plus(v : IntVec) : IntVec {
return IntVec(x + v.x, y + v.y)
}
operator fun compareTo(other : IntVec) : Int {
return if (y == other.y) other.x - x else y - other.y
}
}
data class RaceCourse(val thinkTime : Int, val stepLimit : Int, val width : Int, val length : Int, val vision : Int) {
constructor(input : java.util.Scanner) :this(input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt()) {}
}
fun addSquares(x : Int, y0 : Int, y1 : Int, squares : MutableList<IntVec>) {
for (y in (if (y1 > y0) y0..y1 else y0 downTo y1)) squares.add(IntVec(x, y))
}
data class Movement(val from : IntVec, val to : IntVec) {
fun touchedSquares() : MutableList<IntVec> {
val r : MutableList<IntVec> = mutableListOf()
if (to.x == from.x) addSquares(from.x, from.y, to.y, r)
else {
val a : Double = (to.y - from.y).toDouble() / (to.x - from.x).toDouble()
val sgnx = if (from.x < to.x) 1 else -1
var y1 = a * sgnx / 2.0 + from.y + 0.5
var iy1 = (if (to.y > from.y) floor(y1) else ceil(y1) - 1).toInt()
addSquares(from.x, from.y, iy1, r)
for (x in (if (sgnx > 0) (from.x + sgnx)..(to.x - 1) else (from.x + sgnx).downTo(to.x + 1))) {
val y0 = a * (x - from.x - sgnx / 2.0) + from.y + 0.5
y1 = a * (x - from.x + sgnx / 2.0) + from.y + 0.5
val iy0 = (if (to.y > from.y) ceil(y0) - 1 else floor(y0)).toInt()
iy1 = (if (to.y > from.y) floor(y1) else ceil(y1) - 1).toInt()
addSquares(x, iy0, iy1, r)
}
val y0 = a * (to.x - from.x - sgnx / 2.0) + from.y + 0.5
val iy0 = (if (to.y > from.y) ceil(y0) - 1 else floor(y0)).toInt()
addSquares(to.x, iy0, to.y, r)
}
return r
}
}
data class PlayerState(val position : IntVec, val velocity : IntVec) {
constructor (input : java.util.Scanner) : this(IntVec(input.nextInt(), input.nextInt()), IntVec(input.nextInt(), input.nextInt())) {}
operator fun compareTo(other : PlayerState) : Int {
val c1 = position.compareTo(other.position)
return if (c1 == 0) velocity.compareTo(other.velocity) else c1
}
}
data class RaceInfo(val stepNumber : Int, val timeLeft : Int, val me : PlayerState, val opponent : PlayerState, val squares : List<List<Int>>) {
constructor(input : java.util.Scanner, course : RaceCourse)
:this(input.nextInt(), input.nextInt(), PlayerState(input),
PlayerState(input),
Array(course.length, {Array(course.width, {input.nextInt()}).asList()}).asList()) {}
}
data class Candidate(val course : RaceCourse, val step : Int, val state : PlayerState, val from : Candidate?, val how : IntVec) : Comparable<Candidate> {
val seq = nextSeq
init {
nextSeq += 1
}
val goaled = state.position.y >= course.length
val goalTime = if (goaled) (step + course.length - state.position.y - 0.5) / state.velocity.y else 0.0
operator override fun compareTo(other : Candidate) : Int {
if (goaled) {
if (!other.goaled || other.goalTime > goalTime) return -1
else if (other.goalTime < goalTime) return 1
else return 0
} else if (state == other.state) return step - other.step
else return other.state.compareTo(state)
}
override fun toString() : String {
return "#${seq}: ${step}@(${state.position.x},${state.position.y})+(${state.velocity.x},${state.velocity.y}) <- #${from?.seq ?: 0}"
}
}
fun plan(info : RaceInfo, course : RaceCourse) : IntVec {
val candidates = PriorityQueue<Candidate>()
val initial = PlayerState(info.me.position, info.me.velocity)
val initialCand = Candidate(course, 0, initial, null, IntVec(0, 0))
val reached = mutableMapOf(initial to initialCand)
var best = initialCand
candidates.add(initialCand)
while (!candidates.isEmpty()) {
val c = candidates.poll()
for (cay in 1 downTo -1) {
for (cax in -1..1) {
val accel = IntVec(cax, cay)
var velo = c.state.velocity + accel
if (velo.x * velo.x + velo.y * velo.y <= speedLimitSquared) {
val pos = c.state.position + velo
if (0 <= pos.x && pos.x < course.width) {
val move = Movement(c.state.position, pos)
val touched = move.touchedSquares()
if (pos != info.opponent.position &&
touched.all { s ->
0 > s.y || s.y >= course.length ||
info.squares[s.y][s.x] != 1}) {
if (0 <= pos.y && pos.y < course.length &&
info.squares[pos.y][pos.x] == 2) {
velo = IntVec(0, 0)
}
val nextState = PlayerState(pos, velo)
val nextCand = Candidate(course, c.step + 1, nextState, c, accel)
if (!nextCand.goaled &&
c.step < searchDepth &&
(!reached.containsKey(nextState) ||
reached[nextState]!!.step > c.step + 1)) {
candidates.add(nextCand)
reached[nextState] = nextCand
if (nextCand < best) best = nextCand
}
}
}
}
}
}
}
if (best == initialCand) {
var ax = 0
var ay = 0
if (info.me.velocity.x < 0) ax += 1
else if (info.me.velocity.x > 0) ax -= 1
if (info.me.velocity.y < 0) ay += 1
else if (info.me.velocity.y > 0) ay -= 1
return IntVec(ax, ay)
}
var c : Candidate = best
while (c.from != initialCand) {
c = c.from!!
}
return c.how
}
fun main(args : Array<String>) {
val input = java.util.Scanner(System.`in`)
val course = RaceCourse(input)
println(0)
System.out.flush()
try {
while (true) {
val info = RaceInfo(input, course)
val accel = plan(info, course)
println("${accel.x} ${accel.y}")
System.out.flush()
}
} catch (e : Exception) {
}
}
| 0 | HTML | 0 | 0 | 04db0dade2bb0ef9803fb473665b171a233a2748 | 6,069 | software-for-SamurAI-Coding-2018-19 | MIT License |
2022/kotlin-lang/src/main/kotlin/mmxxii/days/Day3.kt | Delni | 317,500,911 | false | {"Kotlin": 66017, "Dart": 53066, "Go": 28200, "TypeScript": 7238, "Rust": 7104, "JavaScript": 2873} | package mmxxii.days
class Day3 : Abstract2022<Int>("03", "Rucksack Reorganization") {
override fun part1(input: List<String>): Int = input
.map(String::toRucksack)
.map { it.first.intersect(it.second.toSet()).single() }
.sumByPriority()
override fun part2(input: List<String>) = input
.toSquad()
.map { it[0].intersect(it[1]).intersect(it[2]).single() }
.sumByPriority()
private fun List<String>.toPriority() = map { it.toCharArray().single().code }.map {
it.takeIf { it >= 'a'.code }?.let { char -> char - 'a'.code + 1 } ?: (it - 'A'.code + 27)
}
private fun List<String>.sumByPriority() = toPriority().sum()
}
private fun String.toRucksack() = split("").let {
it.subList(1, it.size / 2) to it.subList(it.size / 2, it.size - 1)
}
private fun List<String>.toSquad() = List(size) { index ->
index.takeIf { it != 0 && (it + 1) % 3 == 0 }?.let {
subList(it - 2, it + 1).map { s -> s.split("").filter(String::isNotEmpty).toSet() }
}
}.filterNotNull() | 0 | Kotlin | 0 | 1 | d8cce76d15117777740c839d2ac2e74a38b0cb58 | 1,049 | advent-of-code | MIT License |
src/Day01.kt | maewCP | 579,203,172 | false | {"Kotlin": 59412} | fun main() {
fun prepareInput(allInput: String): MutableList<Int> {
val elfCalories = mutableListOf<Int>()
allInput.split("\n\n").forEach { elf ->
elfCalories.add(elf.split("\n").sumOf { cal -> cal.toInt() })
}
return elfCalories
}
fun part1(input: List<String>): Int {
val allInput = input.joinToString(separator = "\n")
val elfCalories = prepareInput(allInput)
return elfCalories.maxOf { it }
}
fun part2(input: List<String>): Int {
val allInput = input.joinToString(separator = "\n")
val elfCalories = prepareInput(allInput)
elfCalories.sortDescending()
return (0..2).sumOf { elfCalories[it] }
}
// 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")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 8924a6d913e2c15876c52acd2e1dc986cd162693 | 1,010 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/aoc2022/Day7.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2022
class Day7(input: List<String>) {
private val fileSizes = parseInput(input)
/**
* Returns list of sizes of files / directories in the file system. The file names are not needed
* for anything so those are not included.
*/
private fun parseInput(input: List<String>): List<Int> {
var currentDir = "/"
// Map of full directory path to size of files in the directory (sub directories not included)
val directories = mutableMapOf<String, Int>()
var i = 0
while (i < input.size) {
val parts = input[i].split(" ")
when (parts[1]) {
"cd" -> {
when (parts[2]) {
"/" -> currentDir = "/"
".." -> currentDir = currentDir.substringBeforeLast("/")
else -> {
if (!currentDir.endsWith("/")) {
currentDir += "/"
}
currentDir += parts[2]
}
}
}
"ls" -> {
val content = input.subList(i + 1, input.size).takeWhile { !it.startsWith("$") }
directories[currentDir] = content.filterNot { it.startsWith("dir") }
.sumOf { it.split(" ").first().toInt() }
i += content.size //advance past all entries
}
else -> error("Unknown command")
}
i++ //advance past the command
}
// directories only includes the size of the files, not of the directories so need to add subdirectory sizes
return directories.map { (path, _) ->
// all directories with a shared initial full path is located in the directory identified by the
// shared path. Their combined size is the size of the base path directory.
directories.filter { it.key.startsWith(path) }.values.sum()
}
}
fun solvePart1(): Int {
return fileSizes.sumOf { if (it <= 100000) it else 0 }
}
fun solvePart2(): Int {
val toFree = fileSizes.max() - 40000000
return fileSizes.filter { it >= toFree }.min()
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,290 | aoc | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/AmountOfTime.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
/**
* 2385. Amount of Time for Binary Tree to Be Infected
* @see <a href="https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected">Source</a>
*/
fun interface AmountOfTime {
operator fun invoke(root: TreeNode?, start: Int): Int
}
class AmountOfTimeBFS : AmountOfTime {
override fun invoke(root: TreeNode?, start: Int): Int {
val treeMap: MutableMap<Int, MutableSet<Int>> = mutableMapOf()
convert(root, 0, treeMap)
val queue = LinkedList<Int>()
queue.offer(start)
var minute = 0
val visited = mutableSetOf(start)
while (queue.isNotEmpty()) {
var levelSize = queue.size
while (levelSize > 0) {
val current = queue.pollFirst()
for (num in treeMap.getOrDefault(current, mutableSetOf())) {
if (!visited.contains(num)) {
visited.add(num)
queue.offer(num)
}
}
levelSize--
}
minute++
}
return minute - 1
}
private fun convert(current: TreeNode?, parent: Int, treeMap: MutableMap<Int, MutableSet<Int>>) {
if (current == null) {
return
}
if (!treeMap.containsKey(current.value)) {
treeMap[current.value] = mutableSetOf()
}
val adjacentList = treeMap.getOrDefault(current.value, mutableSetOf())
if (parent != 0) {
adjacentList.add(parent)
}
current.left?.value?.let {
adjacentList.add(it)
}
current.right?.value?.let {
adjacentList.add(it)
}
convert(current.left, current.value, treeMap)
convert(current.right, current.value, treeMap)
}
}
class AmountOfTimeDFS : AmountOfTime {
private var maxDistance = 0
override fun invoke(root: TreeNode?, start: Int): Int {
traverse(root, start)
return maxDistance
}
private fun traverse(root: TreeNode?, start: Int): Int {
val depth: Int
if (root == null) {
return 0
}
val leftDepth = traverse(root.left, start)
val rightDepth = traverse(root.right, start)
if (root.value == start) {
maxDistance = kotlin.math.max(leftDepth, rightDepth)
depth = -1
} else if (leftDepth >= 0 && rightDepth >= 0) {
depth = kotlin.math.max(leftDepth, rightDepth) + 1
} else {
val distance = kotlin.math.abs(leftDepth) + kotlin.math.abs(rightDepth)
maxDistance = kotlin.math.max(maxDistance, distance)
depth = kotlin.math.min(leftDepth, rightDepth) - 1
}
return depth
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,440 | kotlab | Apache License 2.0 |
src/main/kotlin/day03_oop/day03_oop.kt | andrew-suprun | 725,670,189 | false | {"Kotlin": 18354, "Python": 17857, "Dart": 8224} | package day03_oop
import java.io.File
fun main() {
Part1("input.data").run()
Part2("input.data").run()
}
data class Number(val value: Int, val row: Int, val colStart: Int, var colEnd: Int)
abstract class Day03(fileName: String) {
private val lines = File(fileName).readLines()
val numbers = parseEngine()
abstract fun score(char: Char, row: Int, col: Int): Int
fun run() {
var result = 0
for ((row, line) in lines.withIndex()) {
for ((col, char) in line.withIndex()) {
result += score(char, row, col)
}
}
println(result)
}
private fun parseEngine(): List<Number> {
val numbers = mutableListOf<Number>()
for ((row, line) in lines.withIndex()) {
var firstDigit = -1
for ((col, char) in line.withIndex()) {
if (char.isDigit()) {
if (firstDigit == -1) {
firstDigit = col
}
} else {
if (firstDigit != -1) {
val value = line.substring(firstDigit, col).toInt()
numbers += Number(value = value, row = row, colStart = firstDigit, colEnd = col)
firstDigit = -1
}
}
}
if (firstDigit != -1) {
val value = line.substring(firstDigit, line.length).toInt()
numbers += Number(value = value, row = row, colStart = firstDigit, colEnd = line.length)
}
}
return numbers
}
fun adjacent(number: Number, row: Int, col: Int): Boolean =
row in number.row - 1..number.row + 1 && col in number.colStart - 1..number.colEnd
}
class Part1(fileName: String) : Day03(fileName) {
override fun score(char: Char, row: Int, col: Int): Int {
var result = 0
if (char != '.' && !char.isDigit()) {
for (number in numbers) {
if (adjacent(number, row, col)) {
result += number.value
}
}
}
return result
}
}
class Part2(fileName: String) : Day03(fileName) {
override fun score(char: Char, row: Int, col: Int): Int {
var result = 0
if (char == '*') {
val adjacentNumbers = mutableListOf<Number>()
for (number in numbers) {
if (adjacent(number, row, col)) adjacentNumbers += number
}
if (adjacentNumbers.size == 2) {
result += adjacentNumbers[0].value * adjacentNumbers[1].value
}
}
return result
}
} | 0 | Kotlin | 0 | 0 | dd5f53e74e59ab0cab71ce7c53975695518cdbde | 2,685 | AoC-2023 | The Unlicense |
src/chapter3/section4/ex30_ChiSquareStatistic.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter3.section4
import extensions.formatDouble
import extensions.random
import kotlin.math.sqrt
/**
* 卡方值(chi-square statistic)
* 为SeparateChainingHashST添加一个方法来计算散列表的X²
* 对于大小为M并含有N个元素的散列表,这个值的定义为:
* X² = (M / N)((f₀ - N / M)² + (f₁ - N / M)² + ... + (f(m-1) - N / M)²)
* 其中,f(i)为散列值为i的键的数量
* 这个统计数据是检测我们的散列函数产生的随机值是否满足假设的一种方法
* 如果满足,对于N>cM,这个值落在 M - sqrt(M) 和 M + sqrt(M) 之间的概率为 1 - 1/c
*
* 解:c为一个小常数,大小等于N/M(向下取整)
* 随机生成N个键插入到Hash表中,计算卡方值,判断是否在 M - sqrt(M) 和 M + sqrt(M) 之间
* 重复多次,计算卡方值在范围内的实际概率,与期望概率 1 - 1/c 对比
* 卡方值越小,数据分布越均匀
*/
fun <K : Any, V : Any> SeparateChainingHashST<K, V>.chiSquareStatistic(): Double {
val array = IntArray(m)
keys().forEach {
array[hash(it)]++
}
var sum = 0.0
val mn = m.toDouble() / n
val nm = n.toDouble() / m
array.forEach {
sum += (it - nm) * (it - nm)
}
return mn * sum
}
fun main() {
val size = 100
val maxKey = Int.MAX_VALUE
val repeatTimes = 1000
val N = size
var M = 4
//根据N的大小,计算在只插入不删除的情况下M的大小
while (N > 8 * M) {
M *= 2
}
val c = N / M
val min = M - sqrt(M.toDouble())
val max = M + sqrt(M.toDouble())
println("N=$N M=$M c=$c")
println("min=${formatDouble(min, 2)}")
println("max=${formatDouble(max, 2)}")
println("Expected probability: (1-1/c) = ${formatDouble(1 - 1.0 / c, 2)}")
var count = 0
repeat(repeatTimes) {
val st = SeparateChainingHashST<Int, Int>()
while (st.size() < size) {
st.put(random(maxKey), 0)
}
val value = st.chiSquareStatistic()
if (value in min..max) {
count++
}
}
println("Actual probability: ${formatDouble(count.toDouble() / repeatTimes, 2)}")
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,196 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/day03/Day03.kt | Puju2496 | 576,611,911 | false | {"Kotlin": 46156} | package day03
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val input = readInput("src/day03", "Day03")
println("Part1")
part1(input)
println("Part2")
part2(input)
}
private fun part1(inputs: List<String>) {
var sum = 0
inputs.forEach {
val first: String = it.subSequence(0, it.length / 2).toString()
val second: String = it.subSequence(it.length / 2, it.length).toString()
val same: String = first.filter { a -> second.contains(a) }
sum += same.first().code - if (same.first().isUpperCase()) 38 else 96
println("input $it - $first - $second - $same - ${same.first().code} - $sum")
}
println("sum - $sum")
}
private fun part2(inputs: List<String>) {
val list: List<List<String>> = inputs.groupBy { inputs.indexOf(it) / 3 }.values.toList()
var sum = 0
list.forEach {
val same: String = it[0].filter { a -> it[1].contains(a) && it[2].contains(a) }
sum += same.first().code - if (same.first().isUpperCase()) 38 else 96
println("sub : $it - $same - $sum")
}
println("sum - $sum")
} | 0 | Kotlin | 0 | 0 | e04f89c67f6170441651a1fe2bd1f2448a2cf64e | 1,162 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/day4/Day4.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day4
import days.Day
import kotlin.math.pow
class Day4: Day(false) {
override fun partOne(): Any {
//Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
val winningNumbers: List<List<Int>> = readInput().map{
it.substringAfter(":").substringBefore("|").trim().split(" ").filter { it.isNotBlank() }
.map{it.toInt()}
}
val myValues = readInput().map{ it ->
it.substringAfter("| ")
.trim()
.split(" ")
.filter { it.isNotBlank() }
.map{it.toInt()}
}
var result = 0
for (i in winningNumbers.indices) {
val winningNumber = winningNumbers[i]
val myValue = myValues[i]
var count = 0
for (number in myValue) {
if (number in winningNumber) {
count++
}
}
result += 2.0.pow((count - 1).toDouble()).toInt()
}
return result
}
override fun partTwo(): Any {
val winningNumbers: List<List<Int>> = readInput().map{
it.substringAfter(":").substringBefore("|").trim().split(" ").filter { it.isNotBlank() }
.map{it.toInt()}
}
val myValues = readInput().map{ it ->
it.substringAfter("| ").trim().split(" ").filter { it.isNotBlank() }.map{it.toInt()}
}
val instances = IntArray(winningNumbers.size){1}
for (i in winningNumbers.indices) {
val winningNumber = winningNumbers[i]
val myValue = myValues[i]
var count = 0
for (number in myValue) {
if (number in winningNumber) {
count++
}
}
for (j in 0 ..< count) {
try {
instances[j+i+1] += instances[i]
}catch (e: Exception) {
println("i: $i, j: $j")
}
}
}
return instances.sum()
}
}
| 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 2,074 | advent-of-code_2023 | The Unlicense |
src/main/kotlin/aoc2019/ManyWorldsInterpretation.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.utils.Point
import komu.adventofcode.utils.nonEmptyLines
import utils.shortestPathBetween
import utils.shortestPathWithCost
private typealias LockType = Int
private typealias CollectedKeys = Int
fun manyWorldsInterpretation(input: String): Int =
Vault.parse(input).solve()
private class Vault private constructor(
tiles: Collection<Tile>,
private val starts: List<Tile>
) {
private val keyCount = tiles.count { it.key != null }
private val keysByType = tiles.filter { it.key != null }.associateBy { it.key!! }
private val pathCache = mutableMapOf<PathCacheKey, List<Tile>>()
fun solve(): Int {
val (_, cost) = shortestPathWithCost(State(starts), { it.keyCount == keyCount }) { state ->
val result = mutableListOf<Pair<State, Int>>()
for ((i, from) in state.tiles.withIndex()) {
for ((key, keyTile) in keysByType.entries) {
if (!state.hasKey(key)) {
val path = path(from, keyTile, state.collectedKeys)
if (path != null && path.hasNoUnCollectedKeys(state.collectedKeys))
result += state.collectKeyAt(i, keyTile, key) to path.size
}
}
}
result
} ?: error("no path")
return cost
}
private fun List<Tile>.hasNoUnCollectedKeys(collectedKeys: CollectedKeys): Boolean =
subList(0, size - 1).none { it.key != null && it.key !in collectedKeys }
private fun path(from: Tile, to: Tile, collectedKeys: CollectedKeys): List<Tile>? =
pathCache.getOrPut(PathCacheKey(collectedKeys, from, to)) {
shortestPathBetween(from, to) { it.accessibleNeighbors(collectedKeys) }.orEmpty()
}.takeUnless { it.isEmpty() }
private data class PathCacheKey(val from: Tile, val to: Tile, val collectedKeys: CollectedKeys) {
constructor(collectedKeys: CollectedKeys, from: Tile, to: Tile) : this(
if (from.hashCode() < to.hashCode()) from else to,
if (from.hashCode() < to.hashCode()) to else from,
collectedKeys
)
}
private data class State(val tiles: List<Tile>, val collectedKeys: CollectedKeys = 0) {
val keyCount = Integer.bitCount(collectedKeys)
fun hasKey(key: LockType) =
key in collectedKeys
fun collectKeyAt(index: Int, to: Tile, key: LockType): State {
val tiles = tiles.toMutableList()
tiles[index] = to
return State(tiles, collectedKeys or key)
}
}
private class Tile(val lock: LockType? = null, val key: LockType? = null) {
private var neighbors: List<Tile> = emptyList()
private var unlockedNeighbors = true
fun initNeighbors(neighbors: List<Tile>) {
this.neighbors = neighbors
this.unlockedNeighbors = neighbors.all { it.lock == null }
}
fun accessibleNeighbors(keys: CollectedKeys): List<Tile> =
if (unlockedNeighbors) neighbors else neighbors.filter { it.canPass(keys) }
fun canPass(keys: CollectedKeys) =
lock == null || lock in keys
}
companion object {
private operator fun CollectedKeys.contains(key: LockType) =
(this and key) != 0
private fun encodeKey(key: Char): Int =
1 shl (key.toUpperCase() - 'A')
fun parse(input: String): Vault {
val starts = mutableListOf<Tile>()
val tilesByPoint = mutableMapOf<Point, Tile>()
for ((y, line) in input.nonEmptyLines().withIndex()) {
for ((x, c) in line.withIndex()) {
val point = Point(x, y)
when {
c == '@' -> {
val tile = Tile()
starts += tile
tilesByPoint[point] = tile
}
c == '.' ->
tilesByPoint[point] = Tile()
c.isLowerCase() ->
tilesByPoint[point] = Tile(key = encodeKey(c))
c.isUpperCase() ->
tilesByPoint[point] = Tile(lock = encodeKey(c))
}
}
}
for ((point, tile) in tilesByPoint)
tile.initNeighbors(point.neighbors.mapNotNull { tilesByPoint[it] })
return Vault(tilesByPoint.values.toList(), starts)
}
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 4,607 | advent-of-code | MIT License |
src/main/java/com/barneyb/aoc/aoc2022/day18/BoilingBoulders.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day18
import com.barneyb.aoc.util.*
import com.barneyb.util.HashSet
import com.barneyb.util.Queue
import com.barneyb.util.Vec3
fun main() {
Solver.execute(
::parse,
::surfaceArea, // 3586
::externalSurfaceArea, // 2072
)
}
internal fun parse(input: String) =
HashSet<Vec3>().apply {
input.toSlice()
.trim()
.lines()
.forEach {
val (x, y, z) = it.split(",")
.map(Slice::toInt)
add(Vec3(x, y, z))
}
}
internal fun surfaceArea(cubes: HashSet<Vec3>): Int {
val v = cubes.size
var e = 0
for (c in cubes) {
if (cubes.contains(c.mx(1))) e++
if (cubes.contains(c.my(1))) e++
if (cubes.contains(c.mz(1))) e++
}
return 6 * v - 2 * e
}
internal fun externalSurfaceArea(cubes: HashSet<Vec3>): Int {
val visited = HashSet<Vec3>()
var faces = 0
val queue = Queue<Vec3>()
// this assumes the droplet is "against" the origin and cubic-ish.
val range = cubes.fold(1..1) { r, v ->
r + v.x + v.y + v.z
}.let { r ->
r.first - 1..r.last + 1
}
fun check(v: Vec3) {
if (v.x !in range) return
if (v.y !in range) return
if (v.z !in range) return
if (visited.contains(v)) return
if (cubes.contains(v)) {
faces++
} else {
visited.add(v)
queue.enqueue(v)
}
}
check(Vec3(range.first, range.first, range.first))
while (!queue.isEmpty()) {
val curr = queue.dequeue()
check(curr.mx(1))
check(curr.mx(-1))
check(curr.my(1))
check(curr.my(-1))
check(curr.mz(1))
check(curr.mz(-1))
}
return faces
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 1,811 | aoc-2022 | MIT License |
src/main/kotlin/be/twofold/aoc2021/Day03.kt | jandk | 433,510,612 | false | {"Kotlin": 10227} | package be.twofold.aoc2021
object Day03 {
fun part1(input: List<String>): Int {
val count = input.size
val width = input[0].length
var result = 0
for (i in 0 until width) {
val isOne = input.count { it[i] == '1' } >= (count / 2)
result = (result shl 1) or (if (isOne) 1 else 0)
}
return result * (result xor ((1 shl width) - 1))
}
fun part2(input: List<String>): Int {
val first = removeCommon(input, true)
val second = removeCommon(input, false)
return first * second
}
private fun removeCommon(input: List<String>, mostCommon: Boolean): Int {
var index = 0
var result = input
while (result.size > 1) {
val grouped = result.groupBy { it[index] }
val ones = grouped['1']!!
val zeros = grouped['0']!!
result = if ((ones.size >= zeros.size) xor mostCommon) zeros else ones
index++
}
return result.first().toInt(2)
}
}
fun main() {
val input = Util.readFile("/day03.txt")
println("Part 1: ${Day03.part1(input)}")
println("Part 2: ${Day03.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 2408fb594d6ce7eeb2098bc2e38d8fa2b90f39c3 | 1,190 | aoc2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindMinArrowShots.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
/**
* 452. Minimum Number of Arrows to Burst Balloons
* @see <a href="https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/">Source</a>
*/
sealed interface FindMinArrowShots {
operator fun invoke(points: Array<IntArray>): Int
}
object FindMinArrowShotsGreedy : FindMinArrowShots {
override operator fun invoke(points: Array<IntArray>): Int {
if (points.isEmpty()) {
return 0
}
points.sortWith { a, b ->
a[1].compareTo(b[1])
}
var ans = 0
var arrow = 0
for (i in points.indices) {
if (ans == 0 || points[i][0] > arrow) {
ans++
arrow = points[i][1]
}
}
return ans
}
}
object FindMinArrowShotsCompact : FindMinArrowShots {
override operator fun invoke(points: Array<IntArray>): Int {
points.sortBy { it[1] }
var last = 0
return 1 + (1..points.lastIndex).count { e ->
(points[e][0] > points[last][1])
.also { if (it) last = e }
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,730 | kotlab | Apache License 2.0 |
monty-hall/src/main/kotlin/com/nickperov/stud/algorithms/montyhall/MontyHallSimulator.kt | nickperov | 327,780,009 | false | null | package com.nickperov.stud.algorithms.montyhall
import kotlin.random.Random
enum class Prize {
GOAT, CAR
}
enum class Strategy {
KEEP, CHANGE, GUESS
}
object MontyHallApp {
@JvmStatic
fun main(args: Array<String>) {
println("Simulate monty hall game with different strategies")
val rounds = generateRounds(1_000_000)
/*println(rounds.contentDeepToString())*/
Strategy.values().forEach { strategy ->
val percentageWins = play(rounds, strategy)
println("Strategy %{strategy.name} wins:$percentageWins%")
}
}
}
private fun play(rounds: Array<Array<Prize>>, strategy: Strategy): Double {
val result = rounds.map { play(it, strategy) }.toTypedArray()
val totalWins = result.filter { it }.count()
return (totalWins / (rounds.size / 100).toDouble()).toDouble()
}
private fun play(round: Array<Prize>, strategy: Strategy): Boolean {
val firstTry = Random.nextInt(3)
val openedDoor = openDoor(round, firstTry)
val secondTry = makeSecondTry(firstTry, openedDoor, strategy)
return round[secondTry] == Prize.CAR
}
private fun makeSecondTry(firstTry: Int, openedDoor: Int, strategy: Strategy): Int {
return when (strategy) {
Strategy.KEEP -> firstTry
Strategy.CHANGE -> nextDoor(firstTry, openedDoor)
Strategy.GUESS -> if (Random.nextBoolean()) nextDoor(firstTry, openedDoor) else firstTry
}
}
private fun nextDoor(currentDoor: Int, openedDoor: Int): Int {
for (i in 0..2) {
if (i != currentDoor && i != openedDoor) {
return i;
}
}
throw RuntimeException("Fatal error")
}
private fun openDoor(round: Array<Prize>, firstTry: Int): Int {
round.forEachIndexed { index, prize ->
if (index != firstTry && prize == Prize.GOAT) {
return index
}
}
throw RuntimeException("Fatal error")
}
private fun generateRounds(size: Int): Array<Array<Prize>> {
return Array(size) { generateRound() }
}
private fun generateRound(): Array<Prize> {
return when (Random.nextInt(3)) {
0 -> {
arrayOf(Prize.CAR, Prize.GOAT, Prize.GOAT)
}
1 -> {
arrayOf(Prize.GOAT, Prize.CAR, Prize.GOAT)
}
else -> {
arrayOf(Prize.GOAT, Prize.GOAT, Prize.CAR)
}
}
}
| 0 | Kotlin | 0 | 0 | 6696f5d8bd73ce3a8dfd4200f902e2efe726cc5a | 2,342 | Algorithms | MIT License |
src/main/kotlin/dev/siller/aoc2023/Day11.kt | chearius | 725,594,554 | false | {"Kotlin": 50795, "Shell": 299} | package dev.siller.aoc2023
import dev.siller.aoc2023.util.Point
import kotlin.math.abs
data object Day11 : AocDayTask<ULong, ULong>(
day = 11,
exampleInput =
"""
|...#......
|.......#..
|#.........
|..........
|......#...
|.#........
|.........#
|..........
|.......#..
|#...#.....
""".trimMargin(),
expectedExampleOutputPart1 = 374u,
expectedExampleOutputPart2 = 82000210uL
) {
private data class Universe(
val width: ULong,
val height: ULong,
val galaxies: List<Point>
) {
fun grow(steps: ULong = 1u): Universe {
val emptyX = (0..width.toInt()).toSet() - galaxies.map(Point::x).distinct().toSet()
val emptyY = (0..height.toInt()).toSet() - galaxies.map(Point::y).distinct().toSet()
val newWidth = width + (emptyX.size.toULong() * steps)
val newHeight = height + (emptyY.size.toULong() * steps)
val newGalaxies =
galaxies.map { galaxy ->
val newX = galaxy.x + (emptyX.count { x -> x < galaxy.x } * steps.toInt())
val newY = galaxy.y + (emptyY.count { y -> y < galaxy.y } * steps.toInt())
Point(newX, newY)
}
return Universe(newWidth, newHeight, newGalaxies)
}
}
override fun runPart1(input: List<String>): ULong = parseUniverse(input).grow().galaxies.let(::calculateDistances)
override fun runPart2(input: List<String>): ULong =
parseUniverse(input).grow(steps = 1000000uL - 1uL).galaxies.let(::calculateDistances)
private fun calculateDistances(galaxies: List<Point>) =
galaxies.foldIndexed(0uL) { index, acc, firstGalaxy ->
acc +
galaxies.drop(index + 1).fold(0uL) { subAcc, secondGalaxy ->
val vector = secondGalaxy - firstGalaxy
subAcc + abs(vector.x).toULong() + abs(vector.y).toULong()
}
}
private fun parseUniverse(input: List<String>): Universe {
val height = input.size.toULong()
val width = input[0].length.toULong()
val galaxies =
input
.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == '#') {
Point(x, y)
} else {
null
}
}
}
return Universe(width, height, galaxies)
}
}
| 0 | Kotlin | 0 | 0 | fab1dd509607eab3c66576e3459df0c4f0f2fd94 | 2,617 | advent-of-code-2023 | MIT License |
src/Day19.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | import kotlin.math.max
private fun blueprints(): List<Blueprint> {
return readInput("Day19").map {
val bVals = Regex(
"Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. " +
"Each obsidian robot costs (\\d+) ore and (\\d+) clay. " +
"Each geode robot costs (\\d+) ore and (\\d+) obsidian."
).matchEntire(it)!!.groupValues.drop(1).map { v -> v.toInt() }
Blueprint(bVals[0], bVals[1], bVals[2], bVals[3], bVals[4], bVals[5], bVals[6])
}
}
private var maxOreCost = 0
private var maxClayCost = 0
private var maxObsCost = 0
private var maxG = 0
private val tCache = HashMap<Timeless, Int>()
private val rCache = HashMap<ResourcelessState, Resources>()
private fun maxGeodes(b: Blueprint, time: Int): Int {
maxG = 0
rCache.clear()
tCache.clear()
maxOreCost = listOf(b.oreRCost, b.clayRCostOre, b.obsRCostOre, b.gRCostOre).max()
maxClayCost = b.obsRCostClay
maxObsCost = b.gRCostObs
val initState = State(0, 0, 0, 0, 1, 0, 0, 0, time)
rCache[initState.toRless()] = initState.toR()
tCache[initState.toTimeless()] = initState.timeLeft
val states = ArrayDeque<State>()
states.add(initState)
while (states.isNotEmpty()) {
val s = states.removeFirst()
processState(s, b, states)
}
return maxG
}
private fun processState(s: State, b: Blueprint, states: ArrayDeque<State>) {
// potentially we will have at least s.geode + s.geodeRobots * s.timeLeft
maxG = max(maxG, s.geode + s.geodeRobots * s.timeLeft)
if (s.timeLeft == 0) {
return
}
val newStates: List<State> = buildRobots(s, b).map { it.updateResAndTime(s) }
newStates.forEach {
// if we already visited state with same robots and at the same time, but with >= resources
val rLess = it.toRless()
val rc = rCache[rLess]
val visMoreRes =
rc != null && rc.ore >= it.ore && rc.clay >= it.clay && rc.obsidian >= it.obsidian && rc.geode >= it.geode
// if we potentially can make more than maxG by building geode robot on every minute left
val t = it.timeLeft
val canImprove = (it.geode + it.geodeRobots * t + t * (t - 1) / 2) > maxG
// if we already visited same state, but earlier
val timeless = it.toTimeless()
val tc = tCache[timeless]
val visEarlier = (tc != null && tc >= it.timeLeft)
if (!visMoreRes && !visEarlier && canImprove) {
states.add(it)
rCache[rLess] = it.toR()
tCache[timeless] = it.timeLeft
}
}
}
private fun buildRobots(init: State, b: Blueprint): List<State> {
val states = ArrayList<State>()
val (ore, clay, obs, g, oreR, clayR, obsR, gR, timeLeft) = init
// no need to wait if we can build any robot
if (!(ore >= b.gRCostOre && obs >= b.gRCostObs && ore >= b.obsRCostOre && clay >= b.obsRCostClay && ore >= b.clayRCostOre && ore >= b.oreRCost)) {
states.add(init)
}
// no need to build more robots than maxCost, because we will not be able to spend resources anyway
// no need to build more robots if (timeLeft < (res / maxCost)), because enough resources already to build on each minute left
if (ore >= b.gRCostOre && obs >= b.gRCostObs) {
val newGR = State(ore - b.gRCostOre, clay, obs - b.gRCostObs, g, oreR, clayR, obsR, gR + 1, timeLeft)
states.add(newGR)
}
if (ore >= b.obsRCostOre && clay >= b.obsRCostClay && (timeLeft > (init.obsidian / maxObsCost))) {
val newObsR = State(ore - b.obsRCostOre, clay - b.obsRCostClay, obs, g, oreR, clayR, obsR + 1, gR, timeLeft)
if (newObsR.obsidianRobots <= maxObsCost) states.add(newObsR)
}
if (ore >= b.clayRCostOre && (timeLeft > (init.clay / maxClayCost))) {
val newClayR = State(ore - b.clayRCostOre, clay, obs, g, oreR, clayR + 1, obsR, gR, timeLeft)
if (newClayR.clayRobots <= maxClayCost) states.add(newClayR)
}
if (ore >= b.oreRCost && (timeLeft > (init.ore / maxOreCost))) {
val newOreR = State(ore - b.oreRCost, clay, obs, g, oreR + 1, clayR, obsR, gR, timeLeft)
if (newOreR.oreRobots <= maxOreCost) states.add(newOreR)
}
return states
}
private fun part1(blueprints: List<Blueprint>): Int {
return blueprints.sumOf { maxGeodes(it, 24) * it.id }
}
private fun part2(blueprints: List<Blueprint>): Int {
return blueprints.take(3).map { maxGeodes(it, 32) }.reduce(Int::times)
}
fun main() {
measure { part1(blueprints()) } // 1659
measure { part2(blueprints()) } //6804
}
private data class Blueprint(
val id: Int,
val oreRCost: Int,
val clayRCostOre: Int,
val obsRCostOre: Int,
val obsRCostClay: Int,
val gRCostOre: Int,
val gRCostObs: Int
)
private data class State(
val ore: Int,
val clay: Int,
val obsidian: Int,
val geode: Int,
val oreRobots: Int,
val clayRobots: Int,
val obsidianRobots: Int,
val geodeRobots: Int,
val timeLeft: Int
) {
fun updateResAndTime(init: State): State = State(
ore + init.oreRobots,
clay + init.clayRobots,
obsidian + init.obsidianRobots,
geode + init.geodeRobots,
oreRobots,
clayRobots,
obsidianRobots,
geodeRobots,
timeLeft - 1
)
fun toTimeless(): Timeless =
Timeless(ore, clay, obsidian, geode, oreRobots, clayRobots, obsidianRobots, geodeRobots)
fun toR(): Resources =
Resources(ore, clay, obsidian, geode)
fun toRless(): ResourcelessState =
ResourcelessState(oreRobots, clayRobots, obsidianRobots, geodeRobots, timeLeft)
}
private data class ResourcelessState(
val oreRobots: Int,
val clayRobots: Int,
val obsidianRobots: Int,
val geodeRobots: Int,
val timeLeft: Int
)
private data class Timeless(
val ore: Int,
val clay: Int,
val obsidian: Int,
val geode: Int,
val oreRobots: Int,
val clayRobots: Int,
val obsidianRobots: Int,
val geodeRobots: Int,
)
private data class Resources(
val ore: Int,
val clay: Int,
val obsidian: Int,
val geode: Int
) | 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 6,189 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindTheSmallestDivisorGivenThreshold.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <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
// Find the Smallest Divisor Given a Threshold
fun interface SmallestDivisorStrategy {
operator fun invoke(nums: IntArray, threshold: Int): Int
fun computeSum(nums: IntArray, x: Int): Long {
var s: Long = 0
for (n in nums) {
s += (n / x + if (n % x == 0) 0 else 1).toLong()
}
return s
}
}
class SmallestDivisorBinarySearch : SmallestDivisorStrategy {
override operator fun invoke(nums: IntArray, threshold: Int): Int {
// search boundaries for the divisor
var left = 1
var right = 2
while (computeSum(nums, right) > threshold) {
left = right
right = right shl 1
}
// binary search
while (left <= right) {
val pivot = left + (right - left shr 1)
val num: Long = computeSum(nums, pivot)
if (num > threshold) {
left = pivot + 1
} else {
right = pivot - 1
}
}
// at the end of loop, left > right,
// computeSum(right) > threshold
// computeSum(left) <= threshold
// --> return left
return left
}
}
class SmallestDivisorMath : SmallestDivisorStrategy {
override operator fun invoke(nums: IntArray, threshold: Int): Int {
// binary search
// binary search
var left = 1
var right = nums[nums.size - 1]
while (left <= right) {
val pivot = left + (right - left shr 1)
val num = computeSum(nums, pivot).toInt()
if (num > threshold) {
left = pivot + 1
} else {
right = pivot - 1
}
}
// at the end of loop, left > right,
// computeSum(right) > threshold
// computeSum(left) <= threshold
// --> return left
// at the end of loop, left > right,
// computeSum(right) > threshold
// computeSum(left) <= threshold
// --> return left
return left
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,685 | kotlab | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/ThreeSum.kt | faniabdullah | 382,893,751 | false | null | //Given an integer array nums, return all the triplets [nums[i], nums[j], nums[
//k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
//
// Notice that the solution set must not contain duplicate triplets.
//
//
// Example 1:
// Input: nums = [-1,0,1,2,-1,-4]
//Output: [[-1,-1,2],[-1,0,1]]
// Example 2:
// Input: nums = []
//Output: []
// Example 3:
// Input: nums = [0]
//Output: []
//
//
// Constraints:
//
//
// 0 <= nums.length <= 3000
// -10⁵ <= nums[i] <= 10⁵
//
// Related Topics Array Two Pointers Sorting 👍 13427 👎 1296
package algorithms.twopointer
class ThreeSum {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun threeSum(nums: IntArray): List<List<Int>> {
var res = HashSet<List<Int>>()
nums.sort()
for (i in 0 until nums.lastIndex - 1) {
var j = i + 1
var k = nums.lastIndex
val tmp = -nums[i]
while (j < k) {
val sum = nums[j] + nums[k]
when {
sum == tmp -> {
res.add(listOf(nums[i], nums[j], nums[k]))
j++
k--
}
sum < tmp -> {
j++
}
else -> {
k--
}
}
}
}
return res.toList()
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 1,799 | dsa-kotlin | MIT License |
src/main/kotlin/com/psmay/exp/advent/y2021/Day03.kt | psmay | 434,705,473 | false | {"Kotlin": 242220} | package com.psmay.exp.advent.y2021
import com.psmay.exp.advent.y2021.util.transpose
object Day03 {
private fun gammaAndEpsilonBits(comparedCountsPerColumn: List<Int>): Pair<List<Boolean>, List<Boolean>> {
val gammaBits = gammaBits(comparedCountsPerColumn)
val epsilonBits = gammaBits.map { !it }
return gammaBits to epsilonBits
}
private fun gammaBits(comparedCountsPerColumn: List<Int>): List<Boolean> =
comparedCountsPerColumn.mapIndexed() { i, x ->
if (x < 0) false
else if (x > 0) true
else throw IllegalArgumentException("Column at index $i has an equal number of true and false values.")
}
private fun compareCountsPerColumn(columns: List<List<Boolean>>): List<Int> = columns.map { column ->
val (trueCount, falseCount) = counts(column)
trueCount.compareTo(falseCount)
}
private fun counts(column: List<Boolean>): Pair<Int, Int> {
val counts = column
.groupBy { it }
.map { (k, v) -> k to v.size }
.associate { it }
val trueCount = counts[true] ?: 0
val falseCount = counts[false] ?: 0
return trueCount to falseCount
}
private fun mostCommon(input: List<Boolean>): Boolean? {
val (trueCount, falseCount) = counts(input)
val compared = trueCount.compareTo(falseCount)
return if (compared == 0) null else (compared > 0)
}
private fun leastCommon(input: List<Boolean>): Boolean? {
val (trueCount, falseCount) = counts(input)
val compared = trueCount.compareTo(falseCount)
return if (compared == 0) null else (compared < 0)
}
private fun applyBitCriteria(
rows: List<List<Boolean>>,
getPreferredValue: (List<Boolean>) -> Boolean,
): List<Boolean> {
var remainingRows = rows
val columnCount = rows.minOfOrNull { it.size } ?: 0
// NB: If I were confident that I could get it to work without too many tries, this would probably be a swell
// place for a tail recursion.
for (columnIndex in 0 until columnCount) {
val column = remainingRows.map { it[columnIndex] }
val preferredValue = getPreferredValue(column)
remainingRows = remainingRows.filter { it[columnIndex] == preferredValue }
if (remainingRows.count() == 1) {
return remainingRows[0]
}
}
throw IllegalStateException("Bit criteria filtering resulted in a number of lines other than 1 (${remainingRows.size}).")
}
private fun applyOxygenGeneratorRatingBitCriteria(rows: List<List<Boolean>>) =
applyBitCriteria(rows) { mostCommon(it) ?: true }
private fun applyCo2ScrubberRatingBitCriteria(rows: List<List<Boolean>>) =
applyBitCriteria(rows) { leastCommon(it) ?: false }
private fun parseBinary(input: List<Boolean>) = input
.joinToString("") { if (it) "1" else "0" }
.toInt(2)
fun part1(input: List<List<Boolean>>): Int {
val columns = input.transpose()
val comparedCountsPerColumn = compareCountsPerColumn(columns)
val (gammaBits, epsilonBits) = gammaAndEpsilonBits(comparedCountsPerColumn)
val gamma = parseBinary(gammaBits)
val epsilon = parseBinary(epsilonBits)
return gamma * epsilon
}
fun part2(input: List<List<Boolean>>): Int {
val oxygenGeneratorRatingBits = applyOxygenGeneratorRatingBitCriteria(input)
val co2ScrubberRatingBits = applyCo2ScrubberRatingBitCriteria(input)
val oxygenGeneratorRating = parseBinary(oxygenGeneratorRatingBits)
val co2ScrubberRating = parseBinary(co2ScrubberRatingBits)
return oxygenGeneratorRating * co2ScrubberRating
}
} | 0 | Kotlin | 0 | 0 | c7ca54612ec117d42ba6cf733c4c8fe60689d3a8 | 3,799 | advent-2021-kotlin | Creative Commons Zero v1.0 Universal |
src/Day04.kt | zsmb13 | 572,719,881 | false | {"Kotlin": 32865} | fun main() {
fun parse(input: List<String>) = input
.map { line ->
val (a1, a2) = line.substringBefore(',').split('-').map(String::toInt)
val (b1, b2) = line.substringAfter(',').split('-').map(String::toInt)
(a1..a2) to (b1..b2)
}
operator fun IntRange.contains(other: IntRange) =
other.first in this && other.last in this
fun part1(input: List<String>) = parse(input)
.count { (r1, r2) -> r1 in r2 || r2 in r1 }
fun part2(input: List<String>) = parse(input)
.count { (r1, r2) -> r1.intersect(r2).isNotEmpty() }
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 6 | 32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35 | 809 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/java/com/droidhats/mapprocessor/AStar.kt | RobertBeaudenon | 232,313,026 | false | null | package com.droidhats.mapprocessor
/**
* Main data structure that we use to hold the vertices in the graph
*/
class Vertex(circle: Circle, endPoint: Pair<Double, Double>) {
val pos: Pair<Double, Double> = Pair(circle.cx, circle.cy)
val heuristic: Double = getDistance(pos, endPoint)
var prev: Vertex? = null
private var value: Double? = null
private var sum: Double? = null
val neighbors: MutableList<Vertex> = mutableListOf()
/**
* set the value of this vertex and update its sum based on the heuristic function
* @param value to update
*/
fun setValue(value: Double) {
this.value = value
sum = value + 1.5 * heuristic
}
/**
* Return the value of this vertex
* @return value
*/
fun getValue(): Double? = value
/**
* Return the sum
* @return sum
*/
fun getSum(): Double? = sum
/**
* Remove popped node from the neighbors of this vertex
* @param poppedNode
*/
fun removeFromNeighbors(poppedNode: Vertex) {
for (neighborInd in neighbors.indices) {
if (neighbors[neighborInd] == poppedNode) {
neighbors.removeAt(neighborInd)
return
}
}
}
}
/**
* A priority queue of next nodes to examine.
* They are ordered from lowest sum to highest
*/
class PriorityQueue {
private val queue: MutableList<Vertex> = mutableListOf()
/**
* Inserts the vertex at the proper position
* @param vertex to insert
*/
fun insert(vertex: Vertex) {
for (indVertex in queue.indices) {
if (vertex.getSum()!! < queue[indVertex].getSum()!!) {
// set it in its proper position
queue.add(indVertex, vertex)
return
}
}
// case that it has the biggest sum
queue.add(vertex)
}
/**
* Returns the first vertex in the list
* @return vertex
*/
fun pop(): Vertex? {
if (queue.size == 0) return null
return queue.removeAt(0)
}
/**
* Determine whether the vertex is within the queue
* @param vertex to check
* @return whether it is not within the queue
*/
fun isNotWithin(vertex: Vertex): Boolean {
return vertex !in queue
}
/**
* Remove the vertex in the queue
* @param vertex to remove
*/
fun removeVertex(vertex: Vertex) {
queue.remove(vertex)
}
}
/**
* Find the nearest vertex to the given map element
* @param mapElement
* @param pathElements to search for the nearest point in
* @return nearest vertex
*/
fun findNearestPoint(mapElement: MapElement, pathElements: List<Vertex>): Vertex {
var nearestNode: Vertex = pathElements[0]
var smallestDistance: Double = getDistance(mapElement.getCenter(), nearestNode.pos)
for (vertex in pathElements) {
val distanceToNode = getDistance(mapElement.getCenter(), vertex.pos)
if(distanceToNode < smallestDistance) {
nearestNode = vertex
smallestDistance = distanceToNode
}
}
return nearestNode
}
/**
* Takes 2 map elements and returns the shortest path in between them given the list of path elements
* as an arrow
* @param start element where the user is starting from
* @param end or destination element to reach
* @param list of vertices connected in a graph
* @return string of the path
*/
fun getPath(start: MapElement, end: MapElement, pathElements: MutableList<Vertex>): String {
val startVertex = findNearestPoint(start, pathElements)
val endVertex = findNearestPoint(end, pathElements)
val path = aStar(startVertex, endVertex, start, end, pathElements)
if (path != null)
return path
// converting path to string
var cur: Vertex? = endVertex
val string: StringBuilder = StringBuilder()
while (cur?.prev != null) {
string.append(Path.createPath(cur.pos, cur.prev!!.pos))
cur = cur.prev
}
// check if the start and end vertices are the same
if(endVertex != cur) {
string.append(Circle.getPoint(cur!!.pos.first, cur.pos.second))
}
// Check if the path exists
if(endVertex.prev != null) {
// Get the start and end point of the last drawn path and use them to draw the arrow head paths
val lastDrawnPathStartPoint =
Circle(endVertex.prev!!.pos.first, endVertex.prev!!.pos.second, 2.0)
val lastDrawnPathEndPoint = Circle(endVertex.pos.first, endVertex.pos.second, 2.0)
val arrowHeadPaths: List<String> =
getArrowHeadPaths(lastDrawnPathStartPoint, lastDrawnPathEndPoint)
// Append the two arrow heads' paths to the string to be drawn on the map.
string.append(arrowHeadPaths[0])
string.append(arrowHeadPaths[1])
}
return string.toString()
}
/**
* A* algorithm for getting the shortest path quickly
* @param startVertex the vertex at the start of the path
* @param endVertex the vertex at the end of the path
* @param start the start element or place where the user is starting from
* @param end the end element or destination for where the user wants to go
* @param pathElements the elements along the path connected in a weighted graph
*/
fun aStar(
startVertex: Vertex,
endVertex: Vertex,
start: MapElement,
end: MapElement,
pathElements: MutableList<Vertex>
): String? {
val queue = PriorityQueue()
// A* algorithm part
var poppedNode: Vertex? = startVertex
while (poppedNode != endVertex) {
for (neighbor in poppedNode!!.neighbors) {
if (neighbor.getValue() == null || poppedNode.getValue()!! < neighbor.getValue()!!) {
neighbor.setValue(getDistance(poppedNode.pos, neighbor.pos))
neighbor.prev = poppedNode
if (!queue.isNotWithin(neighbor)) {
queue.removeVertex(neighbor)
}
}
neighbor.removeFromNeighbors(poppedNode)
if (queue.isNotWithin(neighbor)) {
queue.insert(neighbor)
}
}
poppedNode = queue.pop()
if (poppedNode == null) {
return getPath(start, end, removeStartAndEnd(startVertex, endVertex, pathElements))
}
}
return null
}
/**
* Removes the found start and end vertices from the inputted list and returns it.
* @param start vertex
* @param end vertex
* @param list of vertices
* @return new list of vertices
*/
fun removeStartAndEnd(start: Vertex, end: Vertex, list: MutableList<Vertex>): MutableList<Vertex> {
for (vertex in list) {
if (vertex == start || vertex == end) {
for (neighbor in vertex.neighbors) {
neighbor.removeFromNeighbors(vertex)
}
}
}
list.remove(start)
list.remove(end)
return list
}
| 4 | Kotlin | 4 | 7 | ea136a60a71f5d393f4a5688e86b9c56c6bea7b6 | 6,910 | SOEN390-CampusGuideMap | MIT License |
07/src/commonMain/kotlin/Main.kt | daphil19 | 725,415,769 | false | {"Kotlin": 131380} | import Card.Companion.toCardOrdinal
import Card.Companion.toCardOrdinalPart2
expect fun getLines(): List<String>
fun main() {
var lines = getLines()
// lines = """32T3K 765
//T55J5 684
//KK677 28
//KTJJT 220
//QQQJA 483""".lines()
part1(lines)
part2(lines)
}
enum class Card(val ch: Char) {
// ORDINAL ORDER MATTERS!
Two('2'), Three('3'), Four('4'), Five('5'), Six('6'), Seven('7'), Eight('8'), Nine('9'), Ten('T'), Jack('J'), Queen('Q'), King('K'), Ace('A');
companion object {
fun Char.toCard() = when(this) {
'2' -> Two
'3' -> Three
'4' -> Four
'5' -> Five
'6' -> Six
'7' -> Seven
'8' -> Eight
'9' -> Nine
'T' -> Ten
'J' -> Jack
'Q' -> Queen
'K' -> King
'A' -> Ace
else -> throw IllegalStateException("invalid char $this")
}
fun Char.toCardOrdinal() = toCard().ordinal
fun Char.toCardOrdinalPart2() = toCard().let {
if (it == Jack) {
// jacks are really jokers, and are the worst card for comparison
-1
} else it.ordinal
}
}
}
// TODO maybe sealed?
enum class Type {
//ORDINAL ORDER MATTERS!
FiveOfAKind,
FourOfAKind,
FullHouse,
ThreeOfAKind,
TwoPair,
Pair,
High
}
data class Hand(val hand: String, val bet: Long, val type: Type)
fun part1(lines: List<String>) = printDuration {
val res = lines.map { line ->
val (hand, bet) = line.split(" ").take(2)
val associations = hand.toCharArray().toSet().associateWith { ch -> hand.count { it == ch } }
val type = when {
associations.size == 1 -> Type.FiveOfAKind
associations.values.contains(4) -> Type.FourOfAKind
associations.values.containsAll(listOf(3,2)) -> Type.FullHouse
associations.values.contains(3) -> Type.ThreeOfAKind
associations.values.count { it == 2 } == 2 -> Type.TwoPair
associations.values.contains(2) -> Type.Pair
else -> Type.High
}
Hand(hand, bet.toLong(), type)
}.sortedWith(compareByDescending<Hand> { it.type.ordinal }.thenComparator { a, b ->
a.hand.zip(b.hand).first { it.first != it.second }.let {
(it.first.toCardOrdinal() compareTo it.second.toCardOrdinal())
}
})
// .onEach { println(it) }
.mapIndexed { index, hand -> hand.bet * (index+1) }
.sum()
println(res)
}
fun part2(lines: List<String>) = printDuration {
val res = lines.map { line ->
val (hand, bet) = line.split(" ").take(2)
val associations = hand.toCharArray().toSet().associateWith { ch -> hand.count { it == ch } }.toMutableMap()
associations[Card.Jack.ch]?.let {
// check to make sure we don't empty the list... ture IFF we have all jacks!
if (associations.size > 1) {
associations.remove(Card.Jack.ch)
}
val best = associations.maxBy { it.value }
associations[best.key] = it + best.value
}
val type = when {
associations.size == 1 -> Type.FiveOfAKind
associations.values.contains(4) -> Type.FourOfAKind
associations.values.containsAll(listOf(3,2)) -> Type.FullHouse
associations.values.contains(3) -> Type.ThreeOfAKind
associations.values.count { it == 2 } == 2 -> Type.TwoPair
associations.values.contains(2) -> Type.Pair
else -> Type.High
}
Hand(hand, bet.toLong(), type)
}.sortedWith(compareByDescending<Hand> { it.type.ordinal }.thenComparator { a, b ->
a.hand.zip(b.hand).first { it.first != it.second }.let {
(it.first.toCardOrdinalPart2() compareTo it.second.toCardOrdinalPart2())
}
})
// .onEach { println(it) }
.mapIndexed { index, hand -> hand.bet * (index+1) }
.sum()
println(res)
}
| 0 | Kotlin | 0 | 0 | 70646b330cc1cea4828a10a6bb825212e2f0fb18 | 4,062 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/com/rtarita/days/Day8.kt | RaphaelTarita | 570,100,357 | false | {"Kotlin": 79822} | package com.rtarita.days
import com.rtarita.structure.AoCDay
import com.rtarita.util.day
import kotlinx.datetime.LocalDate
object Day8 : AoCDay {
override val day: LocalDate = day(8)
private fun getGrid(input: String): List<List<Int>> {
return input.lineSequence()
.map { line ->
line.asSequence().map {
it.digitToInt()
}.toList()
}.toList()
}
private inline fun <R> List<List<Int>>.calculate(x: Int, y: Int, calculation: (gridval: Int, xList: List<Int>, yList: List<Int>) -> R): R {
return calculation(this[y][x], this[y], List(size) { this[it][x] })
}
override fun executePart1(input: String): Int {
val grid = getGrid(input)
return grid.indices.sumOf { y ->
grid[y].indices.count { x ->
grid.calculate(x, y) { height, xList, yList ->
(xList.subList(0, x).maxOrNull() ?: -1) < height
|| (xList.subList(x + 1, xList.size).maxOrNull() ?: -1) < height
|| (yList.subList(0, y).maxOrNull() ?: -1) < height
|| (yList.subList(y + 1, yList.size).maxOrNull() ?: -1) < height
}
}
}
}
override fun executePart2(input: String): Int {
val grid = getGrid(input)
return grid.indices.maxOf { y ->
grid[y].indices.maxOf { x ->
grid.calculate(x, y) { height, xList, yList ->
if (x == 0 || x == xList.lastIndex || y == 0 || y == yList.lastIndex) {
0
} else {
(xList.subList(1, x).takeLastWhile { it < height }.count() + 1) *
(xList.subList(x + 1, xList.lastIndex).takeWhile { it < height }.count() + 1) *
(yList.subList(1, y).takeLastWhile { it < height }.count() + 1) *
(yList.subList(y + 1, yList.lastIndex).takeWhile { it < height }.count() + 1)
}
}
}
}
}
} | 0 | Kotlin | 0 | 9 | 491923041fc7051f289775ac62ceadf50e2f0fbe | 2,144 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/g2801_2900/s2861_maximum_number_of_alloys/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2861_maximum_number_of_alloys
// #Medium #Array #Binary_Search #2023_12_21_Time_289_ms_(100.00%)_Space_43.8_MB_(100.00%)
import kotlin.math.max
class Solution {
fun maxNumberOfAlloys(
n: Int,
k: Int,
budget: Int,
composition: List<List<Int>>,
stock: List<Int>,
cost: List<Int>
): Int {
var ans = 0
var max = 0
for (i in 0 until n) {
max = max(stock[i].toDouble(), max.toDouble()).toInt()
}
for (i in 0 until k) {
var temp = 0
var low = 0
var high = max + budget
var mid: Int
while (low <= high) {
mid = low + (high - low) / 2
if (isPos(i, mid, n, budget, composition, stock, cost)) {
low = mid + 1
temp = mid
} else {
high = mid - 1
}
}
ans = max(ans.toDouble(), temp.toDouble()).toInt()
}
return ans
}
private fun isPos(
idx: Int,
mid: Int,
n: Int,
budget: Int,
composition: List<List<Int>>,
stock: List<Int>,
cost: List<Int>
): Boolean {
var paiSa = 0L
for (i in 0 until n) {
val require = (composition[idx][i].toLong()) * (mid)
val have = stock[i].toLong()
val diff = require - have
if (diff > 0) {
paiSa += diff * (cost[i].toLong())
}
if (budget < paiSa) {
return false
}
}
return budget >= paiSa
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,681 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/nibado/projects/advent/collect/SummedAreaTable.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.collect
import com.nibado.projects.advent.Point
// https://en.wikipedia.org/wiki/Summed-area_table
class SummedAreaTable private constructor(private val table: List<IntArray>) {
private fun get(p: Point) = get(p.x, p.y)
private fun get(x: Int, y: Int) = if(x < 0 || y < 0) { 0 } else table[y][x]
fun get(a: Point, b: Point) = get(a.x, a.y, b.x, b.y)
fun get(x1: Int, y1: Int, x2: Int, y2: Int): Int {
val a = Point(x1 - 1, y1 - 1)
val b = Point(x2, y1 - 1)
val c = Point(x1 - 1, y2)
val d = Point(x2, y2)
return get(a) + get(d) - get(b) - get(c)
}
override fun toString() = toString(4)
fun toString(width: Int): String {
val b = StringBuilder()
for (y in table.indices) {
for (x in table[0].indices) {
b.append("%1\$${width}s".format(table[y][x]))
}
b.append('\n')
}
return b.toString()
}
companion object {
fun from(table: List<IntArray>): SummedAreaTable {
return SummedAreaTable(build(table))
}
private fun build(table: List<IntArray>) : List<IntArray> {
val output = table.indices.map { IntArray(table[0].size) }.toList()
for (y in table.indices) {
for (x in table[0].indices) {
output[y][x] = table[y][x]
if (y > 0)
output[y][x] += output[y - 1][x]
if (x > 0) {
output[y][x] += output[y][x - 1]
if (y > 0)
output[y][x] -= output[y - 1][x - 1] // because this is added twice in above two additions
}
}
}
return output
}
}
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,848 | adventofcode | MIT License |
day10/main.kt | LOZORD | 441,007,912 | false | {"Kotlin": 29367, "Python": 963} | import java.util.Scanner
enum class LineStatus {
VALID,
INCOMPLETE,
CORRUPTED
}
data class StatusWithData(
val status: LineStatus,
val corruption: Char? = null,
val remaining: ArrayDeque<Char>? = null,
)
fun main(args: Array<String>) {
val input = Scanner(System.`in`)
val statuses = ArrayList<StatusWithData>()
while (input.hasNextLine()) {
val scanned = input.nextLine()
statuses.add(classifyLine(scanned.trim()))
}
if (args.contains("--part1")) {
val score = statuses
.filter { it.status == LineStatus.CORRUPTED }
.map { scoreCorruptedChar(it.corruption!!) }
.sum()
println("SCORE: $score")
return
}
val scores = statuses
.filter { it.status == LineStatus.INCOMPLETE }
.map { scoreIncompleteChars(it.remaining!!) }
val median = scores.sorted().get(scores.size / 2)
println("MEDIAN_SCORE: $median")
}
fun classifyLine(line: String): StatusWithData {
val stack = ArrayDeque<Char>()
for (char in line.toCharArray()) {
when (char) {
'(', '[', '{', '<' -> stack.addLast(char)
')', ']', '}', '>' -> {
if (stack.isEmpty()) {
return StatusWithData(LineStatus.CORRUPTED, char)
}
val popped = stack.removeLast()
val opener = getOpener(char)
if (popped != opener) {
return StatusWithData(LineStatus.CORRUPTED, char)
}
}
else -> throw IllegalArgumentException("character $char is not valid")
}
}
if (stack.isNotEmpty()) {
return StatusWithData(LineStatus.INCOMPLETE, remaining=stack)
}
return StatusWithData(LineStatus.VALID)
}
fun getOpener(c: Char): Char? {
when (c) {
')' -> return '('
']' -> return '['
'}' -> return '{'
'>' -> return '<'
else -> return null
}
}
fun getCloser(c: Char): Char? {
when (c) {
'(' -> return ')'
'[' -> return ']'
'{' -> return '}'
'<' -> return '>'
else -> return null
}
}
fun scoreCorruptedChar(c: Char): Int {
when (c) {
')' -> return 3
']' -> return 57
'}' -> return 1197
'>' -> return 25137
else -> throw IllegalArgumentException("can't score character $c")
}
}
fun scoreIncompleteChars(remaining: ArrayDeque<Char>): Long {
fun score(c: Char): Long {
val closer = getCloser(c)
when (closer) {
')' -> return 1
']' -> return 2
'}' -> return 3
'>' -> return 4
else -> throw IllegalArgumentException("can't score closer char $c")
}
}
var acc = 0L
for (c in remaining.reversed()) {
acc = (acc * 5L) + score(c)
}
return acc
} | 0 | Kotlin | 0 | 0 | 17dd266787acd492d92b5ed0d178ac2840fe4d57 | 2,909 | aoc2021 | MIT License |
src/day-7/part-2/solution-day-7-part-2.kts | d3ns0n | 572,960,768 | false | {"Kotlin": 31665} | import `day-7`.Directory
import `day-7`.File
import `day-7`.FileSystemItem
val root = Directory("/")
var currentDirectory = root
fun addFileSystemItem(string: String) {
if (string.startsWith("dir")) {
currentDirectory.content.add(Directory(string.substring(4), parent = currentDirectory))
} else {
val split = string.split(" ")
currentDirectory.content.add(File(split[1], split[0].toInt()))
}
}
fun processCommand(string: String) {
val command = string.removePrefix("$").trim()
if (command.startsWith("cd")) {
val target = command.removePrefix("cd").trim()
currentDirectory = when (target) {
"/" -> root
".." -> currentDirectory.parent
else -> currentDirectory.content.first { it is Directory && it.name == target } as Directory
}
}
}
fun process(string: String) {
if (string.startsWith("$")) {
processCommand(string)
} else {
addFileSystemItem(string)
}
}
fun findDirectoriesWithSizeFrom(
itemsToProcess: List<FileSystemItem>,
foundItems: MutableList<FileSystemItem>,
minSize: Int
): List<FileSystemItem> {
val directories = itemsToProcess.filterIsInstance<Directory>()
if (directories.isEmpty()) {
return foundItems
}
val firstDirectory = directories.first()
val remainingDirectories =
mutableListOf<FileSystemItem>(*directories.drop(1).toTypedArray()).apply {
this.addAll(firstDirectory.content)
}
if (firstDirectory.size >= minSize) {
foundItems.add(firstDirectory)
}
return findDirectoriesWithSizeFrom(remainingDirectories, foundItems, minSize)
}
java.io.File("../input.txt").readLines()
.forEach { process(it) }
val totalDiskSpace = 70000000
val desiredFreeDiskSpace = 30000000
val freeDiskSpace = totalDiskSpace - root.size
val neededDiskSpace = desiredFreeDiskSpace - freeDiskSpace
val wantedDirectorySize =
findDirectoriesWithSizeFrom(root.content, mutableListOf(), neededDiskSpace)
.sortedBy { it.size }
.first()
.size
println(wantedDirectorySize)
assert(wantedDirectorySize == 5649896)
| 0 | Kotlin | 0 | 0 | 8e8851403a44af233d00a53b03cf45c72f252045 | 2,164 | advent-of-code-22 | MIT License |
src/day24/Day24.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | package day24
import readInput
enum class Direction(val symbol: Char, val vec: Position) {
UP('^', Position(-1, 0)),
RIGHT('>', Position(0, 1)),
DOWN('v', Position(1, 0)),
LEFT('<', Position(0, -1));
companion object {
private val symbolMap = Direction.values().associateBy { it.symbol }
fun fromSymbol(symbol: Char): Direction {
return symbolMap[symbol]!!
}
}
}
data class Position(val row: Int, val column: Int) {
operator fun plus(other: Position): Position {
return Position(row + other.row, column + other.column)
}
operator fun minus(other: Position): Position {
return Position(row - other.row, column - other.column)
}
}
data class Blizzard(val position: Position, val direction: Direction)
fun wrapSingleCoordinate(coordinate: Int, restriction: Int): Int {
return (restriction + (coordinate - 1)) % restriction + 1
}
fun moveWrapped(blizzard: Blizzard, valleyHeight: Int, valleyWidth: Int): Blizzard {
val dummyNextPosition = blizzard.position + blizzard.direction.vec
val row = wrapSingleCoordinate(dummyNextPosition.row, valleyHeight)
val column = wrapSingleCoordinate(dummyNextPosition.column, valleyWidth)
return Blizzard(Position(row, column), blizzard.direction)
}
@Suppress("Unused")
fun printState(
valleyHeight: Int,
valleyWidth: Int,
blizzards: Set<Blizzard>,
walls: Set<Position>,
ourPositions: Set<Position>
) {
val blizzardCounts = blizzards.groupBy { it.position }
.map {
it.key to if (it.value.size == 1) {
it.value[0].direction.symbol
} else {
it.value.size.toString()[0]
}
}.toMap()
for (row in 0..valleyHeight + 1) {
for (column in 0..valleyWidth + 1) {
when (val pos = Position(row, column)) {
in walls -> print("#")
in blizzardCounts -> print(blizzardCounts[pos])
in ourPositions -> print("E")
else -> print('.')
}
}
println()
}
}
fun findPath(
start: Position,
finish: Position,
walls: Set<Position>,
valleyHeight: Int,
valleyWidth: Int,
startBlizzards: Set<Blizzard>
): Pair<Int, Set<Blizzard>> {
var possiblePositions = setOf(start)
var requiredSteps = 0
var blizzards = startBlizzards
while (!possiblePositions.contains(finish)) {
++requiredSteps
val nextBlizzards = mutableSetOf<Blizzard>()
for (blizzard in blizzards) {
nextBlizzards.add(moveWrapped(blizzard, valleyHeight, valleyWidth))
}
val nextBlizzardPositions = nextBlizzards.map { it.position }.toSet()
val nextPossiblePositions = mutableSetOf<Position>()
for (position in possiblePositions) {
val neigbours = Direction.values().map { it.vec + position }
val options = neigbours + listOf(position)
val filteredOptions = options.filter { !walls.contains(it) && !nextBlizzardPositions.contains(it) }
/*
if (requiredSteps < 3) {
println("Considering $position")
println("neigbours $neigbours")
println("options $options")
println("filtered $filteredOptions")
println()
}
*/
nextPossiblePositions.addAll(filteredOptions)
}
possiblePositions = nextPossiblePositions
blizzards = nextBlizzards
// println("Step $requiredSteps, total positions: ${nextPossiblePositions.size}")
// println("$possiblePositions")
//printState(valleyHeigh, valleyWidth, blizzards, walls, possiblePositions)
}
return requiredSteps to blizzards
}
fun solve(input: List<String>): Pair<Int, Int> {
val valleyHeigh = input.size - 2
val valleyWidth = input[0].length - 2
val walls = mutableSetOf<Position>()
val startPosition = Position(0, input.first().indexOf('.'))
val finishPosition = Position(input.size - 1, input.last().indexOf('.'))
walls.add(startPosition + Direction.UP.vec)
walls.add(finishPosition + Direction.DOWN.vec)
val blizzards = mutableSetOf<Blizzard>()
for (row in input.indices) {
for (column in input[row].indices) {
val symbol = input[row][column]
if (symbol in Direction.values().map { it.symbol }) {
blizzards.add(Blizzard(Position(row, column), Direction.fromSymbol(symbol)))
}
if (symbol == '#') {
walls.add(Position(row, column))
}
}
}
val (stepsToFinish, blizzards1) = findPath(startPosition, finishPosition, walls, valleyHeigh, valleyWidth, blizzards)
val (stepsBack, blizzards2) = findPath(finishPosition, startPosition, walls, valleyHeigh, valleyWidth, blizzards1)
val (stepsToFinishAgain, _) = findPath(startPosition, finishPosition, walls, valleyHeigh, valleyWidth, blizzards2)
return stepsToFinish to stepsToFinish + stepsBack + stepsToFinishAgain
}
fun main() {
println("Day 24")
val testInput = readInput("Day24-test")
val input = readInput("Day24")
val (testAns1, testAns2) = solve(testInput)
println("test part1: $testAns1")
println("test part2: $testAns2")
val (ans1, ans2) = solve(input)
println("real part1: $ans1")
println("real part2: $ans2")
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 5,439 | aoc-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.