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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/SecretService/KylesMathPack.kt | PartlyFluked | 126,126,943 | false | {"C++": 129610, "C": 98209, "Kotlin": 10802, "CMake": 2384} | package com.example.SecretService
/**
* Created by menta on 29/03/2018.
*/
import java.lang.Math.pow
fun List<Int>.innerProduct(B:List<Int>): Int {
return zip(B)
.map { it.first * it.second }
.sum()
}
fun List<Int>.vandermond(): List<List<Int>> {
return map { xval -> List<Int>(size, {it:Int -> pow(xval.toDouble(), it.toDouble()).toInt()}) }
}
fun List<Int>.polyeval(input: Int): Int {
return foldIndexed(0, {index:Int, soFar:Int, next:Int -> soFar + next*pow(input.toDouble(), index.toDouble()).toInt()})
//foldRight(0, { soFar, alpha -> alpha + soFar * input })
}
fun List<Int>.polyAdd(summand:List<Int>): List<Int> {
return mapIndexed{index, next -> next + summand.get(index)}
}
fun List<Int>.polyMult(multipland: List<Int>): List<Int> {
return foldIndexed( multipland , { index, soFar, next -> soFar
.polyAdd(List<Int>( index,{0}) + multipland.map{it*next} )
})
}
fun List<List<Int>>.transpose(): List<List<Int>> {
return mapIndexed{ rownum, row -> row.mapIndexed{ colnum, col -> get(colnum)[rownum] }
}
}
fun List<List<Int>>.submatrix( droprow: Int, dropcol: Int ): List<List<Int>> {
return filterIndexed { index, _ -> index != droprow }
.map { it.filterIndexed { index, _ -> index != dropcol } }
.fold( listOf(), { current, next -> current.plusElement(next) } )
}
fun List<List<Int>>.det(): Int {
return if (size > 1) mapIndexed { colnum, _ -> submatrix(0, colnum).det() }
.mapIndexed { index, entry -> entry * pow(-1.0, index.toDouble()).toInt() }
.innerProduct( get(0) ) else get(0)[0]
}
fun List<List<Int>>.cofactor(): List<List<Int>> {
return mapIndexed { rownum: Int, row: List<Int> -> row.mapIndexed { colnum, _ -> submatrix(rownum, colnum).det()* pow(-1.0, (colnum+rownum).toDouble()).toInt() }
}
}
fun List<List<Int>>.invert(): List<List<Int>>{
return cofactor()
.transpose()
.map{ row -> row
.map{ entry -> entry }} //divide det()
}
fun List<List<Int>>.matrixMultiplyRight( B: List<List<Int>> ): List<List<Int>> {
return mapIndexed { rownum:Int, brow -> brow
.mapIndexed { colnum:Int, _ -> brow
.innerProduct( B.transpose()[colnum] )
}
}
} | 0 | C++ | 0 | 0 | d2540dcd1e362b2224b65fc63f1adca4689516ec | 2,308 | PASS-android | Apache License 2.0 |
src/main/kotlin/Puzzle13.kt | namyxc | 317,466,668 | false | null | import java.math.BigInteger
object Puzzle13 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle13::class.java.getResource("puzzle13.txt").readText()
val earliestBusNumberMultipledByWaitTime = earliestBusNumberMultipledByWaitTime(input)
println(earliestBusNumberMultipledByWaitTime)
println(firstAfterOtherStarts(input))
}
fun earliestBusNumberMultipledByWaitTime(input: String): Int {
val lines = input.split("\n")
val timeOfArrive = lines.first().toInt()
val busNumbers = lines[1].split(",").filterNot { it == "x" }.map(String::toInt)
val waitTimes = busNumbers.map { it to it - (timeOfArrive % it) }.minByOrNull { it.second }!!
return waitTimes.first * waitTimes.second
}
fun firstAfterOtherStarts(input: String): BigInteger {
val lines = input.split("\n")
val busNumbers = lines[1].split(",").mapIndexed{ idx, value -> value to idx}.filterNot { it.first == "x" }.map { it.first.toBigInteger() to it.second.toBigInteger() }
val M = busNumbers.fold(BigInteger.ONE) { prod, element -> prod * element.first}
var x = BigInteger.ZERO
busNumbers.forEach { pair ->
val bNumer = pair.first
val index = pair.second
val m = M/bNumer
val firstComponent = Eucledian(m, bNumer).calculate().first
val d = (bNumer-index) % bNumer
x += (d * firstComponent * m)
}
while (x < M) x += M
return x%M
}
class Eucledian(a: BigInteger, b:BigInteger){
private var q = mutableListOf(BigInteger.ZERO,BigInteger.ZERO)
private var r = mutableListOf(a,b)
private var x = mutableListOf(BigInteger.ONE,BigInteger.ZERO)
private var y = mutableListOf(BigInteger.ZERO,BigInteger.ONE)
private var i = 2
private fun makeOneStep(): Boolean{
q.add(r[i-2] / r[i-1])
r.add(r[i-2] % r[i-1])
x.add(x[i-2] - q[i] * x[i-1])
y.add(y[i-2] - q[i] * y[i-1])
i++
return r.last() == BigInteger.ONE
}
fun calculate(): Pair<BigInteger, BigInteger>{
while (!makeOneStep()) {}
return Pair(x.last(), y.last())
}
}
} | 0 | Kotlin | 0 | 0 | 60fa6991ac204de6a756456406e1f87c3784f0af | 2,296 | adventOfCode2020 | MIT License |
src/main/kotlin/io/dmitrijs/aoc2022/Day08.kt | lakiboy | 578,268,213 | false | {"Kotlin": 76651} | package io.dmitrijs.aoc2022
class Day08(input: List<String>) {
private val size = input.size
private val grid = input.map { row ->
row.map { it.digitToInt() }
}
fun puzzle1() = (size * 4 - 4) + (1 until (size - 1)).sumOf { y ->
(1 until (size - 1)).count { x -> Point(x, y).visible }
}
fun puzzle2() = (0 until size).maxOf { y ->
(0 until size).maxOf { x -> Point(x, y).visibleTrees }
}
private val Point.value get() = grid[y][x]
private val Point.edge get() = x == 0 || y == 0 || x == size - 1 || y == size - 1
private val Point.invalid get() = x !in 0 until size || y !in 0 until size
private val Point.visible get() = Direction.values().any { direction ->
visibleTowards(direction.move, 1)
}
private val Point.visibleTrees get() = Direction.values().fold(1) { acc, direction ->
acc * visibleCount(direction.move, 1)
}
private tailrec fun Point.visibleTowards(move: Point, distance: Int): Boolean {
val neighbour = move * distance + this
return when {
neighbour.value >= value -> false
neighbour.edge -> true
else -> visibleTowards(move, distance + 1)
}
}
private tailrec fun Point.visibleCount(move: Point, distance: Int): Int {
val neighbour = move * distance + this
return when {
neighbour.invalid -> distance - 1
neighbour.value >= value -> distance
else -> visibleCount(move, distance + 1)
}
}
}
| 0 | Kotlin | 0 | 1 | bfce0f4cb924834d44b3aae14686d1c834621456 | 1,547 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day07.kt | acunap | 573,116,784 | false | {"Kotlin": 23918} | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
@OptIn(ExperimentalTime::class)
fun main() {
fun parseDirectories(input: List<String>) = buildMap {
put("", 0)
var cwd = ""
for(line in input) {
val match = """[$] cd (.*)|(\d*).*""".toRegex().matchEntire(line) ?: continue
match.groups[1]?.value?.let { dir ->
cwd = when (dir) {
"/" -> ""
".." -> cwd.substringBeforeLast("/", "")
else -> if (cwd.isEmpty()) dir else "$cwd/$dir"
}
} ?: match.groups[2]?.value?.toIntOrNull()?.let { size ->
var dir = cwd
while (true) {
put(dir, getOrElse(dir) { 0 } + size)
if (dir.isNullOrEmpty()) break
dir = dir.substringBeforeLast("/", "")
}
}
}
}
fun part1(input: List<String>) = parseDirectories(input).values.sumOf { if (it < 100_000) it else 0 }
fun part2(input: List<String>): Int {
val sizes = parseDirectories(input)
val totalSize = sizes.values.max()
return sizes.values.filter { 70_000_000 - totalSize + it > 30_000_000 }.min()
}
val time = measureTime {
val input = readLines("Day07")
println(part1(input))
println(part2(input))
}
println("Real data time $time")
val timeTest = measureTime {
val testInput = readLines("Day07_test")
check(part1(testInput) == 95_437)
check(part2(testInput) == 24_933_642)
}
println("Test data time $timeTest.")
}
| 0 | Kotlin | 0 | 0 | f06f9b409885dd0df78f16dcc1e9a3e90151abe1 | 1,667 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day22.kt | Yeah69 | 317,335,309 | false | {"Kotlin": 73241} | class Day22 : Day() {
override val label: String get() = "22"
private val initialDecks by lazy {
fun String.toDeck(): List<Int> = this.lineSequence().drop(1).mapNotNull { it.toIntOrNull() }.toList()
val split = input.split("\r\n\r\n")
split[0].toDeck() to split[1].toDeck()
}
private fun List<Int>.privateHash(): Int = (this.size downTo 1).zip(this).sumBy { it.first * it.second }
data class Situation(val zero: List<Int>, val one: List<Int>) {
private fun List<Int>.privateHash(): Int = (this.size downTo 1).zip(this).sumBy { it.first * it.second }
private val hashZero: Int = zero.privateHash()
private val hashOne: Int = one.privateHash()
val hash: Int = hashZero * hashOne
override fun hashCode(): Int =
hash
override fun equals(other: Any?): Boolean =
if (other is Situation) other.zero == this.zero && other.one == this.one
else false
}
val alreadyPlayedGames = mutableMapOf<Situation, Situation>()
override fun taskZeroLogic(): String {
val zerothPlayerDeck = initialDecks.first.toMutableList()
val firstPlayerDeck = initialDecks.second.toMutableList()
while (zerothPlayerDeck.any() && firstPlayerDeck.any()) {
if (zerothPlayerDeck.first() > firstPlayerDeck.first()) {
zerothPlayerDeck.add(zerothPlayerDeck.first())
zerothPlayerDeck.add(firstPlayerDeck.first())
}
else {
firstPlayerDeck.add(firstPlayerDeck.first())
firstPlayerDeck.add(zerothPlayerDeck.first())
}
zerothPlayerDeck.removeAt(0)
firstPlayerDeck.removeAt(0)
}
val winningDeck = if(zerothPlayerDeck.any()) zerothPlayerDeck else firstPlayerDeck
return winningDeck.privateHash().toString()
}
fun recursiveCombat(gameSituation: Situation): Situation {
fun round(roundSituation: Situation): Situation {
val zerothFirst = roundSituation.zero.first()
val firstFirst = roundSituation.one.first()
val zeroWon = if(zerothFirst <= roundSituation.zero.size - 1 &&
firstFirst <= roundSituation.one.size - 1) {
val situation = Situation(zero = roundSituation.zero.drop(1).take(zerothFirst), one = roundSituation.one.drop(1).take(firstFirst))
val resultSituation = recursiveCombat(situation)
alreadyPlayedGames[situation] = resultSituation
resultSituation.zero.any()
}
else zerothFirst > firstFirst
return if (zeroWon) Situation(roundSituation.zero.drop(1) + zerothFirst + firstFirst, roundSituation.one.drop(1))
else Situation(roundSituation.zero.drop(1), roundSituation.one.drop(1) + firstFirst + zerothFirst)
}
var situation = gameSituation
if (alreadyPlayedGames.containsKey(situation))
return alreadyPlayedGames[situation]!!
val alreadyPlayed = mutableMapOf(situation.hash to mutableListOf(situation))
while (situation.zero.any() && situation.one.any()) {
situation = round(situation)
if (alreadyPlayed.containsKey(situation.hash) &&
alreadyPlayed[situation.hash]?.any { it == situation } == true) {
return Situation(zero = situation.zero, one = listOf())
}
else if (alreadyPlayed.containsKey(situation.hash)) alreadyPlayed[situation.hash]?.add(situation)
else alreadyPlayed[situation.hash] = mutableListOf(situation)
}
return situation
}
override fun taskOneLogic(): String {
val pair = recursiveCombat(Situation(zero = initialDecks.first, one = initialDecks.second))
val winningDeck = if (pair.zero.any()) pair.zero else pair.one
return winningDeck.privateHash().toString()
}
} | 0 | Kotlin | 0 | 0 | 23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec | 3,958 | AdventOfCodeKotlin | The Unlicense |
src/main/kotlin/aoc2015/Matchsticks.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2015
import komu.adventofcode.utils.nonEmptyLines
fun matchsticks(input: String): Int {
val lines = input.nonEmptyLines()
return lines.sumBy { it.length } - lines.sumBy { it.decodedLength() }
}
fun matchsticks2(input: String): Int {
val lines = input.nonEmptyLines()
return lines.sumBy { it.encodedLength() } - lines.sumBy { it.length }
}
private fun String.decodedLength(): Int {
require(first() == '"' || last() == '"')
tailrec fun loop(s: String, count: Int = 0): Int = when {
s.isEmpty() -> count
s.startsWith("\\\\") -> loop(s.drop(2), count + 1)
s.startsWith("\\\"") -> loop(s.drop(2), count + 1)
s.startsWith("\\x") -> loop(s.drop(4), count + 1)
s.startsWith("\\") -> error(s)
else -> loop(s.drop(1), count + 1)
}
return loop(substring(1, length - 1))
}
private fun String.encodedLength() = 2 + sumBy { if (it == '"' || it == '\\') 2 else 1 }
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 968 | advent-of-code | MIT License |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem009.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
/**
* Problem 9
*
* A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
*
* a^2 + b^2 = c^2
*
* For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
*
* There exists exactly one Pythagorean triplet for which a + b + c = 1000.
* Find the product abc.
*/
class Problem009 : Problem {
private infix fun <A, B, C> Pair<A, B>.to(c: C) =
Triple(this.first, this.second, c)
private fun Triple<Long, Long, Long>.isPythagorean() =
first * first + second * second == third * third
override fun solve(): Long {
val (a, b, c) = (1..332L)
.flatMap { a -> LongRange(a + 1, (1000 - a) / 2).map { b -> a to b } }
.map { (a, b) -> a to b to 1000 - a - b }
.first { it.isPythagorean() }
return a * b * c
}
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 846 | project-euler | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2018/Day12.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2018
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.e
import java.lang.RuntimeException
fun main() = Day12.run()
object Day12 : Day(2018, 12) {
private val rules: Set<String> = parseRules(input.lines())
private val initialState: String = input.lines().first().substring(15)
private fun parseRules(input: List<String>): Set<String> =
input
.drop(2)
.filter { it.endsWith("#") }
.map { it.take(5) }
.toSet()
override fun part1(): Any {
return updatePlants().drop(19).first().second
}
override fun part2(): Any {
val targetGeneration: Long = 50_000_000_000
var previousDiff = 0L
var previousSize = 0L
var generationNumber = 0
// Go through the sequence until we find one that grows the same one as its previous generation
updatePlants().dropWhile { thisGen ->
val thisDiff = thisGen.second - previousSize // Our diff to last generation
if (thisDiff != previousDiff) {
// Still changing
previousDiff = thisDiff
previousSize = thisGen.second
generationNumber += 1
true
} else {
// We've found it, stop dropping.
false
}
}.first() // Consume first because sequences are lazy and it won't start otherwise.
return previousSize + (previousDiff * (targetGeneration - generationNumber))
}
private fun updatePlants(state: String = initialState): Sequence<Pair<String, Long>> = sequence {
var zeroIndex = 0
var currentState = state
while (true) {
while (!currentState.startsWith(".....")) {
currentState = ".$currentState"
zeroIndex++
}
while (!currentState.endsWith(".....")) {
currentState = "$currentState."
}
currentState = currentState
.toList()
.windowed(5, 1)
.map { it.joinToString(separator = "") }
.map { if (it in rules) '#' else '.' }
.joinToString(separator = "")
zeroIndex -= 2 // Because there are two positions to the left of the first real center and were not evaluated
yield(Pair(currentState, currentState.sumIndexesFrom(zeroIndex)))
}
}
private fun String.sumIndexesFrom(zero: Int): Long =
this.mapIndexed { idx, c -> if (c == '#') idx.toLong() - zero else 0 }.sum()
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,612 | adventofkotlin | MIT License |
src/Day04.kt | cgeesink | 573,018,348 | false | {"Kotlin": 10745} | fun main() {
fun part1(input: List<String>): Int {
val data = input.map { it.asRanges() }
return data.count { it.first fullyOverlaps it.second || it.second fullyOverlaps it.first }
}
fun part2(input: List<String>): Int {
val data = input.map { it.asRanges() }
return data.count { it.first overlaps it.second }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun String.asIntRange(): IntRange = substringBefore("-").toInt()..substringAfter("-").toInt()
fun String.asRanges(): Pair<IntRange, IntRange> = substringBefore(",").asIntRange() to substringAfter(",").asIntRange()
infix fun IntRange.fullyOverlaps(other: IntRange): Boolean = first <= other.first && last >= other.last
infix fun IntRange.overlaps(other: IntRange): Boolean = first <= other.last && other.first <= last | 0 | Kotlin | 0 | 0 | 137fb9a9561f5cbc358b7cfbdaf5562c20d6b10d | 1,053 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day5.kt | andilau | 573,139,461 | false | {"Kotlin": 65955} | package days
@AdventOfCodePuzzle(
name = "Supply Stacks",
url = "https://adventofcode.com/2022/day/5",
date = Date(day = 5, year = 2022)
)
class Day5(input: List<String>) : Puzzle {
private val stacks = input
.takeWhile { it.isNotBlank() }
.reversed().drop(1)
.map { line -> line.indices.filter { (it - 1) % 4 == 0 }.map { line[it] } }
.toStacks()
private val procedures = input
.dropWhile { it.isNotBlank() }.drop(1)
.map { line -> Procedure.from(line) }
override fun partOne(): String = stacks.deepCopy().moveElements { it }
override fun partTwo(): String = stacks.deepCopy().moveElements { it.reversed() }
private fun List<List<Char>>.toStacks() =
(0..this.maxOf { it.lastIndex })
.map { ix -> this.mapNotNull { it.getOrNull(ix) }.dropLastWhile { !it.isLetter() }.toArrayDeque() }
private fun List<ArrayDeque<Char>>.moveElements(transform: (List<Char>) -> List<Char>) =
procedures.fold(this) { stacks, p ->
val (quantity, from, to) = p
val slice: List<Char> = (1..quantity).mapNotNull { stacks[from].removeLastOrNull() }
stacks[to].addAll(transform(slice))
stacks
}.joinToString("") { it.last().toString() }
data class Procedure(val quantity: Int, val from: Int, val to: Int) {
companion object {
private val linePattern = Regex("""move (\d+) from (\d+) to (\d+)""")
fun from(line: String): Procedure {
val find = linePattern.find(line) ?: throw IllegalArgumentException("Check your input: $line")
val (move, from, to) = find.groupValues.drop(1).map(String::toInt)
return Procedure(move, from - 1, to - 1)
}
}
}
private fun <T> List<T>.toArrayDeque() = ArrayDeque(this)
private fun <T> List<ArrayDeque<T>>.deepCopy() = this.map { it.toArrayDeque() }
}
| 0 | Kotlin | 0 | 0 | da824f8c562d72387940844aff306b22f605db40 | 1,948 | advent-of-code-2022 | Creative Commons Zero v1.0 Universal |
rakeKotlin/src/main/java/tech/ippon/rakekotlin/KeywordsExtractor.kt | JulianClemot | 550,972,261 | false | {"Kotlin": 61528} | package tech.ippon.rakekotlin
import java.util.*
import kotlin.math.max
class KeywordsExtractor(stopWords: List<String> = stopWordsFr) {
private val stopWordsRegex: Regex by lazy {
stopWords.joinToString(separator = STOP_WORDS_DELIMITER) { "\\b$it(?![\\w-])" }.toRegex()
}
fun extract(content: String): Map<String, Double> {
val sentences: List<String> = getSentences(content)
val keywords: List<String> = getKeywords(sentences)
val wordScores: Map<String, Double> = calculateWordScores(keywords)
val keywordsCandidates: Map<String, Double> =
getCandidateKeywordScores(keywords, wordScores)
return keywordsCandidates.toList().sortedByDescending { it.second }.toMap()
}
private fun getSentences(content: String): List<String> =
content.split(SENTENCES_SPLITTER_REGEX.toRegex()).filter { it.isNotBlank() }
private fun getKeywords(sentences: List<String>): List<String> =
sentences
.asSequence()
.map { it.trim().replace(stopWordsRegex, STOP_WORDS_DELIMITER) }
.map { it.split("\\$STOP_WORDS_DELIMITER".toRegex()) }
.map {
it.map { phrase ->
phrase.trim().lowercase(Locale.getDefault())
}
}
.flatten()
.filter { it.isNotBlank() }
.toList()
private fun calculateWordScores(phrases: List<String>): Map<String, Double> {
val wordFrequencies = mutableMapOf<String, Int>()
val wordDegrees = mutableMapOf<String, Int>()
val wordScores = mutableMapOf<String, Double>()
phrases.forEach {
val words = separateWords(it)
val degree = max(MINIMUM_DEGREE_SCORE, words.size - 1)
words.forEach { word ->
wordFrequencies[word] = wordFrequencies.getOrDefault(word, 0) + 1
wordDegrees[word] = wordDegrees.getOrDefault(word, 0) + degree
}
}
wordFrequencies.keys.forEach { frequenciesKey ->
wordScores[frequenciesKey] =
wordDegrees.getOrDefault(
frequenciesKey,
0
).toDouble() / wordFrequencies.getOrDefault(
frequenciesKey,
MINIMUM_DEGREE_SCORE
).toDouble()
}
return wordScores
}
private fun getCandidateKeywordScores(
keywords: List<String>,
wordScores: Map<String, Double>
): Map<String, Double> = keywords.associateWith {
separateWords(it).sumOf { word -> wordScores.getOrDefault(word, 0.0) }
}
private fun separateWords(sentences: String) =
sentences
.split(WORDS_SPLITTER_REGEX.toRegex())
.map { it.trim().lowercase(Locale.getDefault()) }
.filter { it.isNotEmpty() }
companion object {
private const val SENTENCES_SPLITTER_REGEX =
"[.!?,;:\\t\\\\\"\\\\(\\\\)\\u2019\\u2013]|\\\\s\\\\-\\\\s"
private const val WORDS_SPLITTER_REGEX = "(\\s|[.;:,])+"
private const val STOP_WORDS_DELIMITER = "|"
private const val MINIMUM_DEGREE_SCORE = 1
}
} | 0 | Kotlin | 1 | 2 | e1ff792d2a2cff1be0074e7806507e9cdd530824 | 3,214 | Ocear | MIT License |
src/Day01.kt | treegem | 572,875,670 | false | {"Kotlin": 38876} | import common.readInput
fun main() {
val day = "01"
fun part1(input: List<String>): Int {
val caloriesGrouped = groupCaloriesByElf(input)
return caloriesGrouped.maxOf { it.sum() }
}
fun part2(input: List<String>): Int {
val caloriesGrouped = groupCaloriesByElf(input)
return caloriesGrouped
.map { it.sum() }
.sorted()
.takeLast(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 24_000)
check(part2(testInput) == 45_000)
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
}
private fun groupCaloriesByElf(input: List<String>): MutableList<MutableList<Int>> {
val caloriesGrouped = mutableListOf<MutableList<Int>>()
input.forEachIndexed() { index, inputString ->
if (index == 0 || inputString.isBlank()) {
caloriesGrouped.add(mutableListOf())
} else {
caloriesGrouped.last().add(inputString.toInt())
}
}
return caloriesGrouped
}
| 0 | Kotlin | 0 | 0 | 97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8 | 1,159 | advent_of_code_2022 | Apache License 2.0 |
src/day03/Day03.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day03
import utils.*
fun findDuplicate(lines: List<Set<Char>>): Char = lines.reduce { acc, chars ->
acc.intersect(chars)
}.single()
fun getPriority(c: Char): Int =
1 + (c.lowercaseChar() - 'a') + c.isUpperCase().compareTo(false) * 26
fun part1(input: List<String>): Int = input.sumOf { line ->
getPriority(findDuplicate(line.chunked(line.length / 2).map { it.toSet() }))
}
fun part2(input: List<String>): Int = input.chunked(3).sumOf { lines ->
getPriority(findDuplicate(lines.map { it.toSet() }))
}
fun main() {
val testInput = readInput("Day03_test")
expect(part1(testInput), 157)
expect(part2(testInput), 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 744 | AOC-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/com/adventofcode/year2021/day3/part1/App.kt | demidko | 433,889,383 | false | {"Kotlin": 7692, "Dockerfile": 264} | package com.adventofcode.year2021.day3.part1
import com.adventofcode.year2021.day
import java.math.BigInteger
/**
* Calculates bits in one column
*/
class BitColumn {
private var trueCounter = 0L
private var falseCounter = 0L
fun collectBit(bit: Char) {
when (bit) {
'0' -> ++falseCounter
'1' -> ++trueCounter
}
}
fun mostCommonBit(): Char {
check(trueCounter != falseCounter)
return when (trueCounter > falseCounter) {
true -> '1'
else -> '0'
}
}
fun leastCommonBit(): Char {
return when (mostCommonBit()) {
'0' -> '1'
else -> '0'
}
}
}
/**
* Calculates bits in 12 columns
*/
class PowerCalculator(private val columnsCount: Int) {
private val bitColumn = Array(columnsCount) { BitColumn() }
fun collectBits(bits: String) {
bits.forEachIndexed { index, bit ->
bitColumn[index].collectBit(bit)
}
}
private fun gamma(): BigInteger {
val g = bitColumn.map(BitColumn::mostCommonBit).toCharArray().let(::String)
return BigInteger(g, 2)
}
private fun epsilon(): BigInteger {
val e = bitColumn.map(BitColumn::leastCommonBit).toCharArray().let(::String)
return BigInteger(e, 2)
}
fun calculatePower(): BigInteger {
return gamma() * epsilon()
}
}
/**
* [Day 3 Part 1](https://adventofcode.com/2021/day/3)
*/
fun main() {
val calculator = PowerCalculator(12)
day(3) {
let(calculator::collectBits)
}
println(calculator.calculatePower())
} | 0 | Kotlin | 0 | 0 | 2f42bede3ed0c4b17cb2575f6b61a1917a465bda | 1,488 | adventofcode | MIT License |
src/leetcodeProblem/leetcode/editor/en/WordSearch.kt | faniabdullah | 382,893,751 | false | null | //Given an m x n grid of characters board and a string word, return true if
//word exists in the grid.
//
// The word can be constructed from letters of sequentially adjacent cells,
//where adjacent cells are horizontally or vertically neighboring. The same letter
//cell may not be used more than once.
//
//
// Example 1:
//
//
//Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word =
// "ABCCED"
//Output: true
//
//
// Example 2:
//
//
//Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word =
// "SEE"
//Output: true
//
//
// Example 3:
//
//
//Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word =
// "ABCB"
//Output: false
//
//
//
// Constraints:
//
//
// m == board.length
// n = board[i].length
// 1 <= m, n <= 6
// 1 <= word.length <= 15
// board and word consists of only lowercase and uppercase English letters.
//
//
//
// Follow up: Could you use search pruning to make your solution faster with a
//larger board?
// Related Topics Array Backtracking Matrix 👍 7371 👎 280
package leetcodeProblem.leetcode.editor.en
class WordSearch {
fun solution() {
}
//below code is used to auto submit to leetcode.com (using ide plugin)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun exist(board: Array<CharArray>, word: String): Boolean {
val m = board.size;
val n = board[0].size
val dx = intArrayOf(1, -1, 0, 0)
val dy = intArrayOf(0, 0, 1, -1)
val seen = Array(m) { BooleanArray(n) }
fun dfs(x: Int, y: Int, start: Int): Boolean {
if (start == word.length) return true
if (x < 0 || x >= m || y < 0 || y >= n ||
seen[x][y] || board[x][y] != word[start]
) {
return false
}
seen[x][y] = true
for (i in 0..3) {
if (dfs(x + dx[i], y + dy[i], start + 1)) {
return true
}
}
seen[x][y] = false
return false
}
for (i in 0..m - 1) {
for (j in 0..n - 1) {
if (board[i][j] == word[0]) {
if (dfs(i, j, 0)) {
return true
}
}
}
}
return false
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,635 | dsa-kotlin | MIT License |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day13/day13.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day13
import biz.koziolek.adventofcode.*
import kotlin.math.min
fun main() {
val inputFile = findInput(object {})
val notes = parseNotes202313(inputFile.bufferedReader().readLines())
println("Summarized notes: ${notes.summarize()}")
println("Summarized notes with fixed smudges: ${notes.fixSmudges().summarize(notes)}")
}
data class Notes202313(val patterns: List<RocksPattern>) {
fun summarize(previousNotes: Notes202313? = null): Int =
if (previousNotes == null) {
patterns.mapNotNull { it.findReflection()?.summarize() }.sum()
} else {
patterns.zip(previousNotes.patterns)
.map { (currentPattern, previousPattern) ->
val currentReflections = currentPattern.findReflections()
val previousReflections = previousPattern.findReflections()
currentReflections.subtract(previousReflections).single()
}
.sumOf { it.summarize() }
}
fun fixSmudges(): Notes202313 =
Notes202313(patterns.map { it.fixSmudge()!! })
}
const val ROCK = '#'
const val ASH = '.'
data class RocksPattern(val contents: List<String>) {
val width = contents[0].length
val height = contents.size
fun findReflection(): Reflection? =
findReflections().singleOrNullOnlyWhenZero()
fun findReflections(): Set<Reflection> =
findReflections(contents)
private fun findReflections(lines: List<String>): Set<Reflection> =
buildSet {
addAll(findHorizontalReflections(lines))
addAll(findVerticalReflections(lines))
}
private fun findVerticalReflections(lines: List<String>): Set<VerticalReflection> =
findReflectionIndexes(lines)
.mapTo(mutableSetOf()) { VerticalReflection(it) }
private fun findHorizontalReflections(lines: List<String>): Set<HorizontalReflection> =
findReflectionIndexes(lines.transpose())
.mapTo(mutableSetOf()) { HorizontalReflection(it) }
private fun findReflectionIndexes(lines: List<String>): Set<Int> {
val mirrorAfter = mutableSetOf<Int>()
for (index in lines.indices) {
if (index == lines.size - 1) {
continue
}
var matches = true
for (distance in 0..min(index, lines.size - 2 - index)) {
if (lines[index - distance] != lines[index + 1 + distance]) {
matches = false
break
}
}
if (matches) {
mirrorAfter.add(index)
}
}
return mirrorAfter
}
@Suppress("unused")
fun toStringWithReflection(): String =
buildString {
val reflection = findReflection()
for ((rowIndex, line) in contents.withIndex()) {
for ((columnIndex, char) in line.withIndex()) {
append(char)
if (reflection is HorizontalReflection && columnIndex == reflection.afterColumn) {
append(AsciiColor.BRIGHT_WHITE.format("|"))
}
}
append("\n")
if (reflection is VerticalReflection && rowIndex == reflection.afterRow) {
append(AsciiColor.BRIGHT_WHITE.format("-".repeat(line.length)) + "\n")
}
}
}
fun fixSmudge(): RocksPattern? {
val smudge = findSmudge(contents) ?: findSmudge(contents, horizontalReflection = true)
return if (smudge != null) {
RocksPattern(contents = replaceSmudge(contents, smudge))
} else {
null
}
}
private fun findSmudge(lines: List<String>, horizontalReflection: Boolean = false): Coord? {
val currentLines = if (horizontalReflection) lines.transpose() else lines
val existingReflections = findReflections(currentLines)
for (index in currentLines.indices) {
if (index == currentLines.size - 1) {
continue
}
for (distance in 0..min(index, currentLines.size - 2 - index)) {
val indexA = index - distance
val indexB = index + 1 + distance
val lineA = currentLines[indexA]
val lineB = currentLines[indexB]
val differences = findDifferences(lineA, lineB)
if (differences.size == 1) {
val smudgePos = Coord(
x = differences.single(),
y = indexA,
)
val newLines = replaceSmudge(currentLines, smudgePos)
val newReflections = findReflections(newLines)
if (newReflections.subtract(existingReflections).isNotEmpty()) {
return if (horizontalReflection) {
Coord(x = smudgePos.y, y = smudgePos.x)
} else {
smudgePos
}
}
}
}
}
return null
}
private fun findDifferences(a: String, b: String): List<Int> =
a.zip(b).mapIndexedNotNull { index, pair ->
if (pair.first != pair.second) index else null
}
private fun replaceSmudge(lines: List<String>, smudge: Coord) =
lines.mapIndexed { y, line ->
if (y == smudge.y) {
line.withIndex().joinToString("") { (x, char) ->
if (x == smudge.x) {
char.swap(ROCK, ASH)
} else {
char
}.toString()
}
} else {
line
}
}
companion object {
fun fromString(string: String): RocksPattern =
RocksPattern(string.split("\n"))
}
}
sealed interface Reflection {
fun summarize(): Int
}
data class HorizontalReflection(val afterColumn: Int) : Reflection {
override fun summarize(): Int = afterColumn + 1
}
data class VerticalReflection(val afterRow: Int) : Reflection {
override fun summarize(): Int = (afterRow + 1) * 100
}
fun parseNotes202313(lines: Iterable<String>): Notes202313 =
buildList {
var pattern = mutableListOf<String>()
lines.forEach { line ->
if (line.isBlank()) {
add(RocksPattern(pattern))
pattern = mutableListOf()
} else {
pattern.add(line)
}
}
if (pattern.isNotEmpty()) {
add(RocksPattern(pattern))
}
}.let { Notes202313(it) }
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 6,781 | advent-of-code | MIT License |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day14.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
import com.akikanellis.adventofcode.year2022.utils.Point
object Day14 {
private val SAND_STARTING_POINT = Point(500, 0)
fun unitsOfSandRestingBeforeFreefall(input: String) =
unitsOfSandResting(input, sandFreeFalls = true)
fun unitsOfSandRestingWhenFull(input: String) =
unitsOfSandResting(input, sandFreeFalls = false)
private fun unitsOfSandResting(input: String, sandFreeFalls: Boolean): Int {
val rockAndSandPoints = scannedRockPoints(input)
val minRockXWithoutFloor = rockAndSandPoints.minOf { it.x }
val maxRockXWithoutFloor = rockAndSandPoints.maxOf { it.x }
val maxRockYWithoutFloor = rockAndSandPoints.maxOf { it.y }
rockAndSandPoints += floorRockPoints(
minRockXWithoutFloor,
maxRockXWithoutFloor,
maxRockYWithoutFloor
)
var moreSandCanFit = true
var amountOfRestingSand = 0
while (moreSandCanFit) {
var currentSandPoint = SAND_STARTING_POINT
var sandIsMoving = true
while (sandIsMoving) {
if (sandFreeFalls && currentSandPoint.y > maxRockYWithoutFloor) {
sandIsMoving = false
moreSandCanFit = false
} else if (currentSandPoint.plusY() !in rockAndSandPoints) {
currentSandPoint = currentSandPoint.plusY()
} else if (currentSandPoint.minusX().plusY() !in rockAndSandPoints) {
currentSandPoint = currentSandPoint.minusX().plusY()
} else if (currentSandPoint.plusX().plusY() !in rockAndSandPoints) {
currentSandPoint = currentSandPoint.plusX().plusY()
} else {
rockAndSandPoints += currentSandPoint
amountOfRestingSand++
sandIsMoving = false
}
}
if (SAND_STARTING_POINT in rockAndSandPoints) {
moreSandCanFit = false
}
}
return amountOfRestingSand
}
private fun scannedRockPoints(input: String) = input
.lines()
.filter { it.isNotBlank() }
.flatMap {
it
.split(" -> ")
.map { coordinates ->
coordinates
.split(",")
.let { xAndY -> Point(xAndY[0].toInt(), xAndY[1].toInt()) }
}
.zipWithNext()
.flatMap { (leftPoint, rightPoint) ->
(leftPoint.x..rightPoint.x).map { x -> leftPoint.copy(x = x) } +
(leftPoint.y..rightPoint.y).map { y -> leftPoint.copy(y = y) } +
(rightPoint.x..leftPoint.x).map { x -> rightPoint.copy(x = x) } +
(rightPoint.y..leftPoint.y).map { y -> rightPoint.copy(y = y) }
}
}.toMutableSet()
private fun floorRockPoints(
minX: Int,
maxX: Int,
maxY: Int
) = (minX - maxY..maxX + maxY).map { x -> Point(x, maxY + 2) }
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 3,141 | advent-of-code | MIT License |
calendar/day15/Day15.kt | starkwan | 573,066,100 | false | {"Kotlin": 43097} | package day15
import Day
import Lines
import kotlin.math.abs
class Day15 : Day() {
override fun part1(input: Lines): Any {
val targetY = 2000000
val sensorsAtTargetY = mutableSetOf<Int>()
val beaconsAtTargetY = mutableSetOf<Int>()
val infeasibleAtTargetY = mutableSetOf<Int>()
val regex = """Sensor at x=([-]?\d+), y=([-]?\d+): closest beacon is at x=([-]?\d+), y=([-]?\d+)""".toRegex()
for (line in input) {
regex.findAll(line)
.map { result -> result.groups.drop(1).map { it!!.value.toInt() } }
.forEach { (sx, sy, bx, by) ->
if (sy == targetY) sensorsAtTargetY.add(sx)
if (by == targetY) beaconsAtTargetY.add(bx)
val mDistance = abs(sy - by) + abs(sx - bx)
val mDistanceAtTargetY = mDistance - abs(sy - targetY)
if (mDistanceAtTargetY >= 0) {
for (step in 0..mDistanceAtTargetY) {
infeasibleAtTargetY.add(sx - step)
infeasibleAtTargetY.add(sx + step)
}
}
}
}
infeasibleAtTargetY.removeAll(sensorsAtTargetY + beaconsAtTargetY)
return infeasibleAtTargetY.size
}
override fun part2(input: Lines): Any {
val env = Environment(input)
return env.findBeacon().let { it.x.toLong() * 4000000 + it.y.toLong() }
}
class Environment(input: Lines) {
private val sensors = mutableListOf<Cell>()
private val regex =
"""Sensor at x=([-]?\d+), y=([-]?\d+): closest beacon is at x=([-]?\d+), y=([-]?\d+)""".toRegex()
private val min = 0
private val max = 4000000
init {
for (line in input) {
regex.findAll(line)
.map { result -> result.groups.drop(1).map { it!!.value.toInt() } }
.forEach { (sx, sy, bx, by) ->
val mDistance = abs(sy - by) + abs(sx - bx)
sensors.add(Cell(sx, sy, mDistance))
}
}
}
fun findBeacon(): Cell {
for (y in 0..max) {
findBeaconAtY(y)?.let { return it }
}
error("failed to find")
}
private fun getCellAt(x: Int, y: Int): Cell {
val step = sensors.map { sensor ->
val mDistanceTraveled = abs(x - sensor.x) + abs(y - sensor.y)
sensor.steps - mDistanceTraveled // remaining steps at x,y
}.max()
return Cell(x, y, maxOf(-1, step))
}
private fun findBeaconAtY(y: Int): Cell? {
var cell = getCellAt(min, y)
while (cell.x <= max) {
if (cell.steps == -1) {
return cell
}
cell = getCellAt(cell.x + cell.steps + 1, y)
}
return null
}
}
/**
* @param steps guaranteed no beacon can be found within number of steps(mDistance)
*/
data class Cell(val x: Int, val y: Int, val steps: Int)
} | 0 | Kotlin | 0 | 0 | 13fb66c6b98d452e0ebfc5440b0cd283f8b7c352 | 3,198 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | arisaksen | 573,116,584 | false | {"Kotlin": 42887} | import org.assertj.core.api.Assertions.assertThat
// https://adventofcode.com/2022/day/4
fun main() {
fun part1(items: List<String>): Int =
items
.map { it.split(",") }
.map { it.map { range -> (range.substringBefore("-").toInt()..range.substringAfter("-").toInt()) } }
.also { it.map { println(it) } }
.filter { it.first() intRangeContains it.last() } // Util.kt
.size
// .count { it.first() intRangeContains it.last() } // tip: count replaces both .filter and size
fun part2(items: List<String>): Int =
items
.map { it.split(",") }
.map { it.map { range -> (range.substringBefore("-").toInt()..range.substringAfter("-").toInt()) } }
.also { it.map { println(it) } }
.map { it.first() intersect it.last() }
.filter { it.isNotEmpty() }
.size
// .count { it.isNotEmpty() } // tip: count replaces both .filter and size
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
assertThat(part1(testInput)).isEqualTo(2)
assertThat(part2(testInput)).isEqualTo(4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 85da7e06b3355f2aa92847280c6cb334578c2463 | 1,300 | aoc-2022-kotlin | Apache License 2.0 |
src/Day02.kt | papichulo | 572,669,466 | false | {"Kotlin": 16864} | import kotlin.IllegalArgumentException
fun main() {
fun part2(input: List<String>): Int {
return input.sumOf { when(it) {
"A X" -> 3
"A Y" -> 4
"A Z" -> 8
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 2
"C Y" -> 6
"C Z" -> 7
else -> throw IllegalArgumentException()
}.toInt()
}
}
fun part1(input: List<String>): Int {
return input.sumOf { when(it) {
"A X" -> 4
"A Y" -> 8
"A Z" -> 3
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 7
"C Y" -> 2
"C Z" -> 6
else -> throw IllegalArgumentException()
}.toInt()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e277ee5bca823ce3693e88df0700c021e9081948 | 1,083 | aoc-2022-in-kotlin | Apache License 2.0 |
2016/src/main/kotlin/com/koenv/adventofcode/Day3.kt | koesie10 | 47,333,954 | false | null | package com.koenv.adventofcode
object Day3 {
fun isTrianglePossible(input: String) = isTrianglePossible(getSides(input))
private fun isTrianglePossible(sides: List<Int>) = isTrianglePossible(sides[0], sides[1], sides[2])
private fun isTrianglePossible(a: Int, b: Int, c: Int): Boolean {
if (a + b <= c) {
return false
}
if (b + c <= a) {
return false
}
if (c + a <= b) {
return false
}
return true
}
private fun getSides(input: String): List<Int> {
val sides = input.split(" ")
.filter(String::isNotBlank)
.map(String::toInt)
if (sides.size != 3) {
throw IllegalArgumentException("A triangle must have 3 sides: $input")
}
return sides
}
fun getPossibleTriangles(input: String): Int {
return input.lines()
.filter(String::isNotBlank)
.map { isTrianglePossible(it) }
.sumBy { if (it) 1 else 0 }
}
fun getPossibleTrianglesByColumn(input: String): Int {
val lines = input.lines().filter(String::isNotBlank)
var possibilities = 0
for (i in 0..(lines.size - 1) step 3) {
val sides = lines.subList(i, i + 3)
.map { getSides(it) }
.flatten()
for (j in 0..2) {
if (isTrianglePossible(sides[j], sides[j + 3], sides[j + 6])) {
possibilities++
}
}
}
return possibilities
}
} | 0 | Kotlin | 0 | 0 | 29f3d426cfceaa131371df09785fa6598405a55f | 1,608 | AdventOfCode-Solutions-Kotlin | MIT License |
src/array/LeetCode88.kt | Alex-Linrk | 180,918,573 | false | null | package array
/**
* 合并两个有序数组
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
思路:
因为是两个有序数组,为了避免移动数组的麻烦,从后往前比较,
将有效的最大值放在最后面,并向前移动并继续前面的过程,完成整个过程
并且要判断是num2是有比较头,如果没有则将num2直接放放到数组头
*/
class Solution88 {
fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit {
var big = m
var other = n
var p = big-- + other-- - 1
while (big >= 0 && other >= 0) {
nums1[p--] = if (nums1[big] > nums2[other]) nums1[big--] else nums2[other--]
}
while (other >= 0) {
nums1[p--] = nums2[other--]
}
}
}
fun main() {
val nums1 = intArrayOf(1, 2, 3, 0, 0, 0)
val nums2 = intArrayOf(2, 5, 6)
Solution88().merge(nums1, 3, nums2 = nums2, n = 3)
println(nums1.toList())
} | 0 | Kotlin | 0 | 0 | 59f4ab02819b7782a6af19bc73307b93fdc5bf37 | 1,316 | LeetCode | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/container_with_most_water/ContainerWithMostWater.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.container_with_most_water
import nonstdlib.listOfInts
import datsok.shouldEqual
import org.junit.Test
import kotlin.random.Random
/**
* https://leetcode.com/problems/container-with-most-water
*/
class ContainerWithMostWaterTests {
@Test fun `some examples`() {
listOf(1, 1).findMaxContainer() shouldEqual 1
listOf(1, 2).findMaxContainer() shouldEqual 1
listOf(2, 1).findMaxContainer() shouldEqual 1
listOf(1, 2, 3).findMaxContainer() shouldEqual 2
listOf(2, 2, 3).findMaxContainer() shouldEqual 4
listOf(2, 7, 7, 2).findMaxContainer() shouldEqual 7
listOf(1, 8, 6, 2, 5, 4, 8, 3, 7).findMaxContainer() shouldEqual 49
}
@Test fun `huge list`() {
val hugeList = Random(seed = 123).listOfInts(size = 1_000_000, valuesRange = 0 until 1000)
hugeList.findMaxContainer() shouldEqual 997958043
}
private fun List<Int>.findMaxContainer(): Int {
if (size < 2) error("")
var maxVolume = 0
var from = 0
var to = size
while (from < to) {
val volume = minOf(this[from], this[to - 1]) * (to - from - 1)
maxVolume = maxOf(maxVolume, volume)
if (this[from] < this[to - 1]) from++ else to--
}
return maxVolume
}
private fun List<Int>.findMaxContainer__(): Int {
if (size < 2) error("")
var maxVolume = 0
val maxDepth = sorted()[size - 2]
(1..maxDepth).forEach { depth ->
val from = indexOfFirst { it >= depth }
val to = indexOfLast { it >= depth }
val volume = minOf(this[from], this[to]) * (to - from)
if (volume > maxVolume) maxVolume = volume
}
return maxVolume
}
private fun List<Int>.findMaxContainer_(): Int {
var maxVolume = 0
(0..size - 2).forEach { from ->
(from + 2..size).forEach { to ->
val volume = minOf(this[from], this[to - 1]) * (to - from - 1)
if (volume > maxVolume) maxVolume = volume
}
}
return maxVolume
}
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,141 | katas | The Unlicense |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem035.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.common.isEven
import dev.mikeburgess.euler.sequences.PrimeSequence
import kotlin.math.floor
import kotlin.math.log10
import kotlin.math.pow
/**
* The number 197 is called a circular prime because all rotations of the digits: 197, 971, and 719,
* are themselves prime.
*
* There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
*
* How many circular primes are there below one million?
*/
class Problem035 : Problem {
private fun length(n: Long) =
floor(log10(n.toDouble())).toInt() + 1
private fun rotate(n: Long, length: Int) =
(((n % 10) * (10f).pow(length)).toLong() + n) / 10
private fun rotations(n: Long) =
generateSequence(n) { rotate(it, length(n)) }
.take(length(n))
.toList()
override fun solve(): Long {
val isCircular = mutableMapOf(2L to true)
val primes = PrimeSequence().takeWhile { it < 1_000_000 }.toList()
for (prime in primes) {
if (!isCircular.containsKey(prime)) {
val rotations = rotations(prime)
val isPrime = rotations.none(Long::isEven) && primes.containsAll(rotations)
rotations.forEach { isCircular.putIfAbsent(it, isPrime) }
}
}
return isCircular.filterValues { it }.count().toLong()
}
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 1,418 | project-euler | MIT License |
kotlin/src/katas/kotlin/leetcode/knapsack/Knapsack.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.knapsack
import nonstdlib.*
import datsok.*
import org.junit.*
/**
* Guided by Priyo based on
* https://medium.com/@fabianterh/how-to-solve-the-knapsack-problem-with-dynamic-programming-eb88c706d3cf
*/
class KnapsackTests {
@Test fun `find maximum amount of meetings fitting hours`() {
optimise(setOf(Meeting(1)), hours = 0) shouldEqual emptySet()
optimise(setOf(Meeting(1)), hours = 1) shouldEqual setOf(Meeting(1))
optimise(setOf(Meeting(2)), hours = 1) shouldEqual emptySet()
optimise(setOf(Meeting(2), Meeting(4), Meeting(1), Meeting(6)), hours = 8) shouldEqual
setOf(Meeting(1), Meeting(2), Meeting(4))
}
@Test fun `find meetings that fill hours as close to maximum as possible`() {
optimise2(setOf(Meeting(2), Meeting(4), Meeting(1), Meeting(6)), hours = 8) shouldEqual listOf(
setOf(Meeting(2), Meeting(6))
)
optimise2(setOf(Meeting(4), Meeting(5), Meeting(6), Meeting(9)), hours = 9) shouldEqual listOf(
setOf(Meeting(9)), setOf(Meeting(4), Meeting(5))
)
optimise2(setOf(Meeting(2), Meeting(4), Meeting(5), Meeting(6)), hours = 9) shouldEqual listOf(
setOf(Meeting(4), Meeting(5))
)
}
@Test fun `caching results`() {
findMaxValue(
maxCapacity = 10,
items = listOf(
Item(size = 5, value = 10),
Item(size = 4, value = 40),
Item(size = 6, value = 30),
Item(size = 3, value = 50)
)
).let { (maxValues, maxValue) ->
maxValues.joinToString("\n") { it.toList().toString() } shouldEqual """
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10]
[0, 0, 0, 0, 40, 40, 40, 40, 40, 50, 50]
[0, 0, 0, 0, 40, 40, 40, 40, 40, 50, 70]
[0, 0, 0, 50, 50, 50, 50, 90, 90, 90, 90]
""".trimIndent()
maxValue shouldEqual 90
}
findMaxValue(
maxCapacity = 9,
items = listOf(
Item(size = 5, value = 1),
Item(size = 4, value = 1),
Item(size = 8, value = 1)
)
).let { (maxValues, _) ->
maxValues.joinToString("\n") { it.toList().toString() }.printed()/* shouldEqual """
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10]
[0, 0, 0, 0, 40, 40, 40, 40, 40, 50, 50]
[0, 0, 0, 0, 40, 40, 40, 40, 40, 50, 70]
[0, 0, 0, 50, 50, 50, 50, 90, 90, 90, 90]
""".trimIndent()*/
// maxValue shouldEqual 90
}
}
}
private data class Item(val size: Int, val value: Int)
private fun findMaxValue(maxCapacity: Int, items: List<Item>): Pair<Array<IntArray>, Int> {
val maxValues = Array(items.size + 1) { IntArray(maxCapacity + 1) }
items.forEachIndexed { itemIndex, (weight, value) ->
(1..maxCapacity).forEach { capacity ->
val maxValueWithoutItem = maxValues[itemIndex][capacity]
val maxValueWithItem = if (capacity < weight) 0 else {
val remainingCapacity = capacity - weight
value + maxValues[itemIndex][remainingCapacity]
}
maxValues[itemIndex + 1][capacity] = maxOf(maxValueWithoutItem, maxValueWithItem)
}
}
return Pair(maxValues, maxValues[items.size][maxCapacity])
}
private fun optimise2(meetings: Set<Meeting>, hours: Int): List<Set<Meeting>> {
fun Set<Meeting>.duration() = sumBy { it.hours }
val bestMeetings = doOptimise2(meetings, hours).sortedBy { -it.duration() }
return bestMeetings
.takeWhile { it.duration() == bestMeetings.first().duration() }
.sortedBy { it.size }
}
private fun doOptimise2(meetings: Set<Meeting>, hours: Int): List<Set<Meeting>> {
if (hours < 0) return emptyList()
if (meetings.isEmpty()) return listOf(emptySet())
val meeting = meetings.last()
return doOptimise2(meetings - meeting, hours) +
doOptimise2(meetings - meeting, hours - meeting.hours).map { it + meeting }
}
private fun optimise(meetings: Set<Meeting>, hours: Int): Set<Meeting> {
val sorted = meetings.sortedBy { it.hours }.toMutableList()
var hoursLeft = hours
val result = LinkedHashSet<Meeting>()
while (sorted.isNotEmpty()) {
val meeting = sorted.removeAt(0)
hoursLeft -= meeting.hours
if (hoursLeft < 0) break
result.add(meeting)
}
return result
}
private data class Meeting(val hours: Int) {
override fun toString() = hours.toString()
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 4,737 | katas | The Unlicense |
src/main/kotlin/_2022/Day03.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
fun main() {
fun findCommonChar(strings: List<String>): Collection<Char> {
return strings.map { it.toSet() }
.reduce(Set<Char>::intersect)
}
fun getCharPriority(it: Char): Int {
var result = (it - 'a') + 1
if (result < 0) {
result += 58
}
return result
}
fun part1(input: List<String>): Int {
return input.sumOf {
val chunked = it.chunked(it.length / 2)
val chars = findCommonChar(chunked)
chars.map(::getCharPriority).sum()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf {
val chars = findCommonChar(it)
chars.map(::getCharPriority).sum()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 1,064 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dp/SOS.kt | yx-z | 106,589,674 | false | null | package dp
import java.util.*
// shortest oscillating supersequence
// find the definition of an oscillating sequence in 'LOS'
// find the definition of a supersequence in 'SCS'
// find sos of A[1..n] here
fun main(args: Array<String>) {
val A = intArrayOf(3, 10, 15, 9, 29)
println(sos(A))
}
fun sos(A: IntArray): Int {
val n = A.size
// sos(i): len of sos for A[i..n]
// so's(i): len of so's for A[i..n]
// where so's is the shortest oscillating' supersequence
// also find the definition of oscillating' sequence in 'LOS'
// sos(i), so's(i) = 0 if i > n
// sos(i), so's(i) = 1 if i = n
// sos(i) = 2 + sos(i + 1) if A[i] < A[i + 1]
// so's(i) = 1 + sos(i + 1) if A[i] < A[i + 1]
// sos(i) = 1 + so's(i + 1) o/w
// so's(i) = 2 + so's(i + 1) o/w
val sos = IntArray(n)
val soos = IntArray(n)
sos[n - 1] = 1
soos[n - 1] = 1
for (i in n - 2 downTo 0) {
sos[i] = if (A[i] < A[i + 1]) {
2 + sos[i + 1]
} else {
1 + soos[i + 1]
}
soos[i] = if (A[i] < A[i + 1]) {
1 + sos[i + 1]
} else {
2 + soos[i + 1]
}
}
println(Arrays.toString(sos))
println(Arrays.toString(soos))
return sos[0]
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,135 | AlgoKt | MIT License |
src/main/kotlin/solutions/Day17PyroclasticFlow.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import models.Coord2d
import models.Grid
import utils.Input
import utils.Solution
import kotlin.math.max
// run only this day
fun main() {
Day17PyroclasticFlow()
}
class Day17PyroclasticFlow : Solution() {
init {
begin("Day 17 - Pyroclastic Flow")
val input = Input.parseAllText(filename = "/d17_rocks_and_jets.txt")
.split("\n\n")
val jets = input.last()
val rocks = input.dropLast(1).map { it.convertToRock() }
val sol1 = dropBlocks(rocks, jets, dropLimit = 2022)
output("Rock Height 2022", sol1)
val sol2 = dropBlocks(rocks, jets, dropLimit = 1_000_000_000_000)
output("string 2", sol2)
}
private fun dropBlocks(rocks: List<List<Coord2d>>, jets: String, dropLimit: Long): Long {
val row = List(size = 7) { '.' }
val gridSize = 7
val grid = Grid(MutableList(size = gridSize) { row.toMutableList() })
var rocksDropped = 0
var rockHeight = 0
var curRock: List<Coord2d>? = null
var rockIndex = 0
var jetIndex = 0
val heightChangeMap = mutableListOf<Int>()
// pair = rocksDropped, currentHeight
val stateMap = mutableMapOf<String, Pair<Int, Int>>()
while (rocksDropped < dropLimit) {
// add grid rows if necessary
if ((grid.g.size - rockHeight) < (gridSize + 1))
grid.g.addAll(MutableList(size = gridSize) { row.toMutableList() })
// after last rock was dropped...
if (curRock == null) {
// store new start state
val key = "$jetIndex:$rockIndex"
if (stateMap.containsKey(key).not())
stateMap[key] = Pair(rocksDropped, rockHeight)
else { // found repeat, get cycle
val origKey = stateMap[key]!!
val cycle = (rocksDropped - origKey.first).toLong()
// only calculate total and return if match is actually a cycle
if ((rocksDropped % cycle) == (dropLimit % cycle)) {
val cycleHeight = rockHeight - origKey.second
val remainingRocks = dropLimit - rocksDropped
val cyclesRemaining = remainingRocks / cycle
return rockHeight + (cycleHeight * cyclesRemaining)
}
}
// position new rock
curRock = rocks[rockIndex].map {
it + Coord2d(rockHeight + 3, 2)
}
}
// push by jet
jets[jetIndex].push(curRock, grid, gridSize)
jetIndex = (jetIndex + 1) % jets.length
// try fall, update info if rock couldn't fall
if (curRock.tryFall(grid).not()) {
rocksDropped++
rockIndex = (rockIndex + 1) % rocks.size
val droppedHeight = curRock.maxOf { it.x + 1 }
heightChangeMap.add(droppedHeight - rockHeight)
rockHeight = max(rockHeight, droppedHeight)
curRock.forEach { grid[it] = '#' }
curRock = null
}
/* curRock?.forEach { grid[it] = '@' }
grid.printFlippedOnX()
grid.g.forEachIndexed { i, r ->
r.forEachIndexed { k, c -> if (c == '@') grid.g[i][k] = '.' }
}*/
}
// fallback if no pattern in simulation
return rockHeight.toLong()
}
private fun String.convertToRock(): List<Coord2d> {
val lines = split("\n")
return lines.mapIndexed { x, line ->
line.mapIndexedNotNull { y, char ->
if (char == '#') Coord2d(lines.size - 1 - x, y)
else null
}
}.flatten()
}
private fun Char.push(rock: List<Coord2d>, grid: Grid<Char>, gWidth: Int) {
val direction = when (this) {
'<' -> -1
else -> 1
}
val tempR = rock.map { it.copy(y = it.y + direction) }
if (tempR.any { it.y < 0 || it.y == gWidth || grid[it] == '#' })
return
else {
rock.forEachIndexed { i, r ->
r.y = tempR[i].y
}
}
}
private fun List<Coord2d>.tryFall(grid: Grid<Char>): Boolean {
return if (any { it.x - 1 < 0 || grid.g[it.x - 1][it.y] == '#' })
false
else {
forEach { c ->
c.x -= 1
}
true
}
}
}
| 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 4,647 | advent-of-code-2022 | MIT License |
src/main/kotlin/treesandgraphs/EvaluateDivision.kt | e-freiman | 471,473,372 | false | {"Kotlin": 78010} | package treesandgraphs
private data class Vertex(val name: String, val edges: MutableList<Pair<Vertex, Double>>) {
var visited = false
}
class EvaluateDivision {
private val vertexes = mutableMapOf<String, Vertex>()
private fun dfs(v: Vertex, target: Vertex, value: Double): Pair<Boolean, Double> {
v.visited = true
if (v === target) {
return true to value
}
for (e in v.edges) {
if (!e.first.visited) {
val r = dfs(e.first, target, value * e.second)
if (r.first) {
return r
}
}
}
return false to -1.0
}
fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray {
for (i in equations.indices) {
val v1 = vertexes[equations[i][0]] ?: Vertex(equations[i][0], mutableListOf())
val v2 = vertexes[equations[i][1]] ?: Vertex(equations[i][1], mutableListOf())
v1.edges.add(v2 to values[i])
v2.edges.add(v1 to 1.0 / values[i])
vertexes[v1.name] = v1
vertexes[v2.name] = v2
}
val ret = DoubleArray(queries.size) { -1.0 }
for ((i, q) in queries.withIndex()) {
var v1 = vertexes[q[0]]
var v2 = vertexes[q[1]]
if (v1 != null && v2 != null) {
for (entry in vertexes.entries) {
entry.value.visited = false
}
ret[i] = dfs(v1, v2, 1.0).second
}
}
return ret
}
}
| 0 | Kotlin | 0 | 0 | fab7f275fbbafeeb79c520622995216f6c7d8642 | 1,618 | LeetcodeGoogleInterview | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/FindTheWinnerOfTheCircularGame.kt | faniabdullah | 382,893,751 | false | null | //There are n friends that are playing a game. The friends are sitting in a
//circle and are numbered from 1 to n in clockwise order. More formally, moving
//clockwise from the iᵗʰ friend brings you to the (i+1)ᵗʰ friend for 1 <= i < n, and
//moving clockwise from the nᵗʰ friend brings you to the 1ˢᵗ friend.
//
// The rules of the game are as follows:
//
//
// Start at the 1ˢᵗ friend.
// Count the next k friends in the clockwise direction including the friend you
//started at. The counting wraps around the circle and may count some friends
//more than once.
// The last friend you counted leaves the circle and loses the game.
// If there is still more than one friend in the circle, go back to step 2
//starting from the friend immediately clockwise of the friend who just lost and
//repeat.
// Else, the last friend in the circle wins the game.
//
//
// Given the number of friends, n, and an integer k, return the winner of the
//game.
//
//
// Example 1:
//
//
//Input: n = 5, k = 2
//Output: 3
//Explanation: Here are the steps of the game:
//1) Start at friend 1.
//2) Count 2 friends clockwise, which are friends 1 and 2.
//3) Friend 2 leaves the circle. Next start is friend 3.
//4) Count 2 friends clockwise, which are friends 3 and 4.
//5) Friend 4 leaves the circle. Next start is friend 5.
//6) Count 2 friends clockwise, which are friends 5 and 1.
//7) Friend 1 leaves the circle. Next start is friend 3.
//8) Count 2 friends clockwise, which are friends 3 and 5.
//9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
//
//
// Example 2:
//
//
//Input: n = 6, k = 5
//Output: 1
//Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is
//friend 1.
//
//
//
// Constraints:
//
//
// 1 <= k <= n <= 500
// Related Topics Array Math Recursion Queue Simulation 👍 535 👎 16
package leetcodeProblem.leetcode.editor.en
class FindTheWinnerOfTheCircularGame {
fun solution() {
// array solution , O(n*k) , O(n)
fun findTheWinner(n: Int, k: Int): Int {
if (n == 1) return n
val listMaintain = mutableListOf<Int>()
for (j in 0 until n) {
listMaintain.add(j + 1)
}
var lastIndex = 0
while (true) {
for (i in 1 until k + 1) {
if (lastIndex > listMaintain.size - 1) {
lastIndex = 0
}
if (i == k) {
listMaintain.removeAt(lastIndex)
} else {
lastIndex++
}
}
if (listMaintain.size == 1) break
}
return listMaintain[0]
}
}
//below code will be used for submission to leetcode (using plugin of course)
// math solution
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun findTheWinner(n: Int, k: Int): Int {
var answer = 0
for (i in 1..n)
answer = (answer + k) % i
return answer + 1
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {
println(FindTheWinnerOfTheCircularGame.Solution().findTheWinner(6, 4))
}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 3,339 | dsa-kotlin | MIT License |
src/Day07.kt | vitind | 578,020,578 | false | {"Kotlin": 60987} |
fun main() {
class Directory(directoryName: String, parentDirectory: Directory?) {
private val directoryName: String = directoryName
private val parentDirectory: Directory? = parentDirectory
private val innerDirectories = arrayListOf<Directory>()
private val files = arrayListOf<Pair<String,Int>>()
fun addDirectory(innerDirectoryName: String) {
innerDirectories.add(Directory(innerDirectoryName, this))
}
fun addFile(fileName: String, fileSize: Int) {
files.add(Pair(fileName, fileSize))
}
fun getDirectoryName() : String { return directoryName }
fun getParentDirectory() : Directory? { return parentDirectory }
fun getDirectory(directoryName: String): Directory? {
return innerDirectories.find { dir ->
dir.directoryName.equals(directoryName)
}
}
fun getAllDirectories(): ArrayList<Directory> { return innerDirectories }
fun getAllFiles(): ArrayList<Pair<String, Int>> { return files }
}
var rootDirectory: Directory = Directory("/", null)
var currDirectory: Directory? = null
fun changeDirectory(directoryName: String) {
// Special case when "cd .."
if (directoryName.equals("..")) {
currDirectory = currDirectory?.getParentDirectory()
return
}
val directory = currDirectory?.getDirectory(directoryName)
directory?.let {
currDirectory = directory
} ?: run {
// println("ERROR: Directory '${directoryName}' not found in '${currDirectory?.getDirectoryName()}', ignoring changing directory")
}
}
fun addInnerDirectory(currDirectory: Directory?, innerDirectoryName: String) {
currDirectory?.addDirectory(innerDirectoryName)
}
fun addFileToDirectory(currDirectory: Directory?, fileName: String, fileSize: Int) {
currDirectory?.addFile(fileName, fileSize)
}
fun processCommands(input: List<String>) {
input.forEach { command ->
val arguments = command.split(" ")
when (arguments[0]) {
"$" -> {
when (arguments[1]) {
"cd" -> {
changeDirectory(arguments[2]) //NOTE: $ cd directoryName
}
"ls" -> {
// List command -> Any "dir" or fileSize as arguments[0] should be added to the current directory
}
}
}
"dir" -> {
currDirectory?.addDirectory(arguments[1])
}
else -> {
arguments[0].toIntOrNull()?.let { fileSize ->
currDirectory?.addFile(arguments[1], fileSize) // arguments[1] contains the fileName
} ?: run {
println("ERROR: ${arguments[0]} could not be converted to Int! | command = ${command}")
}
}
}
}
}
var totalSizeOfSelectedDirectories = 0
fun getDirectorySizePart1(directory: Directory?): Int {
directory?.let {
val totalFileSize = directory.getAllFiles().sumOf { file -> file.second }
val totalDirectoriesSize = directory.getAllDirectories().sumOf { innerDirectory -> getDirectorySizePart1(innerDirectory) }
val totalSize = totalFileSize + totalDirectoriesSize
if (totalSize <= 100000) {
totalSizeOfSelectedDirectories += totalSize
}
return totalSize
}
return 0
}
val directorySizes = arrayListOf<Pair<String,Int>>()
fun getDirectorySizePart2(directory: Directory?): Int {
directory?.let {
val totalFileSize = directory.getAllFiles().sumOf { file -> file.second }
val totalDirectoriesSize = directory.getAllDirectories().sumOf { innerDirectory -> getDirectorySizePart2(innerDirectory) }
val totalSize = totalFileSize + totalDirectoriesSize
directorySizes.add(Pair(directory.getDirectoryName(), totalSize))
return totalSize
}
return 0
}
fun part1(input: List<String>): Int {
rootDirectory = Directory("/", null)
currDirectory = rootDirectory
processCommands(input)
getDirectorySizePart1(rootDirectory)
return totalSizeOfSelectedDirectories
}
val TOTAL_FILESYSTEM_SPACE = 70000000
val REQUIRED_UNUSED_SPACE = 30000000
fun part2(input: List<String>): Int {
rootDirectory = Directory("/", null)
currDirectory = rootDirectory
processCommands(input)
var directorySizeToBeRemoved = 0
val currentFreeSpace = TOTAL_FILESYSTEM_SPACE - getDirectorySizePart2(rootDirectory)
val sortedDirectorySizes = directorySizes.sortedWith(compareBy { it.second })
for (directorySize in sortedDirectorySizes) {
var unusedSpaceAcquired = directorySize.second + currentFreeSpace
if (unusedSpaceAcquired > REQUIRED_UNUSED_SPACE) {
// println("DirectoryName = ${directorySize.first} | Size Removed = ${directorySize.second} | Unused Space Acquired = ${unusedSpaceAcquired}")
directorySizeToBeRemoved = directorySize.second
break
}
}
return directorySizeToBeRemoved
}
val input = readInput("Day07")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | 2698c65af0acd1fce51525737ab50f225d6502d1 | 5,604 | aoc2022 | Apache License 2.0 |
src/commonMain/kotlin/avl/AvlUtils.kt | EdwarDDay | 174,175,328 | false | null | /*
* Copyright 2019 <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 de.edwardday.sortedlist.avl
import de.edwardday.sortedlist.Tree
import de.edwardday.sortedlist.comparePartitioned
import de.edwardday.sortedlist.compareTo
import de.edwardday.sortedlist.size
internal val Tree<*, Int>?.height: Int get() = this?.data ?: 0
private fun <T> constructTree(value: T, left: Tree<T, Int>?, right: Tree<T, Int>?): Tree<T, Int> =
Tree(value, left, right, calculateHeight(left, right))
internal fun calculateHeight(left: Tree<*, Int>?, right: Tree<*, Int>?) =
maxOf(left.height, right.height) + 1
private fun <T> Tree<T, Int>.copyUpdated(
value: T = this.value,
left: Tree<T, Int>? = this.left,
right: Tree<T, Int>? = this.right
): Tree<T, Int> {
return if (left === this.left && right === this.right && value == this.value) this
else copy(value = value, left = left, right = right, data = calculateHeight(left, right))
}
internal fun <T> Tree<T, Int>?.plus(element: T, comparator: Comparator<T>): Tree<T, Int> {
return when {
this == null -> constructTree(element, null, null)
element.compareTo(this, comparator) < 0 -> balanceHeavyLeft(left = left.plus(element, comparator))
else -> balanceHeavyRight(right = right.plus(element, comparator))
}
}
internal fun <T> Tree<T, Int>?.plus(elements: Collection<T>, comparator: Comparator<T>): Tree<T, Int>? {
return when {
// isEmpty
elements.isEmpty() -> this
this == null -> elements.first().let { value ->
constructTree(value, null, null).plus(elements.drop(1), comparator)
}
else -> {
val (lefts, rights) = elements.partition { it.compareTo(this, comparator) < 0 }
val newLeft = left.plus(lefts, comparator)
val newRight = right.plus(rights, comparator)
return join(newLeft, value, newRight)
}
}
}
internal fun <T> Tree<T, Int>.minus(element: T, comparator: Comparator<T>): Tree<T, Int>? {
val removeResult = minusInternal(element, comparator)
return if (removeResult == null) this else removeResult.newChild
}
private fun <T> Tree<T, Int>.minusInternal(element: T, comparator: Comparator<T>): RemoveResult<T, Int>? {
if (value == element) {
return when {
left == null -> RemoveResult(right)
right == null -> RemoveResult(left)
left.height >= right.height -> left.pollMax().run {
RemoveResult(copyUpdated(value = polled, left = newChild))
}
else -> right.pollMin().run {
RemoveResult(copyUpdated(value = polled, right = newChild))
}
}
} else {
val compared = element.compareTo(this, comparator)
val leftRemoveResult = left?.takeIf { compared <= 0 }?.minusInternal(element, comparator)
return when (leftRemoveResult) {
null -> right?.takeIf { compared >= 0 }?.minusInternal(element, comparator)?.run {
RemoveResult(balanceHeavyLeft(right = newChild))
}
else -> RemoveResult(balanceHeavyRight(left = leftRemoveResult.newChild))
}
}
}
internal fun <T> Tree<T, Int>.minus(elements: Collection<T>, comparator: Comparator<T>): Tree<T, Int>? {
val removeResult = minusInternal(elements, comparator)
return removeResult.newChild
}
private fun <T> Tree<T, Int>?.minusInternal(
elements: Collection<T>,
comparator: Comparator<T>
): RemoveManyResult<T, Int> {
return when {
this == null || elements.isEmpty() -> RemoveManyResult(this, elements)
else -> {
val elementsWithoutThis = elements.minus(value)
val removeThis = elementsWithoutThis.size != elements.size
val (smaller, equal, greater) = elementsWithoutThis.comparePartitioned(value, comparator)
val (newLeft, leftToRemove) = left.minusInternal(smaller + equal, comparator)
val (newRight, rightToRemove) = right.minusInternal(leftToRemove - smaller + greater, comparator)
val toRemove = leftToRemove - equal + rightToRemove
if (removeThis) {
when {
newLeft == null -> RemoveManyResult(newRight, toRemove)
newRight == null -> RemoveManyResult(newLeft, toRemove)
newLeft.height > newRight.height -> newLeft.pollMax().let { (leftPolled, newValue) ->
RemoveManyResult(join(leftPolled, newValue, newRight), toRemove)
}
else -> newRight.pollMin().let { (rightPolled, newValue) ->
RemoveManyResult(join(newLeft, newValue, rightPolled), toRemove)
}
}
} else {
RemoveManyResult(join(newLeft, value, newRight), toRemove)
}
}
}
}
internal fun <T> Tree<T, Int>.balanceHeavyLeft(
left: Tree<T, Int>? = this.left,
right: Tree<T, Int>? = this.right
): Tree<T, Int> {
return if (left != null && left.height - right.height > 1) {
if (left.right != null && left.right.height > left.left.height) {
// double rotate
left.right.copyUpdated(
left = left.copyUpdated(right = left.right.left),
right = this.copyUpdated(left = left.right.right, right = right)
)
} else {
// rotate
left.copyUpdated(right = this.copyUpdated(left = left.right, right = right))
}
} else {
this.copyUpdated(left = left, right = right)
}
}
internal fun <T> Tree<T, Int>.balanceHeavyRight(
left: Tree<T, Int>? = this.left,
right: Tree<T, Int>? = this.right
): Tree<T, Int> {
return if (right != null && right.height - left.height > 1) {
if (right.left != null && right.left.height > right.right.height) {
// double rotate
right.left.copyUpdated(
left = this.copyUpdated(left = left, right = right.left.left),
right = right.copyUpdated(left = right.left.right)
)
} else {
// rotate
right.copyUpdated(left = this.copyUpdated(left = left, right = right.left))
}
} else {
this.copyUpdated(left = left, right = right)
}
}
internal fun <T> Tree<T, Int>.pollMin(): PollResult<T, Int> {
return when (left) {
null -> PollResult(right, value)
else -> {
left.pollMin().let {
it.copy(newChild = balanceHeavyRight(left = it.newChild))
}
}
}
}
internal fun <T> Tree<T, Int>.pollMax(): PollResult<T, Int> {
return when (right) {
null -> PollResult(left, value)
else -> {
right.pollMax().let {
it.copy(newChild = balanceHeavyLeft(right = it.newChild))
}
}
}
}
internal data class PollResult<T, D>(val newChild: Tree<T, D>?, val polled: T)
private data class RemoveResult<T, D>(val newChild: Tree<T, D>?)
private data class RemoveManyResult<T, D>(val newChild: Tree<T, D>?, val toRemove: Collection<T>)
internal fun <T> Tree<T, Int>.subTree(fromIndex: Int, toIndex: Int): Tree<T, Int>? {
val leftSize = left.size
return when {
fromIndex >= toIndex -> null
toIndex <= leftSize -> left?.subTree(fromIndex, toIndex)
fromIndex > leftSize -> right?.subTree(fromIndex - leftSize - 1, toIndex - leftSize - 1)
else -> join(left?.subTreeFrom(fromIndex), value, right?.subTreeTo(toIndex - leftSize - 1))
}
}
internal fun <T> Tree<T, Int>.subTree(from: T, to: T, comparator: Comparator<T>): Tree<T, Int>? {
return when {
comparator.compare(from, to) >= 0 -> null
to.compareTo(this, comparator) <= 0 -> left?.subTree(from, to, comparator)
from.compareTo(this, comparator) > 0 -> right?.subTree(from, to, comparator)
else -> join(left?.subTreeFrom(from, comparator), value, right?.subTreeTo(to, comparator))
}
}
internal fun <T> Tree<T, Int>.subTreeFrom(fromIndex: Int): Tree<T, Int>? {
val leftSize = left.size
return when {
fromIndex > leftSize -> right?.subTreeFrom(fromIndex - leftSize - 1)
fromIndex <= 0 -> this
else -> join(left?.subTreeFrom(fromIndex), value, right)
}
}
internal fun <T> Tree<T, Int>.subTreeFrom(from: T, comparator: Comparator<T>): Tree<T, Int>? {
return if (from.compareTo(this, comparator) > 0) {
right?.subTreeFrom(from, comparator)
} else {
join(left?.subTreeFrom(from, comparator), value, right)
}
}
internal fun <T> Tree<T, Int>.subTreeTo(toIndex: Int): Tree<T, Int>? {
val leftSize = left.size
return when {
toIndex <= leftSize -> left?.subTreeTo(toIndex)
toIndex >= size -> this
else -> join(left, value, right?.subTreeTo(toIndex - leftSize - 1))
}
}
internal fun <T> Tree<T, Int>.subTreeTo(to: T, comparator: Comparator<T>): Tree<T, Int>? {
return if (to.compareTo(this, comparator) <= 0) {
left?.subTreeTo(to, comparator)
} else {
join(left, value, right?.subTreeTo(to, comparator))
}
}
private fun <T> join(left: Tree<T, Int>?, value: T, right: Tree<T, Int>?): Tree<T, Int> {
return when {
left == null -> right.insertMin(value)
right == null -> left.insertMax(value)
left.height - right.height >= 2 -> left.balanceHeavyRight(right = join(left.right, value, right))
right.height - left.height >= 2 -> right.balanceHeavyLeft(left = join(left, value, right.left))
else -> constructTree(value, left, right)
}
}
private fun <T> Tree<T, Int>?.insertMin(value: T): Tree<T, Int> {
return when {
this == null -> constructTree(value, null, null)
else -> balanceHeavyLeft(left = left.insertMin(value))
}
}
private fun <T> Tree<T, Int>?.insertMax(value: T): Tree<T, Int> {
return when {
this == null -> constructTree(value, null, null)
else -> balanceHeavyRight(right = right.insertMax(value))
}
}
| 0 | Kotlin | 0 | 0 | 219a58640619c74f60c02742baaeb9346524215b | 10,604 | SortedList | Apache License 2.0 |
src/year2022/day20/Day20.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day20
import check
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day20_test")
check(part1(testInput), 3)
check(part2(testInput), 1623178306)
val input = readInput("2022", "Day20")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = decrypt(input)
private fun part2(input: List<String>) = decrypt(
input = input,
decryptionKey = 811589153,
mixingIterations = 10,
)
private fun decrypt(input: List<String>, decryptionKey: Long = 1, mixingIterations: Int = 1): Long {
val originalList = input.mapIndexed { i, n -> Pair(n.toLong() * decryptionKey, i) }
val mixedList = originalList.toMutableList()
repeat(mixingIterations) {
originalList.forEach {
mixNumber(mixedList, it)
}
}
val mixedListNumbers = mixedList.map { it.first }
val indexOfZero = mixedListNumbers.indexOf(0)
val posX = mixedListNumbers[(indexOfZero + 1000) % mixedList.size]
val posY = mixedListNumbers[(indexOfZero + 2000) % mixedList.size]
val posZ = mixedListNumbers[(indexOfZero + 3000) % mixedList.size]
return posX + posY + posZ
}
private fun mixNumber(list: MutableList<Pair<Long, Int>>, numWithIndex: Pair<Long, Int>) {
val index = list.indexOf(numWithIndex)
val num = list[index].first
val sizeWithoutNum = list.size - 1
val moves = num % sizeWithoutNum
val newIndex = (index + moves + sizeWithoutNum) % sizeWithoutNum
list.remove(numWithIndex)
list.add(newIndex.toInt(), numWithIndex)
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,645 | AdventOfCode | Apache License 2.0 |
src/test/kotlin/Day11Test.kt | FredrikFolkesson | 320,692,155 | false | null | import Day11Test.Direction.*
import Day11Test.SeatStatus.*
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class Day11Test {
enum class SeatStatus {
Empty, Taken, Floor, Outside
}
enum class Direction {
UpLeft, Up, UpRight,
Left, Right,
DownLeft, Down, DownRight
}
private fun getOccupiedSeatsWhenStabe(input: String): Int {
val seenMatrices = mutableSetOf<List<List<SeatStatus>>>()
var matrix = getMatrix(input)
while (matrix !in seenMatrices) {
seenMatrices.add(matrix)
matrix = matrix.mapIndexed { y, it ->
it.mapIndexed { x, currentStatus ->
getNewSeatStatus2(currentStatus, getSeenSeats(matrix, x, y))
}
}
}
matrix.map { println(it) }
return matrix.flatten().count { it == Taken }
}
private fun getNewSeatStatus2(currentSeatStatus: SeatStatus, firstSeenSeats: List<SeatStatus>): SeatStatus {
return if (currentSeatStatus == Floor) Floor
else if (currentSeatStatus == Empty && !firstSeenSeats.any { it == Taken }) Taken
else if (currentSeatStatus == Taken && firstSeenSeats.count { it == Taken } >= 5) Empty
else currentSeatStatus
}
private fun getNewSeatStatus(currentSeatStatus: SeatStatus, neighbours: List<SeatStatus>): SeatStatus {
return if (currentSeatStatus == Floor) Floor
else if (currentSeatStatus == Empty && !neighbours.any { it == Taken }) Taken
else if (currentSeatStatus == Taken && neighbours.count { it == Taken } >= 4) Empty
else currentSeatStatus
}
private fun getSeenSeats(matrix: List<List<SeatStatus>>, x: Int, y: Int): List<SeatStatus> {
return listOf(
getSeatInDirection(UpLeft, x, y, matrix),
getSeatInDirection(Up, x, y, matrix),
getSeatInDirection(UpRight, x, y, matrix),
getSeatInDirection(Left, x, y, matrix),
getSeatInDirection(Right, x, y, matrix),
getSeatInDirection(DownLeft, x, y, matrix),
getSeatInDirection(Down, x, y, matrix),
getSeatInDirection(DownRight, x, y, matrix)
)
}
private fun getNeighbours(matrix: List<List<SeatStatus>>, x: Int, y: Int): List<SeatStatus> {
return listOf(
matrix.getOrNull(y - 1)?.getOrNull(x - 1) ?: Outside,
matrix.getOrNull(y - 1)?.getOrNull(x) ?: Outside,
matrix.getOrNull(y - 1)?.getOrNull(x + 1) ?: Outside,
matrix.getOrNull(y)?.getOrNull(x - 1) ?: Outside,
matrix.getOrNull(y)?.getOrNull(x + 1) ?: Outside,
matrix.getOrNull(y + 1)?.getOrNull(x - 1) ?: Outside,
matrix.getOrNull(y + 1)?.getOrNull(x) ?: Outside,
matrix.getOrNull(y + 1)?.getOrNull(x + 1) ?: Outside
)
}
private fun getMatrix(input: String): List<List<SeatStatus>> {
return input
.lines()
.map {
it.map { c ->
when (c) {
'L' -> Empty
'.' -> Floor
'#' -> Taken
else -> throw IllegalArgumentException("Unknown instruction: $it")
}
}
}
}
@Test
fun `test getNeighbours`() {
val input =
"L.LL.LL.LL\n" +
"LLLLLLL.LL\n" +
"L.L.L..L..\n" +
"LLLL.LL.LL\n" +
"L.LL.LL.LL\n" +
"L.LLLLL.LL\n" +
"..L.L.....\n" +
"LLLLLLLLLL\n" +
"L.LLLLLL.L\n" +
"L.LLLLL.LL"
val matrix = getMatrix(input)
assertEquals(listOf(Empty, Empty, Empty, Floor, Floor, Empty, Empty, Empty), getNeighbours(matrix, 2, 2))
assertEquals(
listOf(Outside, Outside, Outside, Outside, Floor, Outside, Empty, Empty),
getNeighbours(matrix, 0, 0)
)
}
@Test
fun listEqualsTest() {
assertEquals(listOf(Empty, Floor, Outside), listOf(Empty, Floor, Outside))
assertTrue(setOf((listOf(Empty, Floor, Outside))).contains(listOf(Empty, Floor, Outside)))
}
@Test
fun `test demo input`() {
val input =
"L.LL.LL.LL\n" +
"LLLLLLL.LL\n" +
"L.L.L..L..\n" +
"LLLL.LL.LL\n" +
"L.LL.LL.LL\n" +
"L.LLLLL.LL\n" +
"..L.L.....\n" +
"LLLLLLLLLL\n" +
"L.LLLLLL.L\n" +
"L.LLLLL.LL\n"
assertEquals(26, getOccupiedSeatsWhenStabe(input))
}
@Test
fun `test real input`() {
val input = readFileAsString("/Users/fredrikfolkesson/git/advent-of-code/src/test/kotlin/input-day11.txt")
println(getOccupiedSeatsWhenStabe(input))
}
@Test
fun `test getSeatInDirection`() {
val input =
".......#.\n" +
"...#.....\n" +
".#.......\n" +
".........\n" +
"..#L....#\n" +
"....#....\n" +
".........\n" +
"#........\n" +
"...#....."
val input2 =
".............\n" +
".L.L.#.#.#.#.\n" +
"............."
val input3 =
".##.##.\n" +
"#.#.#.#\n" +
"##...##\n" +
"...L...\n" +
"##...##\n" +
"#.#.#.#\n" +
".##.##."
val matrix = getMatrix(input3)
assertEquals(Outside, getSeatInDirection(UpLeft, 3, 3, matrix))
assertEquals(Outside, getSeatInDirection(Up, 3, 3, matrix))
assertEquals(Outside, getSeatInDirection(UpRight, 3, 3, matrix))
assertEquals(Outside, getSeatInDirection(Left, 3, 3, matrix))
assertEquals(Outside, getSeatInDirection(Right, 3, 3, matrix))
assertEquals(Outside, getSeatInDirection(DownLeft, 3, 3, matrix))
assertEquals(Outside, getSeatInDirection(Down, 3, 3, matrix))
assertEquals(Outside, getSeatInDirection(DownRight, 3, 3, matrix))
}
private fun getSeatInDirection(direction: Direction, x: Int, y: Int, matrix: List<List<SeatStatus>>): SeatStatus {
val (newX, newY) = when (direction) {
UpLeft -> Pair(x - 1, y - 1)
Up -> Pair(x, y - 1)
UpRight -> Pair(x + 1, y - 1)
Left -> Pair(x - 1, y)
Right -> Pair(x + 1, y)
DownLeft -> Pair(x - 1, y + 1)
Down -> Pair(x, y + 1)
DownRight -> Pair(x + 1, y + 1)
}
val nextSeat = matrix.getOrNull(newY)?.getOrNull(newX) ?: Outside
return if (nextSeat == Outside || nextSeat == Taken || nextSeat == Empty) nextSeat else getSeatInDirection(
direction,
newX,
newY,
matrix
)
}
@Test
fun `test getNewSeatStatus`() {
assertEquals(Floor, getNewSeatStatus(Floor, listOf(Empty, Empty, Empty, Floor, Floor, Empty, Empty, Empty)))
assertEquals(
Taken,
getNewSeatStatus(Empty, listOf(Outside, Outside, Outside, Outside, Floor, Outside, Empty, Empty))
)
}
} | 0 | Kotlin | 0 | 0 | 79a67f88e1fcf950e77459a4f3343353cfc1d48a | 7,513 | advent-of-code | MIT License |
solutions/aockt/y2021/Y2021D08.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import aockt.y2021.Y2021D08.Segment.*
import aockt.y2021.Y2021D08.SevenSegmentDigit.*
import io.github.jadarma.aockt.core.Solution
object Y2021D08 : Solution {
/** The individual segment indicators of a seven segment display. */
private enum class Segment { A, B, C, D, E, F, G }
/** The ten digits as represented on a seven segment display. */
private enum class SevenSegmentDigit(val digit: Int, val segments: Set<Segment>) {
Zero(0, setOf(A, B, C, E, F, G)),
One(1, setOf(C, F)),
Two(2, setOf(A, C, D, E, G)),
Three(3, setOf(A, C, D, F, G)),
Four(4, setOf(B, C, D, F)),
Five(5, setOf(A, B, D, F, G)),
Six(6, setOf(A, B, D, E, F, G)),
Seven(7, setOf(A, C, F)),
Eight(8, setOf(A, B, C, D, E, F, G)),
Nine(9, setOf(A, B, C, D, F, G));
companion object {
fun fromSegmentsOrNull(segments: Set<Segment>) = values().firstOrNull { it.segments == segments }
}
}
/** A set of segments that represent a [SevenSegmentDigit], but that have been swapped in an unknown fashion. */
private data class ScrambledDigit(private val segments: Set<Segment>) : Set<Segment> by segments {
/**
* Given a scrambled digit and the correct mapping [code] between segments, returns the actual encoded
* [SevenSegmentDigit], or throws if either the mapping is invalid, or the input does not represent a digit.
*/
fun unscramble(code: Map<Segment, Segment>): SevenSegmentDigit {
require(code.keys.size == 7) { "Incomplete code, not all segments are mapped." }
require(code.values.toSet().size == 7) { "Invalid code, some segments map to the same segment." }
return SevenSegmentDigit
.fromSegmentsOrNull(segments.map { code.getValue(it) }.toSet())
?: throw IllegalArgumentException("Invalid code, output is not a valid digit.")
}
}
/** Reverse engineer the segment scrambling of a seven segment display given the 10 unique digit patterns. */
private fun Set<ScrambledDigit>.reverseEngineerSevenSegmentDisplay(): Map<Segment, Segment> {
require(size == 10) { "Cannot reverse engineer scrambling because some digits are missing." }
val digits: Map<SevenSegmentDigit, ScrambledDigit> = buildMap {
val unsolved = this@reverseEngineerSevenSegmentDisplay.toMutableList()
fun <T> MutableList<T>.removeFirstWhere(predicate: (T) -> Boolean): T = first(predicate).also(::remove)
this[One] = unsolved.removeFirstWhere { it.size == 2 }
this[Four] = unsolved.removeFirstWhere { it.size == 4 }
this[Seven] = unsolved.removeFirstWhere { it.size == 3 }
this[Eight] = unsolved.removeFirstWhere { it.size == 7 }
this[Three] = unsolved.removeFirstWhere { it.size == 5 && it.containsAll(getValue(One)) }
this[Nine] = unsolved.removeFirstWhere { it.toSet() == getValue(Three) + getValue(Four) }
this[Six] = unsolved.removeFirstWhere { it.size == 6 && !it.containsAll(getValue(One)) }
this[Five] = unsolved.removeFirstWhere { it.size == 5 && (getValue(Six) - it).size == 1 }
this[Two] = unsolved.removeFirstWhere { it.size == 5 }
this[Zero] = unsolved.removeFirstWhere { it.size == 6 }
require(unsolved.isEmpty())
}
return buildMap {
put((digits.getValue(Seven) - digits.getValue(One)).first(), A)
put((digits.getValue(Eight) - digits.getValue(Seven) - digits.getValue(Two)).first(), B)
put((digits.getValue(Eight) - digits.getValue(Six)).first(), C)
put((digits.getValue(Eight) - digits.getValue(Zero)).first(), D)
put((digits.getValue(Eight) - digits.getValue(Nine)).first(), E)
put((digits.getValue(One) intersect digits.getValue(Six)).first(), F)
put((digits.getValue(Eight) - keys).first(), G)
}
}
/** Converts a list of segmented digits to an integer. Might overflow. Throws if list is empty. */
private fun List<SevenSegmentDigit>.toInt(): Int = joinToString(separator = "") { it.digit.toString() }.toInt()
/** Parse the [input] and return the sequence of unique scrambled signals and the four output scrambled digits. */
private fun parseInput(input: String): Sequence<Pair<Set<ScrambledDigit>, List<ScrambledDigit>>> {
fun String.parseScrambledDigitList(): Sequence<ScrambledDigit> =
trim()
.splitToSequence(' ')
.map { digit -> ScrambledDigit(digit.map { Segment.valueOf(it.uppercase()) }.toSet()) }
return input
.lineSequence()
.map { line ->
val (digitsRaw, outputRaw) = line.split('|')
val digits = digitsRaw.parseScrambledDigitList().toSet()
val output = outputRaw.parseScrambledDigitList().toList()
require(digits.size == 10 && output.size == 4) { "Invalid input." }
digits to output
}
}
override fun partOne(input: String) =
input
.lineSequence()
.map { it.substringAfter('|').trim() }
.flatMap { digits -> digits.split(' ').filter { it.length in setOf(2, 3, 4, 7) } }
.count()
override fun partTwo(input: String) =
parseInput(input)
.map { (scrambled, output) -> scrambled.reverseEngineerSevenSegmentDisplay() to output }
.map { (code, output) -> output.map { it.unscramble(code) } }
.fold(0) { acc, digits -> acc + digits.toInt() }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 5,689 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/day04/Day04.kt | Malo-T | 575,370,082 | false | null | package day04
private typealias Assignments = Pair<IntRange, IntRange>
private fun String.toIntRange(): IntRange = split("-").map { it.toInt() }.let { it[0]..it[1] }
// anonymous function
private val hasCompleteOverlap = fun(assignments: Assignments): Boolean {
with(assignments) {
return first.subtract(second).isEmpty() || second.subtract(first).isEmpty()
}
}
// lambda
private val hasOverlap = { assignments: Assignments ->
assignments.first.intersect(assignments.second).isNotEmpty()
}
class Day04 {
fun parse(input: String): List<Assignments> =
input
.lines()
.map { line -> line.split(",") }
.map { (first, second) ->
Assignments(
first = first.toIntRange(),
second = second.toIntRange()
)
}
fun part1(parsed: List<Assignments>): Int = parsed.count(hasCompleteOverlap)
fun part2(parsed: List<Assignments>): Int = parsed.count(hasOverlap)
}
| 0 | Kotlin | 0 | 0 | f4edefa30c568716e71a5379d0a02b0275199963 | 1,016 | AoC-2022 | Apache License 2.0 |
src/test/kotlin/ch/ranil/aoc/aoc2023/Day18.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2023
import ch.ranil.aoc.AbstractDay
import ch.ranil.aoc.aoc2023.Direction.*
import org.junit.jupiter.api.Test
import kotlin.math.abs
import kotlin.test.assertEquals
class Day18 : AbstractDay() {
@Test
fun part1Test() {
assertEquals(62, compute1(testInput))
}
@Test
fun part1Puzzle() {
assertEquals(36679, compute1(puzzleInput))
}
@Test
fun part2Test() {
assertEquals(952408144115, compute2(testInput))
}
@Test
fun part2Puzzle() {
assertEquals(88007104020978, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
// shoelace methode
var s1 = 0
var s2 = 0
var edgeLength = 0
val points = mutableListOf(Point(0, 0))
input
.map { it.parse1() }
.forEach { (direction, length) ->
val lastPoint = points.last()
val nextPoint = lastPoint.move(length, direction)
s1 += (lastPoint.x * nextPoint.y)
s2 += (lastPoint.y * nextPoint.x)
edgeLength += length
points.add(nextPoint)
}
val shoelaceArea = abs(s1 - s2) / 2
return shoelaceArea + (edgeLength / 2) + 1
}
private fun String.parse1(): DigInstruction {
val (d, l, _) = this.split(" ")
return DigInstruction(
direction = d.toDirection(),
length = l.toInt(),
)
}
private fun compute2(input: List<String>): Long {
// shoelace methode
var s = 0L
val points = mutableListOf(Point(0, 0))
input
.map { it.parse2() }
.forEach { (direction, length) ->
val lastPoint = points.last()
val nextPoint = lastPoint.move(length, direction)
// simplified "shoelace" compared to part1
s += (lastPoint.y.toLong() + nextPoint.y.toLong()) * (lastPoint.x.toLong() - nextPoint.x.toLong())
s += length
points.add(nextPoint)
}
return abs(s) / 2L + 1L
}
private fun String.parse2(): DigInstruction {
val (_, lengthHex, dirStr) = Regex(".*\\(#(\\w{5})(\\w)\\)").find(this)?.groupValues.orEmpty()
val length = lengthHex.toInt(16)
val direction = when (dirStr) {
"0" -> E
"1" -> S
"2" -> W
"3" -> N
else -> throw IllegalArgumentException(dirStr)
}
return DigInstruction(direction, length)
}
private data class DigInstruction(
val direction: Direction,
val length: Int,
)
private fun String.toDirection(): Direction {
return when (this) {
"R" -> E
"L" -> W
"U" -> N
"D" -> S
else -> throw IllegalArgumentException("Unknown direction: $this")
}
}
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 2,957 | aoc | Apache License 2.0 |
src/d07/Main.kt | cweckerl | 572,838,803 | false | {"Kotlin": 12921} | package d07
import java.io.File
fun main() {
data class Trie(
val dir: String,
val children: MutableMap<String, Trie> = mutableMapOf(),
val parent: Trie? = null,
var dirSize: Long = 0L
)
// combining parts for this day
val input = File("src/d07/input").readLines()
val root = Trie("/")
var curr = root
input.drop(1).forEach {
if (it.startsWith("$ cd")) {
val dir = it.split(' ')[2]
curr = if (dir == "..") curr.parent!! else curr.children[dir]!!
} else if (it.startsWith("dir")) {
val dir = it.split(' ')[1]
curr.children[dir] = Trie(dir = "${curr.dir}/$dir", parent = curr)
} else if (!it.startsWith("$ ls")) {
curr.dirSize += it.split(' ')[0].toLong()
}
}
val sizes = mutableMapOf<String, Long>()
fun traverse(root: Trie): Long {
val tmp = root.dirSize + root.children.values.sumOf { traverse(it) }
sizes[root.dir] = tmp
return tmp
}
traverse(root)
println(sizes.values.sumOf { if (it <= 100000) it else 0 }) // part 1
val total = sizes["/"]!!
println(sizes.values.filter { 70000000 - total + it >= 30000000 }.min()) // part 2
}
| 0 | Kotlin | 0 | 0 | 612badffbc42c3b4524f5d539c5cbbfe5abc15d3 | 1,248 | aoc | Apache License 2.0 |
app/src/main/java/com/exponential_groth/calculator/result/Util.kt | exponentialGroth | 680,748,973 | false | {"Kotlin": 144165, "CSS": 140} | package com.exponential_groth.calculator.result
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
import kotlin.math.sqrt
private val Double.mantissa get() = toBits() and 0x000fffffffffffffL/* or 0x0010000000000000L*/
private val Double.exponent get() = (toBits() and 0x7ff0000000000000 ushr 52) - 1023
fun reduceFraction(numerator: Long, denominator: Long): Pair<Long, Long> {
val sign = if ((numerator > 0) xor (denominator > 0)) -1 else 1
val gcd = gcd(abs(numerator), abs(denominator))
return Pair(
sign * abs(numerator) / gcd,
abs(denominator) / gcd
)
}
private fun gcd(a: Long, b: Long): Long { // binary gcd algorithm is faster than the euclidean one
require(a > 0 && b > 0)
if (a == 0L) return b
if (b == 0L) return a
val shift = (a or b).countTrailingZeroBits()
var u = a
var v = b
u = u shr u.countTrailingZeroBits()
do {
v = v shr v.countTrailingZeroBits()
v -= u
val m = v shr 63
u += v and m
v = (v + m) xor m
} while (v != 0L)
return u shl shift
}
fun fractionToDecimal(numerator: Long, denominator: Long): String {
val nume = abs(numerator)
val deno = abs(denominator)
val sign = if ((numerator < 0) xor (denominator < 0)) "-" else ""
if (deno == 0L) {
return ""
} else if (nume == 0L) {
return "0"
} else if (nume % deno == 0L) {
return "$sign${nume / deno}"
}
val map = HashMap<Long, Int>()
val rst = StringBuffer("$sign${nume/deno}.")
var end = nume % deno * 10
var i = 0
while (end != 0L) {
if (map.containsKey(end)) {
rst.insert(rst.indexOf(".") + map[end]!! + 1, "\\overline{")
rst.append("}")
return rst.toString()
}
rst.append(end / deno)
map[end] = i++
end = end % deno * 10
}
return rst.toString()
}
fun Double.toFraction(): Pair<Long, Long>? {
val sign = this.sign.toInt()
val exponent = this.exponent
var mantissa = this.mantissa shl 12
/* val maxExponent = 31 // it would work as long as exponent < 52 but that can take long
if (exponent > maxExponent && this <= Long.MAX_VALUE)
return toLong() to 1L
else if (exponent > maxExponent)
return null
else if (exponent == -1023L) // Subnormal numbers are not supported
return null*/
if (abs(exponent) >= 32)
return null
asRepeatingDecimalToFraction()?.let { return it }
if (mantissa.countTrailingZeroBits() < 12 + 5) return null // should have at least 5 zeros to make sure that it is not repeating with a bigger repeating length
var numerator = 1L
var denominator = 1L
var leadingZeros = mantissa.countLeadingZeroBits()
while (leadingZeros != 64) {
numerator = (numerator shl (leadingZeros+1)) + 1
denominator = denominator shl (leadingZeros+1)
mantissa = mantissa shl (leadingZeros + 1)
leadingZeros = mantissa.countLeadingZeroBits()
}
if (exponent >= 0)
numerator = numerator shl exponent.toInt()
else
denominator = denominator shl -exponent.toInt()
return reduceFraction(sign * numerator, denominator)
}
private fun Double.asRepeatingDecimalToFraction(): Pair<Long, Long>? {
val exp = exponent.toInt()
val numOfDigitsToCheck = 52 - max(exp, 0) - 2 // don't check last two digits and the ones that account for the integer part
val digitsToCheck = (mantissa and (0L.inv() shl 2)) shl (62 - numOfDigitsToCheck) // remove the bits mentioned above and trim start
if ((digitsToCheck ushr (64 - numOfDigitsToCheck)).countTrailingZeroBits() > numOfDigitsToCheck / 2) return null
var currentlyCheckedRepetendLength = numOfDigitsToCheck / 2
var minRepeatingPartLength = numOfDigitsToCheck
var smallestRepetendLength: Int? = null
val alreadyChecked = mutableListOf<Int>()
while (currentlyCheckedRepetendLength > 0) {
var isRecurringWithCurrentLength = true
for (i in (64 - numOfDigitsToCheck + currentlyCheckedRepetendLength) until (64 - (numOfDigitsToCheck - minRepeatingPartLength))) {
if ((digitsToCheck and (1L shl (i - currentlyCheckedRepetendLength)) == 0L) != (digitsToCheck and (1L shl i) == 0L)) {
isRecurringWithCurrentLength = false
break
}
}
if (!isRecurringWithCurrentLength && smallestRepetendLength != null) {
if (currentlyCheckedRepetendLength == 1) break
alreadyChecked.add(currentlyCheckedRepetendLength)
do {
currentlyCheckedRepetendLength = smallestRepetendLength / smallestDivisor(smallestRepetendLength, smallestRepetendLength / currentlyCheckedRepetendLength)
} while (currentlyCheckedRepetendLength > 1 && alreadyChecked.any { it % currentlyCheckedRepetendLength == 0 })
if (currentlyCheckedRepetendLength == 1) break
} else if (!isRecurringWithCurrentLength) {
currentlyCheckedRepetendLength--
if (currentlyCheckedRepetendLength != 0) minRepeatingPartLength--
} else {
smallestRepetendLength = currentlyCheckedRepetendLength
if (currentlyCheckedRepetendLength == 1) break
currentlyCheckedRepetendLength /= smallestPrimeFactor(currentlyCheckedRepetendLength)
alreadyChecked.clear()
}
}
if (smallestRepetendLength == null) return null
val repetend = ((((1L shl smallestRepetendLength) - 1) shl (minRepeatingPartLength - smallestRepetendLength)) and (digitsToCheck ushr (64-numOfDigitsToCheck))) ushr (minRepeatingPartLength - smallestRepetendLength)
var shiftRepetitionStart = 0
val allDigits = mantissa
for (i in (2 + minRepeatingPartLength) until (52 - max(exp, 0))) {
if ((allDigits and (1L shl (i - smallestRepetendLength)) == 0L) != (allDigits and (1L shl i) == 0L)) break
shiftRepetitionStart++
}
// I.APPP... = (IAP - IA) / ((2^n - 1) * 2^k) with n = repetendLength, k = digits between . and first P
val p = repetend.rotateRight(shiftRepetitionStart, smallestRepetendLength)
val ia = (mantissa or 0x0010000000000000L) ushr (2 + minRepeatingPartLength + shiftRepetitionStart)
val numerator = ((ia shl smallestRepetendLength) or p) - ia // Do I need to check for overflow here and the line below?
val denominator = ((1L shl smallestRepetendLength) - 1) shl (50 - minRepeatingPartLength - shiftRepetitionStart - exp)
return reduceFraction(sign.toInt() * numerator, denominator)
}
/**returns the smallest divisor of [n] that is bigger than [k]*/
private fun smallestDivisor(n: Int, k: Int): Int {
for (i in k+1 until n) {
if (n % i == 0) return i
}
return n
}
private fun smallestPrimeFactor(n: Int): Int { // fast enough, because n is never bigger than 50
if (n % 2 == 0) return 2
var i = 3
while (i <= sqrt(n.toDouble())) {
if (n % i == 0) return i
i += 2
}
return n
}
fun primeFactors(num: Long): Map<Long, Int> {
var n = num
val factors = mutableMapOf<Long, Int>()
var i = 2L
while (i * i <= n) {
while (n % i == 0L) {
val occurrences = factors[i]?:0
factors[i] = occurrences + 1
n /= i
}
i++
}
if (n > 1) {
val occurrences = factors[i]?:0
factors[n] = occurrences + 1
}
return factors.toMap()
}
private fun Long.rotateRight(n: Int, size: Int) = (((1L shl n) - 1) shl (size - n)) and
(this shl (size - n)) or
(this ushr n) | 0 | Kotlin | 0 | 0 | 49a34a8dd7ff50c670db0ffdf255df135bda332e | 7,637 | Calculator | Apache License 2.0 |
Problem Solving/Algorithms/Basic - Counting Valleys.kt | MechaArms | 525,331,223 | false | {"Kotlin": 30017} | /*
An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps, for every step it was noted if it was an uphill, U, or a downhill, D step. Hikes always start and end at sea level, and each step up or down represents a 1 unit change in altitude. We define the following terms:
A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.
Example
steps = 8 path = [DDUUUUDD]
The hiker first enters a valley 2 units deep. Then they climb out and up onto a mountain 2 units high. Finally, the hiker returns to sea level and ends the hike.
Function Description
Complete the countingValleys function in the editor below.
countingValleys has the following parameter(s):
int steps: the number of steps on the hike
string path: a string describing the path
Returns
int: the number of valleys traversed
Input Format
The first line contains an integer steps, the number of steps in the hike.
The second line contains a single string path, of steps characters that describe the path.
Sample Input
8
UDDDUDUU
Sample Output
1
Explanation
If we represent _ as sea level, a step up as /, and a step down as \, the hike can be drawn as:
_/\ _
\ /
\/\/
The hiker enters and leaves one valley.
*/
//My Solution
//===========
fun countingValleys(steps: Int, path: String): Int {
var valleys: Int = 0
var cur_level: Int = 0
for (steps in path){
if(steps == 'U'){
cur_level += 1
if(cur_level == 0){
valleys += 1
}
}else if (steps == 'D'){
cur_level -= 1
}else{
continue
}
}
return(valleys)
}
fun main(args: Array<String>) {
val steps = readLine()!!.trim().toInt()
val path = readLine()!!
val result = countingValleys(steps, path)
println(result)
}
//Best Solution
//=============
fun countingValleys(steps: Int, path: String): Int {
var valleys=0
var height=0
for (steps in path){
if(steps=='U') height++ else height--
if (height==0 && steps=='U') valleys++
}
return valleys
}
fun main(args: Array<String>) {
val steps = readLine()!!.trim().toInt()
val path = readLine()!!
val result = countingValleys(steps, path)
println(result)
}
| 0 | Kotlin | 0 | 1 | eda7f92fca21518f6ee57413138a0dadf023f596 | 2,629 | My-HackerRank-Solutions | MIT License |
src/main/kotlin/y2023/Day01.kt | jforatier | 432,712,749 | false | {"Kotlin": 44692} | package y2023
import common.Resources.splitOnEmpty
class Day01(private val data: List<String>) {
val VALID_DIGITS: Map<String, Int> = mapOf(
Pair("1", 1),
Pair("2", 2),
Pair("3", 3),
Pair("4", 4),
Pair("5", 5),
Pair("6", 6),
Pair("7", 7),
Pair("8", 8),
Pair("9", 9),
Pair("one", 1),
Pair("two", 2),
Pair("three", 3),
Pair("four", 4),
Pair("five", 5),
Pair("six", 6),
Pair("seven", 7),
Pair("eight", 8),
Pair("nine", 9)
)
fun part1(): Int {
return data
.splitOnEmpty()
.map { grouped ->
grouped.map { line -> line.filter { char -> char.digitToIntOrNull() != null } }
}
// Lines of Int
.map {
it.map { intInLine ->
if (intInLine.length < 2) {
StringBuilder().append(intInLine[0]).append(intInLine[0]).toString()
} else if (intInLine.length > 2) {
StringBuilder().append(intInLine[0]).append(intInLine[intInLine.length - 1]).toString()
} else {
intInLine
}
}
}
.map { it.map { line -> line.toIntOrNull() } }
.reduce { acc, ints -> acc + ints }
.sumOf { it ?: 0 }
}
fun part2(): Int {
return data
.splitOnEmpty()
.map { line ->
line.map { word ->
val first = VALID_DIGITS.get(word.findAnyOf(VALID_DIGITS.keys)?.second)
val second = VALID_DIGITS.get(word.findLastAnyOf(VALID_DIGITS.keys)?.second)
"$first$second".toInt()
}
}
.reduce { acc, ints -> acc + ints }
.sumOf { it }
}
} | 0 | Kotlin | 0 | 0 | 2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae | 1,922 | advent-of-code-kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/WordAbbreviation.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 dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import kotlin.math.max
/**
* Word Abbreviation.
* @see <a href="https://leetcode.com/problems/word-abbreviation/">Source</a>
*/
fun interface WordAbbreviation {
operator fun invoke(dict: List<String>): List<String>
fun abbrev(word: String, i: Int): String {
val n = word.length
return if (n - i <= 3) word else word.substring(0, i + 1) + (n - i - 2) + word[n - 1]
}
}
/**
* Approach #1: Greedy.
*/
class WordAbbreviationGreedy : WordAbbreviation {
override operator fun invoke(dict: List<String>): List<String> {
val wordToAbbr: MutableMap<String?, String?> = HashMap()
val groups: MutableMap<Int, MutableList<String>> = HashMap()
// Try to group words by their length. Because no point to compare words with different length.
// Also, no point to look at words with length < 4.
for (word in dict) {
val len = word.length
if (len < 4) {
wordToAbbr[word] = word
} else {
val g = groups.getOrDefault(len, ArrayList())
g.add(word)
groups[len] = g
}
}
// For each group of words with same length, generate a result HashMap.
for (len in groups.keys) {
val res = getAbbr(groups.getOrDefault(len, emptyList()))
for (word in res.keys) {
wordToAbbr[word] = res[word]
}
}
// Generate the result list
val result: MutableList<String> = ArrayList()
for (word in dict) {
wordToAbbr[word]?.let { result.add(it) }
}
return result
}
private fun getAbbr(words: List<String>): Map<String?, String> {
val res: MutableMap<String?, String> = HashMap()
val len = words[0].length
// Try to abbreviate a word from index 1 to len - 2
for (i in 1 until len - 2) {
val abbrToWord: MutableMap<String, String> = HashMap()
for (s in words) {
if (res.containsKey(s)) continue
// Generate the current abbreviation
val abbr = s.substring(0, i) + (len - 1 - i) + s[len - 1]
// Tick: use reversed abbreviation to word map to check if there is any duplicated abbreviation
if (!abbrToWord.containsKey(abbr)) {
abbrToWord[abbr] = s
} else {
abbrToWord[abbr] = ""
}
}
// Add unique abbreviations find during this round to result HashMap
for (abbr in abbrToWord.keys) {
val s = abbrToWord[abbr]
// Not a unique abbreviation
if (s!!.isEmpty()) continue
res[s] = abbr
}
}
// Add all words that can't be shortened.
for (s in words) {
if (!res.containsKey(s)) {
res[s] = s
}
}
return res
}
}
class IndexedWord(var word: String, var index: Int)
class WordTrieNode {
var children: Array<WordTrieNode?> = arrayOfNulls(ALPHABET_LETTERS_COUNT)
var count: Int = 0
}
/**
* Approach #2: Group + Least Common Prefix.
*/
class WordAbbreviationLCP : WordAbbreviation {
override operator fun invoke(dict: List<String>): List<String> {
val groups: MutableMap<String, MutableList<IndexedWord>> = HashMap()
val ans = Array(dict.size) { "" }
for ((index, word) in dict.withIndex()) {
val ab = abbrev(word, 0)
if (!groups.containsKey(ab)) groups[ab] = ArrayList()
groups[ab]?.add(IndexedWord(word, index))
}
for (group in groups.values) {
group.sortWith { a: IndexedWord, b: IndexedWord ->
a.word.compareTo(b.word)
}
val lcp = IntArray(group.size)
for (i in 1 until group.size) {
val p = longestCommonPrefix(group[i - 1].word, group[i].word)
lcp[i] = p
lcp[i - 1] = max(lcp[i - 1], p)
}
for (i in group.indices) ans[group[i].index] = abbrev(group[i].word, lcp[i])
}
return ans.toList()
}
private fun longestCommonPrefix(word1: String, word2: String): Int {
var i = 0
while (i < word1.length && i < word2.length && word1[i] == word2[i]) i++
return i
}
}
/**
* Approach #3: Group + Trie.
*/
class WordAbbreviationTrie : WordAbbreviation {
override operator fun invoke(dict: List<String>): List<String> {
val groups: MutableMap<String, MutableList<IndexedWord?>> = HashMap()
val ans = Array(dict.size) { "" }
for ((index, word) in dict.withIndex()) {
val ab = abbrev(word, 0)
if (!groups.containsKey(ab)) groups[ab] = ArrayList()
groups[ab]?.add(IndexedWord(word, index))
}
for (group in groups.values) {
val trie = WordTrieNode()
for (iw in group) {
var cur = trie
if (iw!!.word.isNotBlank()) {
for (letter in iw.word.substring(1).toCharArray()) {
if (cur.children[letter - 'a'] == null) cur.children[letter - 'a'] = WordTrieNode()
cur.count++
cur = cur.children[letter - 'a']!!
}
}
}
for (iw in group) {
var cur = trie
var i = 1
if (iw!!.word.isNotBlank()) {
for (letter in iw.word.substring(1).toCharArray()) {
if (cur.count == 1) break
cur = cur.children[letter - 'a']!!
i++
}
}
ans[iw.index] = abbrev(iw.word, i - 1)
}
}
return ans.toList()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 6,631 | kotlab | Apache License 2.0 |
src/main/aoc2016/Day10.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2016
class Day10(input: List<String>) {
interface Instruction
private data class GetInstruction(val value: Int, val to: Int) : Instruction
private data class GiveInstruction(val who: Int,
val lowTo: Int, val lowIsBot: Boolean,
val highTo: Int, val highIsBot: Boolean) : Instruction
private data class Output(val name: Int, var holds: Int = 0)
private data class Bot(val name: Int, val holds: MutableList<Int> = mutableListOf()) {
fun popSmall(): Int {
val min = holds.minOrNull()!!
holds.removeIf { it == min }
return min
}
fun popLarge(): Int {
val max = holds.maxOrNull()!!
holds.removeIf { it == max }
return max
}
fun isReady() = holds.size == 2
}
private val instructions = parseInput(input)
private val bots = Array(210) { i -> Bot(i) }
private val outputs = Array(21) { i -> Output(i) }
private val botQueue = mutableListOf<Int>()
private fun parseInput(input: List<String>): List<Instruction> {
val ret = mutableListOf<Instruction>()
input.forEach {
val parts = it.split(" ")
when (parts[0]) {
"bot" -> {
ret.add(GiveInstruction(parts[1].toInt(),
parts[6].toInt(), parts[5] == "bot",
parts.last().toInt(), parts[parts.size - 2] == "bot"))
}
"value" -> {
ret.add(GetInstruction(parts[1].toInt(), parts.last().toInt()))
}
}
}
return ret
}
private fun initializeBots(): Array<Bot> {
instructions.filterIsInstance<GetInstruction>().forEach {
bots[it.to].holds.add(it.value)
if (bots[it.to].isReady()) {
botQueue.add(it.to)
}
}
return bots
}
private fun executeInstructions(wantedLow: Int, wantedHigh: Int): Int {
while (botQueue.size > 0) {
val botToProcess = botQueue.removeAt(0)
val low = bots[botToProcess].popSmall()
val high = bots[botToProcess].popLarge()
if (high == wantedHigh && low == wantedLow) {
// return when the bot to search for is found
return botToProcess
}
val inst = instructions.filterIsInstance<GiveInstruction>().find {
it.who == botToProcess
} as GiveInstruction
if (inst.highIsBot) {
bots[inst.highTo].holds.add(high)
if (bots[inst.highTo].isReady()) {
botQueue.add(inst.highTo)
}
} else {
outputs[inst.highTo].holds = high
}
if (inst.lowIsBot) {
bots[inst.lowTo].holds.add(low)
if (bots[inst.lowTo].isReady()) {
botQueue.add(inst.lowTo)
}
} else {
outputs[inst.lowTo].holds = low
}
}
return -1
}
fun solvePart1(wantedLow: Int, wantedHigh: Int): Int {
initializeBots()
return executeInstructions(wantedLow, wantedHigh)
}
fun solvePart2(): Int {
initializeBots()
executeInstructions(-1, -1) // Not interested in finding a certain bot
return outputs[0].holds * outputs[1].holds * outputs[2].holds
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,560 | aoc | MIT License |
kotlin/src/com/daily/algothrim/leetcode/CommonChars.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 查找常用字符(leetcode 1002)
*
* 给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
* 你可以按任意顺序返回答案。
*
* 示例 1:
*
* 输入:["bella","label","roller"]
* 输出:["e","l","l"]
* 示例 2:
*
* 输入:["cool","lock","cook"]
* 输出:["c","o"]
*
* 提示:
*
* 1 <= A.length <= 100
* 1 <= A[i].length <= 100
* A[i][j] 是小写字母
*/
class CommonChars {
companion object {
@JvmStatic
fun main(args: Array<String>) {
CommonChars().solution(arrayOf("bella", "label", "roller")).forEach {
println(it)
}
println()
CommonChars().solution(arrayOf("cool", "lock", "cook")).forEach {
println(it)
}
println()
CommonChars().solutionV2(arrayOf("bella", "label", "roller")).forEach {
println(it)
}
println()
CommonChars().solutionV2(arrayOf("cool", "lock", "cook")).forEach {
println(it)
}
println()
CommonChars().solutionV2(arrayOf("acabcddd", "bcbdbcbd", "baddbadb", "cbdddcac", "aacbcccd", "ccccddda", "cababaab", "addcaccd")).forEach {
println(it)
}
}
}
fun solution(A: Array<String>): List<String> {
var result = mutableListOf<String>()
var temp = mutableListOf<String>()
if (A.isEmpty()) return emptyList()
A[0].forEachIndexed { index, c ->
result.add(index, c.toString())
}
var i = 1
while (i < A.size) {
A[i].forEach {
if (result.contains(it.toString())) {
temp.add(it.toString())
result.remove(it.toString())
}
}
result = temp
temp = mutableListOf()
i++
}
return result
}
/**
* 计数
*/
fun solutionV2(A: Array<String>): List<String> {
val result = mutableListOf<String>()
val min = IntArray(26) {
Int.MAX_VALUE
}
A.forEach {
val cur = IntArray(26)
it.forEach { char ->
// 统计字符出现的次数
cur[char - 'a'] = cur[char - 'a'] + 1
}
cur.forEachIndexed { index, i ->
// 所以字符串中对应字符出现的最小次数
min[index] = min[index].coerceAtMost(i)
}
}
min.forEachIndexed { index, i ->
var j = 0
while (j++ < i) {
result.add(('a' + index).toString())
}
}
return result
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 3,022 | daily_algorithm | Apache License 2.0 |
src/main/kotlin/days/Day4.kt | wmichaelshirk | 315,495,224 | false | null | package days
typealias Passport = Map<String, String>
class Day4 : Day(4) {
private val fields = mapOf<String, (String) -> Boolean>(
"byr" to { p -> p.toIntOrNull() in 1920..2002 },
"iyr" to { p -> p.toIntOrNull() in 2010..2020 },
"eyr" to { p -> p.toIntOrNull() in 2020..2030 },
"hgt" to { p ->
val (height, unit) = Regex("^([0-9]+)([a-z]+)$")
.find(p)?.destructured?.toList() ?: listOf("", "")
when (unit) {
"cm" -> height.toIntOrNull() in 150..193
"in" -> height.toIntOrNull() in 59..76
else -> false
}
},
"hcl" to { p -> Regex("^#[0-9a-f]{6}$") matches p },
"ecl" to { p -> listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth").contains(p) },
"pid" to { p -> Regex("^[0-9]{9}$") matches p },
"cid" to { _ -> true }
)
private fun strToPassport(string: String): Passport {
return string.split(Regex("\\s"))
.map {
val (k, v) = it.split(":")
k to v
}.toMap()
}
private fun validate(pass: Passport): Boolean {
return pass.keys.containsAll(fields.keys.minus("cid")) and pass.all {
fields[it.key]?.let { it1 -> it1(it.value) } ?: false
}
}
override fun partOne(): Int {
return inputString.split("\n\n")
.filter {
val document = strToPassport(it)
document.keys.containsAll(fields.keys)
}.count()
}
override fun partTwo(): Int {
return inputString.split("\n\n")
.filter {
val document = strToPassport(it)
validate(document)
}.count()
}
}
| 0 | Kotlin | 0 | 0 | b36e5236f81e5368f9f6dbed09a9e4a8d3da8e30 | 1,776 | 2020-Advent-of-Code | Creative Commons Zero v1.0 Universal |
day04/part2.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Part Two ---
// Just as you're about to report your findings to the Elf, one of you realizes
// that the rules have actually been printed on the back of every card this
// whole time.
//
// There's no such thing as "points". Instead, scratchcards only cause you to
// win more scratchcards equal to the number of winning numbers you have.
//
// Specifically, you win copies of the scratchcards below the winning card
// equal to the number of matches. So, if card 10 were to have 5 matching
// numbers, you would win one copy each of cards 11, 12, 13, 14, and 15.
//
// Copies of scratchcards are scored like normal scratchcards and have the same
// card number as the card they copied. So, if you win a copy of card 10 and it
// has 5 matching numbers, it would then win a copy of the same cards that the
// original card 10 won: cards 11, 12, 13, 14, and 15. This process repeats
// until none of the copies cause you to win any more cards. (Cards will never
// make you copy a card past the end of the table.)
//
// This time, the above example goes differently:
//
// Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
// Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
// Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
// Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
// Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
// Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
//
// - Card 1 has four matching numbers, so you win one copy each of the next
// four cards: cards 2, 3, 4, and 5.
// - Your original card 2 has two matching numbers, so you win one copy each of
// cards 3 and 4.
// - Your copy of card 2 also wins one copy each of cards 3 and 4.
// - Your four instances of card 3 (one original and three copies) have two
// matching numbers, so you win four copies each of cards 4 and 5.
// - Your eight instances of card 4 (one original and seven copies) have one
// matching number, so you win eight copies of card 5.
// - Your fourteen instances of card 5 (one original and thirteen copies) have
// no matching numbers and win no more cards.
// - Your one instance of card 6 (one original) has no matching numbers and
// wins no more cards.
//
// Once all of the originals and copies have been processed, you end up with 1
// instance of card 1, 2 instances of card 2, 4 instances of card 3, 8
// instances of card 4, 14 instances of card 5, and 1 instance of card 6. In
// total, this example pile of scratchcards causes you to ultimately have 30
// scratchcards!
//
// Process all of the original and copied scratchcards until no more
// scratchcards are won. Including the original set of scratchcards, how many
// total scratchcards do you end up with?
import java.io.*
import kotlin.io.*
val numWinners = File("input.txt").readLines().map {
val (winningNumbers, ourNumbers) = it.drop(10).split(" | ").map { it.trimStart().split(Regex("\\s+")).map(String::toInt) }
winningNumbers.intersect(ourNumbers).size
}
val numCards = MutableList(numWinners.size) { 1 }
for ((idx, winners) in numWinners.withIndex()) {
for (j in (idx+1)..(idx+winners)) {
numCards[j] += numCards[idx]
}
}
val result = numCards.sum()
println(result)
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 3,178 | adventofcode2023 | MIT License |
src/Day01/Day01.kt | Trisiss | 573,815,785 | false | {"Kotlin": 16486} | fun main() {
fun initListCalories(input: List<String>): List<Int> {
val listCalories = mutableListOf<Int>()
var sum = 0
input.forEachIndexed { index, element ->
element.toIntOrNull()?.let { num ->
sum += num
if (index == input.lastIndex) listCalories.add(sum)
} ?: listCalories.add(sum).also { sum = 0 }
}
return listCalories
}
fun part1(input: List<String>): Int = initListCalories(input).max()
fun part2(input: List<String>): Int {
val listCalories = initListCalories(input)
return listCalories.sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01/Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01/Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cb81a0b8d3aa81a3f47b62962812f25ba34b57db | 955 | AOC-2022 | Apache License 2.0 |
2022/src/main/kotlin/Day14.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import kotlin.math.sign
object Day14 {
fun part1(input: String): Int {
val grid = parseInput(input)
var count = 0
while (true) {
val settledSand = dropSand(grid)
if (settledSand.y > grid.maxY) {
break
}
grid.putSand(settledSand.x, settledSand.y)
count++
}
return count
}
fun part2(input: String): Int {
val grid = parseInput(input)
var count = 0
while (!grid.get(500, 0)) {
val settledSand = dropSand(grid)
grid.putSand(settledSand.x, settledSand.y)
count++
}
return count
}
private fun dropSand(grid: Grid): Point {
var sandX = 500
var sandY = 0
while (true) {
val sandXDiff = listOf(0, -1, 1).firstOrNull { !grid.get(sandX + it, sandY + 1) }
if (sandXDiff == null) {
return Point(sandX, sandY)
} else {
sandY++
sandX += sandXDiff
}
}
}
private fun parseInput(input: String): Grid {
val grid = Grid()
input
.splitNewlines()
.map(::parseLine)
.forEach { line ->
line.windowed(2).forEach { (start, end) ->
var x = start.x
var y = start.y
grid.putWall(x, y)
while (x != end.x || y != end.y) {
x += (end.x - x).sign
y += (end.y - y).sign
grid.putWall(x, y)
}
}
}
return grid
}
private fun parseLine(line: String): List<Point> {
return line
.split(" -> ")
.map(String::splitCommas)
.map { (x, y) -> Point(x.toInt(), y.toInt()) }
}
private data class Point(val x: Int, val y: Int)
private class Grid {
private val data = mutableSetOf<Point>()
var maxY: Int = 0
private set
fun get(x: Int, y: Int) = (y == maxY + 2) || data.contains(Point(x, y))
fun putWall(x: Int, y: Int) {
data.add(Point(x, y))
maxY = maxOf(maxY, y)
}
fun putSand(x: Int, y: Int) {
data.add(Point(x, y))
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,988 | advent-of-code | MIT License |
src/Day05.kt | vivekpanchal | 572,801,707 | false | {"Kotlin": 11850} | import java.util.Stack
fun main() {
val input = readInput("Day05")
val emptyLine = input.indexOfFirst { it.isEmpty() }
data class CrateMove(val items: Int, val from: Int, val to: Int)
val regex = Regex("\\d+")
fun parseCrateMove(command: String): CrateMove {
val (num, from, to) = regex.findAll(command).map { it.value.toInt() }.toList()
return CrateMove(num, from - 1, to - 1)
}
val moves: List<CrateMove> = input.drop(emptyLine + 1).map(::parseCrateMove)
// Define the stacks
val stack= mutableListOf<Stack<Char>>()
// Define the data
val data = listOf(
listOf('W', 'B', 'D', 'N', 'C', 'F', 'J'),
listOf('P', 'Z', 'V', 'Q', 'L', 'S', 'T'),
listOf('P', 'Z', 'B', 'G', 'J', 'T'),
listOf('D', 'T', 'L', 'J', 'Z', 'B', 'H', 'C'),
listOf('G', 'V', 'B', 'J', 'S'),
listOf('P', 'S', 'Q'),
listOf('B', 'V', 'D', 'F', 'L', 'M', 'P', 'N'),
listOf('P', 'S', 'M', 'F', 'B', 'D', 'L', 'R'),
listOf('V', 'D', 'T', 'R')
)
for (i in data.indices) {
val st=Stack<Char>()
st.addAll(data[i])
println("stack -> $st")
stack.add(i,st)
}
fun CrateMove.moveAtOnce() = Stack<Char>().apply {
repeat(items) {
push(stack[from].pop())
}
repeat(items) {
stack[to].push(pop())
}
}
fun CrateMove.moveOneByOne() = repeat(items) {
stack[to].push(stack[from].pop())
}
fun moveAll(mover: (move: CrateMove) -> Unit): String {
moves.forEach(mover)
return String(stack.map { it.pop() }.toCharArray())
}
fun part1(input: List<String>): String {
return moveAll { move -> move.moveOneByOne() }
}
fun part2(input: List<String>): String {
return moveAll { move -> move.moveAtOnce() }
}
// println("result part 1 == ${part1(input)}")
println("result part 2 == ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | f21a2dd08be66520e9c9de14611e50c14ea017f0 | 1,980 | Aoc-kotlin | Apache License 2.0 |
aoc-2015/src/main/kotlin/aoc/AocDay15.kt | triathematician | 576,590,518 | false | {"Kotlin": 615974} | package aoc
import aoc.util.chunk
import aoc.util.chunkint
class AocDay15: AocDay(15) {
companion object { @JvmStatic fun main(args: Array<String>) { AocDay15().run() } }
override val testinput = """
Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3
""".trimIndent().lines()
class Ingr(val name: String, val c: Int, val d: Int, val f: Int, val t: Int, val cal: Int)
class Cookie(val ingr: Map<Ingr, Int>) {
val c = ingr.map { it.key.c * it.value }.sum().coerceAtLeast(0)
val d = ingr.map { it.key.d * it.value }.sum().coerceAtLeast(0)
val f = ingr.map { it.key.f * it.value }.sum().coerceAtLeast(0)
val t = ingr.map { it.key.t * it.value }.sum().coerceAtLeast(0)
val cal = ingr.map { it.key.cal * it.value }.sum()
fun score() = c*d*f*t
}
fun String.chunkints(n: Int) = chunk(n).substringBefore(",").toInt()
fun String.parse() = Ingr(chunk(0).dropLast(1), chunkints(2), chunkints(4), chunkints(6), chunkints(8), chunkints(10))
fun bestScore(ingrs: List<Ingr>, tsp: Int, c: Cookie, cals: Int?): Int {
if (ingrs.size == 1) {
val c2 = Cookie(c.ingr + (ingrs[0] to tsp))
return if (cals != null && c2.cal != cals) 0 else c2.score()
}
return (0..tsp).maxOf {
bestScore(ingrs.drop(1), tsp - it, Cookie(c.ingr + (ingrs[0] to it)), cals)
}
}
override fun calc1(input: List<String>): Int {
val ingrs = input.map { it.parse() }
return bestScore(ingrs, 100, Cookie(mapOf()), null)
}
override fun calc2(input: List<String>): Int {
val ingrs = input.map { it.parse() }
return bestScore(ingrs, 100, Cookie(mapOf()), 500)
}
} | 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 1,830 | advent-of-code | Apache License 2.0 |
Algorithms/src/main/kotlin/AllWaysToMakeChange.kt | ILIYANGERMANOV | 557,496,216 | false | {"Kotlin": 74485} | fun numberOfWaysToMakeChange(n: Int, denoms: List<Int>): Int {
// Write your code here.
println("----------- CASE: n = $n, denoms = $denoms ----------------")
val allWays = ways(
n = n,
ds = denoms,
)
println("All ways: $allWays")
val uniqueWays = allWays.map { it.sorted() }.toSet()
println("Unique ways: $uniqueWays")
println("------------- END CASE ---------------")
return uniqueWays.size
}
/*
n = 3, denoms = [1,2]
ways(3) = ways(1) + ways(2)
*/
fun ways(
n: Int,
ds: List<Int>,
ways: List<Int> = emptyList()
): List<List<Int>> {
if (n < 0) return emptyList()
if (n == 0) return listOf(ways)
val validDs = ds.filter { it <= n }
return validDs.foldRight(initial = emptyList()) { d, allWays ->
ways(n = n - d, ways = ways + d, ds = validDs) + allWays
}
}
| 0 | Kotlin | 0 | 1 | 4abe4b50b61c9d5fed252c40d361238de74e6f48 | 862 | algorithms | MIT License |
src/main/kotlin/se/radicalcode/aoc/2.kt | gwendo | 162,547,004 | false | null | package se.radicalcode.aoc
fun hasNumberOfUniqueLetter(word: String, count: Int): Boolean {
return word.asSequence().groupingBy { it }.eachCount().filter {it.value == count}.count() > 0
}
fun calculateChecksum(wordList: List<String>): Int {
var hasTwoLetters = wordList.filter{ hasNumberOfUniqueLetter(it, 2) }.count()
var hasThreeLetters = wordList.filter{ hasNumberOfUniqueLetter(it, 3) }.count()
return (hasThreeLetters * hasTwoLetters)
}
fun diffCount(word1: String, word2: String) : Int {
return word1.zip(word2).filter{ it.first != it.second }.count()
}
fun removeDifferentChar(word1: String, word2: String): String {
return word1.zip(word2).filter { it.first == it.second }.map { it.first }.joinToString(separator = "")
}
fun <T1, T2> Collection<T1>.combine(other: Iterable<T2>): List<Pair<T1, T2>> {
return combine(other) { thisItem: T1, otherItem: T2 -> Pair(thisItem, otherItem) }
}
fun <T1, T2, R> Collection<T1>.combine(other: Iterable<T2>, transformer: (thisItem: T1, otherItem:T2) -> R): List<R> {
return this.flatMap { thisItem -> other.map { otherItem -> transformer(thisItem, otherItem) }}
}
| 0 | Kotlin | 0 | 0 | 12d0c841c91695e215f06efaf62d06a5480ba7a2 | 1,148 | advent-of-code-2018 | MIT License |
src/main/kotlin/adventofcode/year2021/Day03BinaryDiagnostic.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2021
import adventofcode.Puzzle
import adventofcode.PuzzleInput
class Day03BinaryDiagnostic(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val numbers by lazy { input.lines() }
override fun partOne(): Int {
val gammaRate = numbers.first().indices.map { index -> mostCommonOrOne(numbers.countBy(index)) }.toInt(2)
val epsilonRate = numbers.first().indices.map { index -> leastCommonOrZero(numbers.countBy(index)) }.toInt(2)
return gammaRate * epsilonRate
}
override fun partTwo(): Int {
val oxygenGeneratorRating = findRating(::mostCommonOrOne)
val co2ScrubberRating = findRating(::leastCommonOrZero)
return oxygenGeneratorRating * co2ScrubberRating
}
private fun findRating(bitCriteria: (Map<Char, Int>) -> Int): Int {
val mutList = numbers.toMutableList()
var index = 0
while (mutList.size > 1) {
val common = bitCriteria(mutList.countBy(index))
mutList.removeAll { it[index].toString().toInt() != common }
index++
}
return mutList.first().toInt(2)
}
companion object {
private fun List<String>.countBy(index: Int) = groupingBy { it[index] }.eachCount()
private fun mostCommonOrOne(eachCount: Map<Char, Int>) = if ((eachCount['1'] ?: 0) >= (eachCount['0'] ?: 0)) 1 else 0
private fun leastCommonOrZero(eachCount: Map<Char, Int>) = if ((eachCount['0'] ?: 0) <= (eachCount['1'] ?: 0)) 0 else 1
private fun List<Int>.toInt(radix: Int) = joinToString("").toInt(radix)
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 1,618 | AdventOfCode | MIT License |
src/Day04.kt | meletios | 573,316,028 | false | {"Kotlin": 4032} | fun main() {
var leftA = 0
var leftB = 0
var rightA = 0
var rightB = 0
fun rearrangeParts(parts: List<String>) {
if (parts[0].toInt() <= parts[2].toInt()) {
leftA = parts[0].toInt()
leftB = parts[1].toInt()
rightA = parts[2].toInt()
rightB = parts[3].toInt()
} else {
leftA = parts[2].toInt()
leftB = parts[3].toInt()
rightA = parts[0].toInt()
rightB = parts[1].toInt()
}
}
fun getResults(input: List<String>, looseOverlapping: Boolean): Int {
var overlappingPairs = 0
var looseOverlappingPairs = 0
input.forEach { line ->
val parts = line.split(",", "-")
rearrangeParts(parts)
if ((leftA <= rightA || leftA <= rightB) && leftB >= rightB) {
overlappingPairs++
} else if (rightA <= leftA && rightB >= leftB) {
overlappingPairs++
} else if (leftB >= rightA || rightB <= leftA) {
looseOverlappingPairs++
}
}
return if (looseOverlapping) looseOverlappingPairs + overlappingPairs else overlappingPairs
}
val inputPart = readInput("Day04")
println("Part 1 Result - ${getResults(inputPart, false)}")
println("Part 2 Result - ${getResults(inputPart, true)}")
}
| 0 | Kotlin | 0 | 0 | 25549bde439b949f6dd091ccd69beb590d078787 | 1,383 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem63/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem63
/**
* LeetCode page: [63. Unique Paths II](https://leetcode.com/problems/unique-paths-ii/);
*/
class Solution {
/* Complexity:
* Time O(MN) and Space O(MN) where M and N are the number of rows and columns in obstacleGrid;
*/
fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int {
val numRows = obstacleGrid.size
val numColumns = obstacleGrid[0].size
if (isObstacle(0, 0, obstacleGrid)
|| isObstacle(numRows - 1, numColumns - 1, obstacleGrid)
) {
return 0
}
// dp[i][j] ::= unique paths if robot initially located at cell(i, j)
val dp = Array(numRows + 1) { IntArray(numColumns + 1) }
dp[numRows - 1][numColumns - 1] = 1
for (row in obstacleGrid.indices.reversed()) {
for (column in obstacleGrid[row].indices.reversed()) {
if (isObstacle(row, column, obstacleGrid)) {
continue
}
dp[row][column] += dp[row + 1][column] + dp[row][column + 1]
}
}
return dp[0][0]
}
private fun isObstacle(row: Int, column: Int, obstacleGrid: Array<IntArray>): Boolean {
return obstacleGrid[row][column] == 1
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,292 | hj-leetcode-kotlin | Apache License 2.0 |
kotlin/2018/src/main/kotlin/2018/Lib03.kt | nathanjent | 48,783,324 | false | {"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966} | package aoc.kt.y2018;
/**
* Day 3.
*/
data class Point(
val x: Int,
val y: Int)
/** Part 1 */
fun processClaims1(input: String): String {
val claimMap = getClaimMap(input)
val overlapCount = claimMap.filter { it.value.count() > 1 } .count()
return overlapCount.toString()
}
/** Part 2 */
fun processClaims2(input: String): String {
val claimMap = getClaimMap(input)
val claimsIntact = mutableMapOf<Int, Boolean>()
val id = claimMap
.map { Pair(it.key, it.value.toList()) }
.fold(claimsIntact, { acc, next ->
val idList = next.second
if (idList.count() > 1) {
idList.forEach { acc.put(it, false) }
} else {
val id = idList.first()
val intact = acc.getOrDefault(id, true)
if (intact) {
acc.put(id, true)
}
}
acc
})
.filter { it.value }
.map { it.key }
.first()
return id.toString()
}
fun getClaimMap(input: String): MutableMap<Point, MutableList<Int>> {
val claimMap = mutableMapOf<Point, MutableList<Int>>()
input.lines()
.filter { !it.isEmpty() }
.map { it.split(" @ ", ": ") }
.forEach {
val idStr = it.get(0)
val position = it.get(1).split(',')
val size = it.get(2).split('x')
val id = idStr.substring(1 until idStr.length).toInt()
val x = position.get(0).toInt()
val y = position.get(1).toInt()
val w = size.get(0).toInt()
val h = size.get(1).toInt()
for (x1 in x until x+w) {
for (y1 in y until y+h) {
val key = <KEY>)
val claimList = claimMap.getOrDefault(key, mutableListOf<Int>())
claimList.add(id)
claimMap.put(key, claimList)
}
}
}
return claimMap
}
| 0 | Rust | 0 | 0 | 7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf | 2,005 | adventofcode | MIT License |
src/main/kotlin/days/aoc2020/Day22.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2020
import days.Day
class Day22: Day(2020, 22) {
override fun partOne(): Any {
val players = parsePlayers(inputList)
while (players.none { it.hasLost() }) {
val drawn = players.mapIndexed { index, player ->
Pair(index,player.drawCard()!!)
}
players[drawn.maxByOrNull { it.second }?.first!!].acceptWonHand(drawn.sortedByDescending { it.second }.map { it.second })
}
return players.filterNot { it.hasLost() }.first().calculateWinningHand()
}
override fun partTwo(): Any {
val players = parsePlayers(inputList)
while (players.none { it.hasLost() }) {
playGame(players)
}
return players.filterNot { it.hasLost() }.first().calculateWinningHand()
}
// play a game, return the winner
private fun playGame(players: List<Player>): Player {
val previousDeckHashes = mutableSetOf<Int>()
while (players.none { it.hasLost() }) {
if (previousDeckHashes.contains(players.hashCode())) {
return players[0]
}
previousDeckHashes.add(players.hashCode())
val drawn = players.map { player ->
Pair(player.id, player.drawCard()!!)
}
if ((drawn[0].second > players[0].deckSize()) || (drawn[1].second > players[1].deckSize())) {
players.first { player -> player.id == (drawn.maxByOrNull { it.second }!!.first)}.acceptWonHand(drawn.sortedByDescending { it.second }.map { it.second })
} else {
val winner = playGame(listOf(
Player(players[0].id, mutableListOf<Int>().apply { addAll(players[0].deck.subList(0,drawn[0].second)) }),
Player(players[1].id, mutableListOf<Int>().apply { addAll(players[1].deck.subList(0,drawn[1].second)) })
))
players.first { it.id == winner.id }.acceptWonHand(listOf(
drawn.first { it.first == winner.id }.second,
drawn.first { it.first != winner.id }.second
))
}
}
return players.first { !it.hasLost() }
}
private fun parsePlayers(list: List<String>): List<Player> {
val players = mutableListOf<Player>()
val deck = mutableListOf<Int>()
var playerId = 0
list.forEach {
when {
it.isBlank() -> {
if (deck.isNotEmpty()) {
players.add(Player(playerId, deck))
}
deck.clear()
}
it.contains(":") -> {
Regex("Player (\\d):").matchEntire(it)?.destructured?.let { (id) -> playerId = id.toInt() }
}
else -> {
deck.add(it.toInt())
}
}
}
return players
}
}
class Player(val id: Int, initialDeck: List<Int>) {
val deck = ArrayDeque<Int>()
init {
deck.addAll(initialDeck)
}
fun deckSize(): Int {
return deck.size
}
fun hasLost(): Boolean {
return deck.isEmpty()
}
fun drawCard(): Int? {
return deck.removeFirst()
}
fun acceptWonHand(cards: List<Int>) {
deck.addAll(cards)
}
fun calculateWinningHand(): Int {
var index = 1
var result = 0
while (deck.isNotEmpty()) {
result += deck.removeLast() * index++
}
return result
}
override fun hashCode(): Int {
return deck.hashCode()
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,658 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/Day01.kt | f1qwase | 572,888,869 | false | {"Kotlin": 33268} | fun main() {
fun part1(input: List<String>): Int {
var currentCount = 0
var maxCount = 0
input.forEach {
if (it.isEmpty()) {
if (currentCount > maxCount) {
maxCount = currentCount
}
currentCount = 0
} else {
currentCount += it.toInt()
}
}
if (currentCount > maxCount) {
maxCount = currentCount
}
currentCount = 0
return maxCount
}
fun part2(input: List<String>): Int {
val elvesFood = mutableListOf(0)
var current = 0
input.forEach {
if (it.isEmpty()) {
elvesFood.add(current)
current = 0
} else {
current += it.toInt()
}
}
if (current != 0) {
elvesFood.add(current)
}
return elvesFood
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 9)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3fc7b74df8b6595d7cd48915c717905c4d124729 | 1,266 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2021/Day14.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2021
import com.nibado.projects.advent.*
object Day14 : Day {
private val values = resourceStrings(2021, 14).let { (template, rules) ->
template to
rules.split("\n").map { it.split(" -> ").let { (from, to) -> from to to } }.toMap()
}
private fun solve(iterations: Int): Long {
val current = values.first.windowed(2).groupBy { it }.map { (k, v) -> k to v.size.toLong() }.toMap().toMutableMap()
val elements = values.first.groupBy { it.toString() }.map { (k, v) -> k to v.size.toLong() }.toMap().toMutableMap()
repeat(iterations) {
val mods = mutableMapOf<String, Long>()
values.second.forEach { (key, replacement) ->
if ((current[key] ?: 0) > 0) {
val occurrences = current[key]!!
mods[key] = (mods[key] ?: 0) - occurrences
val (left, right) = (key[0] + replacement) to (replacement + key[1])
mods[left] = (mods[left] ?: 0) + occurrences
mods[right] = (mods[right] ?: 0) + occurrences
elements[replacement] = (elements[replacement] ?: 0) + occurrences
}
}
mods.forEach { (k, v) ->
current[k] = (current[k] ?: 0) + v
}
}
return elements.values.let { it.maxOrNull()!! - it.minOrNull()!! }
}
override fun part1(): Long = solve(10)
override fun part2(): Long = solve(40)
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,524 | adventofcode | MIT License |
src/main/kotlin/dev/siller/aoc2022/Day02.kt | chearius | 575,352,798 | false | {"Kotlin": 41999} | package dev.siller.aoc2022
private val example = """
A Y
B X
C Z
""".trimIndent()
private const val WIN = 6
private const val DRAW = 3
private const val LOSS = 0
private fun part1(input: List<String>): Int = input
.map {
val opponent = it[0] - 'A' + 1
val me = it[2] - 'X' + 1
me + when (me - opponent) {
1, -2 -> WIN
0 -> DRAW
-1, 2 -> LOSS
else -> 0
}
}
.sum()
private fun part2(input: List<String>): Int = input
.map {
val opponent = it[0] - 'A' + 1
val outcome = (it[2] - 'X') * 3
outcome + when (outcome) {
LOSS -> if (opponent > 1) opponent - 1 else 3
DRAW -> opponent
WIN -> if (opponent < 3) opponent + 1 else 1
else -> 0
}
}
.sum()
fun aocDay02() = aocTaskWithExample(
day = 2,
part1 = ::part1,
part2 = ::part2,
exampleInput = example,
expectedOutputPart1 = 15,
expectedOutputPart2 = 12
)
fun main() {
aocDay02()
}
| 0 | Kotlin | 0 | 0 | e070c0254a658e36566cc9389831b60d9e811cc5 | 1,058 | advent-of-code-2022 | MIT License |
src/Day14.kt | a-glapinski | 572,880,091 | false | {"Kotlin": 26602} | import Day14.move
import utils.Coordinate2D
import utils.readInputAsLines
fun main() {
val input = readInputAsLines("day14_input")
val caveMap = input.flatMap { path ->
path.splitToSequence(" -> ")
.map { Coordinate2D(x = it.substringBefore(',').toInt(), y = it.substringAfter(',').toInt()) }
.zipWithNext { left, right -> left lineTo right }
.flatten()
}.toSet()
val sandSource = Coordinate2D(500, 0)
fun part1(): Int {
val floorLevel = caveMap.maxOf(Coordinate2D::y)
val resting = mutableSetOf<Coordinate2D>()
var current = sandSource
while (current.y < floorLevel) {
current = current.move(caveMap, resting) ?: sandSource.also { resting.add(current) }
}
return resting.size
}
println(part1())
fun part2(): Int {
val floorLevel = caveMap.maxOf(Coordinate2D::y) + 2
val resting = mutableSetOf<Coordinate2D>()
var current = sandSource
while (sandSource !in resting) {
val next = current.move(caveMap, resting)
current = when {
next == null || next.y == floorLevel -> sandSource.also { resting.add(current) }
else -> next
}
}
return resting.size
}
println(part2())
}
private object Day14 {
private val directions = sequenceOf(Coordinate2D(0, 1), Coordinate2D(-1, 1), Coordinate2D(1, 1))
fun Coordinate2D.move(caveMap: Set<Coordinate2D>, resting: Set<Coordinate2D>) =
directions.map(::plus).firstOrNull { it !in caveMap && it !in resting }
} | 0 | Kotlin | 0 | 0 | c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8 | 1,622 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2021/day6/Lanternfish.kt | arnab | 75,525,311 | false | null | package aoc2021.day6
object Lanternfish {
data class Fish(val counter: Int = 8) {
fun nextDay(): List<Fish> {
return if (counter == 0) {
listOf(Fish(6), Fish())
} else {
listOf(Fish(counter - 1))
}
}
}
fun parse(data: String) = data.split(",").map { Fish(it.toInt()) }
fun calculateSchoolSize(initialPopulation: List<Fish>, days: Int): Int {
val schoolAtTheEnd: List<Fish> =
(1..days).fold(initialPopulation) { school, _ ->
school.map { fish -> listOf(fish.nextDay()) }.flatten().flatten()
}
return schoolAtTheEnd.size
}
fun calculateSchoolSizeRecursiveWithMemory(school: List<Fish>, days: Int): Long =
school.sumOf { fish -> spawnAndMemoize(fish, days) }
private val memory = HashMap<Pair<Fish, Int>, Long>()
private fun spawnAndMemoize(fish: Fish, days: Int): Long {
return when {
fish.counter == -1 -> spawnAndMemoize(Fish(6), days) + spawnAndMemoize(Fish(), days)
days == 0 -> 1L
else -> memory[Pair(fish, days)] ?: spawnAndMemoize(
Fish(fish.counter - 1), days - 1
).also {
memory[Pair(fish, days)] = it
}
}
}
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 1,318 | adventofcode | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions57.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
fun test57() {
val array = intArrayOf(1, 2, 4, 7, 11, 15)
print("和为15的两个数为:")
findNumbersWithSum(array, 15).forEach { print("$it ") }
println()
println()
val list1 = findContinuousSequence(15)
while (!list1.isEmpty) {
val value = list1.pop()
print("和为15的序列为:")
value.forEach { print("$it ") }
println()
}
println()
val list2 = findContinuousSequence(19)
while (!list2.isEmpty) {
val value = list2.pop()
print("和为19的序列为:")
value.forEach { print("$it ") }
println()
}
}
/**
* 题目一:在一个已排序的数组中输出任意一组和为s的两个数字。
*/
fun findNumbersWithSum(array: IntArray, s: Int): IntArray {
var start = 0
var end = array.size - 1
val result = IntArray(2)
while (start < end) {
if (array[start] + array[end] < s) {
start++
} else if (array[start] + array[end] > s) {
end--
} else {
result[0] = array[start]
result[1] = array[end]
break
}
}
return result
}
/**
* 题目二:输入一个数字s,求所有和为s的正整数序列。
*/
fun findContinuousSequence(s: Int): LinkedList<IntArray> {
var small = 1
var big = 2
val list = LinkedList<IntArray>()
val mid = (1 + s) / 2
while (small < mid) {
var sum = 0
for (i in small..big) {
sum += i
}
if (sum > s) {
small++
} else if (sum < s) {
big++
} else {
val array = IntArray(big - small + 1) { it + small }
list.push(array)
small++
}
}
return list
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,549 | Algorithm | Apache License 2.0 |
src/Day15.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | import kotlin.math.abs
class BeaconMap {
/**
* Value map is map of sensors and beacons.
*
* key stores coords of sensor, value is coord of beacon.
*/
private val map = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
private var minX = Int.MAX_VALUE
private var minY = Int.MAX_VALUE
private var maxX = Int.MIN_VALUE
private var maxY = Int.MIN_VALUE
// Problem is: bruteforcing all positions is *REALLY* slow für 4_000_000
// So we could create an array for the line, set what is covered, and then check.
// would probably also be slow
// or else we create an array of "covered ranges" per line
fun coveredRanges(y: Int): List<Pair<Int, Int>> {
val ranges = mutableListOf<Pair<Int, Int>>()
map.keys.forEach {
if (lineTouchedBy(it, y))
ranges.add(linecoverBy(it, y))
}
return ranges
}
fun linecoverBy(beacon: Pair<Int, Int>, y:Int): Pair<Int, Int> {
val range = rangeOf(beacon)
val min = beacon.first - range + abs(y - beacon.second)
val max = beacon.first + range - abs(y - beacon.second)
return Pair(min, max)
}
fun lineTouchedBy(beacon: Pair<Int, Int>, y: Int): Boolean {
val range = rangeOf(beacon)
return (abs(y - beacon.second) <= range)
}
/**
* Calculate range of certain beacon
*/
private fun rangeOf(beacon: Pair<Int, Int>): Int {
val sensor = map[beacon]!!
return (abs(beacon.first - sensor.first) + abs(beacon.second - sensor.second))
}
/**
* Set range of map coords
*/
private fun setMapRange() {
map.keys.forEach {
println("Beacon $it, sensor ${map[it]}, range ${rangeOf(it)}")
if (it.first - rangeOf(it) < minX) minX = it.first - rangeOf(it)
if (it.first + rangeOf(it) > maxX) maxX = it.first + rangeOf(it)
if (it.second - rangeOf(it) < minY) minY = it.second - rangeOf(it)
if (it.second + rangeOf(it) > maxY) maxY = it.second + rangeOf(it)
}
}
/**
* where to input the beacons info
*/
fun input(lines: List<String>) {
lines.forEach {
val pattern = "Sensor at x=(.+), y=(.+): closest beacon is at x=(.+), y=(.+)".toRegex()
val matches = pattern.findAll(it)
val match = matches.first()
map[Pair(match.groupValues[1].toInt(), match.groupValues[2].toInt())] =
Pair(match.groupValues[3].toInt(), match.groupValues[4].toInt())
}
setMapRange()
}
/* private fun isCovered(x: Int, y: Int): Boolean {
var covered = false
map.forEach { (sensor, beacon) ->
val range = abs(beacon.first - sensor.first) + abs(beacon.second - sensor.second)
val distance = abs(x - sensor.first) + abs(y - sensor.second)
covered = covered || (distance <= range)
}
return covered
} */
/*
private fun isCovered(x: Int, y: Int): Boolean {
var covered = false
var index = 0
val sensors = map.keys.sortedBy { it.first }
while (!covered && index < sensors.size) {
val sensor = sensors[index]
val beacon = map[sensor]!!
val range = abs(beacon.first - sensor.first) + abs(beacon.second - sensor.second)
val distance = abs(x - sensor.first) + abs(y - sensor.second)
covered = covered || (distance <= range)
index++
}
return covered
} */
fun isCovered(x: Int, y: Int): Boolean {
var covered = false
val coveredRanges = coveredRanges(y)
coveredRanges.forEach {
covered = covered || (x >= it.first && x <= it.second)
}
return covered
}
fun isBeacon(x: Int, y: Int): Boolean {
return map.values.contains(Pair(x, y))
}
fun isSensor(x: Int, y: Int): Boolean {
return map.keys.contains(Pair(x, y))
}
fun checkedPlacesInLine(y: Int): Int {
// we just bruteforce by now for me not being motivated to create an array and count later on
var checked = 0
for (x in minX..maxX) {
if (isCovered(x, y) && !isBeacon(x, y) && !isSensor(x, y)) {
checked++
}
}
return checked
}
fun tuningFrequency(max: Int): Long {
var freq = 0L
for (x in 0..max) {
for (y in 0..max) {
if (!isCovered(x, y))
freq = x * 4_000_000L + y
}
println("$x $freq")
}
return freq
}
fun isTotallyCovered(area: Pair<Pair<Int, Int>, Pair<Int, Int>>): Boolean {
var covered = false
map.keys.forEach {
val range = rangeOf(it)
val x1 = area.first.first
val x2 = area.second.first
val y1 = area.first.second
val y2 = area.second.second
// Well... (x1, y1) has to be covered by the same beacon as (x2, y2)
val distance1 = abs(x1 - it.first) + abs(y1 - it.second)
val distance2 = abs(x2 - it.first) + abs(y2 - it.second)
val distance3 = abs(x1 - it.first) + abs(y2 - it.second)
val distance4 = abs(x2 - it.first) + abs(y1 - it.second)
covered = covered || (distance1 <= range && distance2 <= range && distance3 <= range && distance4 <= range)
}
return covered
}
fun frequency(max: Int): Long {
// new approach:
// create a square, look, if totally covered.
// if not, divide into four quarters, repeat
var counter = 0
var x = Int.MIN_VALUE
var y = Int.MIN_VALUE
val areas = mutableListOf(Pair(Pair(0, 0), Pair(max, max)))
while (areas.size > 0) {
val area = areas.removeFirst()
if (area.first.first == area.second.first && area.first.second == area.second.second) {
if (!isCovered(area.first.first, area.first.second)) {
x = area.first.first
y = area.first.second
}
} else if (!isTotallyCovered(area)) {
val x1 = area.first.first
val x3 = area.second.first
val x2 = (x1 + x3)/2
val y1 = area.first.second
val y3 = area.second.second
val y2 = (y1 + y3)/2
areas.add(Pair(Pair(x1, y1), Pair(x2, y2)))
areas.add(Pair(Pair(minOf(x2 + 1, x3), y1), Pair(x3, y2)))
areas.add(Pair(Pair<Int, Int>(x1, minOf(y2 + 1, y3)), Pair<Int, Int>(x2, y3)))
areas.add(Pair(Pair(minOf(x2 + 1, x3), minOf(y2 + 1, y3)), Pair(x3, y3)))
}
counter++
}
return x * 4_000_000L + y
}
}
fun main() {
fun part1(input: List<String>, y: Int): Int {
val map = BeaconMap()
map.input(input)
return map.checkedPlacesInLine(y)
}
fun part2(input: List<String>, maxCoord: Int): Long {
val map = BeaconMap()
map.input(input)
return map.frequency(maxCoord)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15-TestInput")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInput("Day15-Input")
println(part1(input, 2_000_000))
println(part2(input, 4_000_000))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 7,531 | AoC-2022-12-01 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem863/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem863
import com.hj.leetcode.kotlin.common.model.TreeNode
/**
* LeetCode page: [863. All Nodes Distance K in Binary Tree](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(N) where N is the number of nodes in root;
*/
fun distanceK(root: TreeNode?, target: TreeNode?, k: Int): List<Int> {
requireNotNull(root)
requireNotNull(target)
val adjacencyList = adjacencyList(root)
val bfsQueue = ArrayDeque<TreeNode>()
val visited = hashSetOf<TreeNode>()
var currentDistance = 0
bfsQueue.addLast(target)
visited.add(target)
while (bfsQueue.isNotEmpty()) {
if (currentDistance == k) {
break
}
repeat(bfsQueue.size) {
val node = bfsQueue.removeFirst()
val adjacentNodes = adjacencyList[node] ?: emptyList()
for (adjacentNode in adjacentNodes) {
if (adjacentNode !in visited) {
bfsQueue.addLast(adjacentNode)
visited.add(adjacentNode)
}
}
}
currentDistance++
}
return bfsQueue.map { it.`val` }
}
private fun adjacencyList(root: TreeNode?): Map<TreeNode, List<TreeNode>> {
val result = hashMapOf<TreeNode, MutableList<TreeNode>>()
preorderTraversal(root) { node ->
node.left?.let { left ->
result.computeIfAbsent(node) { mutableListOf() }.add(left)
result.computeIfAbsent(left) { mutableListOf() }.add(node)
}
node.right?.let { right ->
result.computeIfAbsent(node) { mutableListOf() }.add(right)
result.computeIfAbsent(right) { mutableListOf() }.add(node)
}
}
return result
}
private fun preorderTraversal(root: TreeNode?, onEachNode: (node: TreeNode) -> Unit) {
if (root == null) {
return
}
onEachNode(root)
preorderTraversal(root.left, onEachNode)
preorderTraversal(root.right, onEachNode)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,257 | hj-leetcode-kotlin | Apache License 2.0 |
capitulo5/src/main/kotlin/5.21BeaultifulStrings.kt | Cursos-Livros | 667,537,024 | false | {"Kotlin": 104564} | //5.21 (Embelezando Strings) Escreva métodos que realizam cada uma das seguintes tarefas:
//a) Verifique se a string termina com um ponto final e, caso contrário, adicione um ponto final.
//b) Verifique se a string começa com letra maiúscula, caso contrário, coloque a primeira letra em maiúscula.
//c) Use os métodos desenvolvidos nas partes (a) e (b) e escreva um método beautifyString
//que recebe uma string do usuário e, em seguida, chama os métodos em (a) e (b) para garantir
//que a string está formatada corretamente, ou seja, a string tem um ponto final no final,
////e uma primeira letra maiúscula. Certifique-se de produzir a string depois de embelezada!
fun main() {
println("Digite uma String")
var string = leInput7()
var tamanhoString = string.length
val primeiraLetra = verificaPrimeiraLetra(string)
val pontoFinal = verificaPontoFinal(string, tamanhoString)
val bonita = verificaBonita(primeiraLetra, pontoFinal)
if(bonita){
println("A String é bonita")
}else{
println("A String nao é bonita")
}
}
fun leInput7(): String {
val input = readLine() ?: "0"
return input
}
fun verificaPrimeiraLetra(string: String): Boolean {
val primeiraLetra = string[0]
val capitalizada = primeiraLetra.isUpperCase()
return capitalizada
}
fun verificaPontoFinal(string: String, tamanhoString: Int): Boolean {
val ultimoCharactere = string[tamanhoString - 1]
val pontoFinal = ultimoCharactere == '.'
return pontoFinal
}
fun verificaBonita(primeiraLetra: Boolean, pontoFinal: Boolean): Boolean {
return primeiraLetra && pontoFinal
} | 0 | Kotlin | 0 | 0 | f2e005135a62b15360c2a26fb6bc2cbad18812dd | 1,638 | Kotlin-Como-Programar | MIT License |
src/main/kotlin/g1501_1600/s1595_minimum_cost_to_connect_two_groups_of_points/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1501_1600.s1595_minimum_cost_to_connect_two_groups_of_points
// #Hard #Array #Dynamic_Programming #Matrix #Bit_Manipulation #Bitmask
// #2023_06_14_Time_278_ms_(100.00%)_Space_38.4_MB_(100.00%)
class Solution {
fun connectTwoGroups(cost: List<List<Int>>): Int {
// size of set 1
val m = cost.size
// size of set 2
val n = cost[0].size
val mask = 1 shl m
// min cost to connect nodes in set 1 (of different states);
var record = IntArray(mask)
record.fill(Int.MAX_VALUE)
// since we use record to get the min cost of connecting nodes in set 1
// we shall go through nodes in set 2 one by one, to make sure they are connected
// base case:
record[0] = 0
for (col in 0 until n) {
val tmpRecord = IntArray(mask)
tmpRecord.fill(Int.MAX_VALUE)
// try connection with each of the node in set 1
for (row in 0 until m) {
for (msk in 0 until mask) {
// the new min cost should be based on the cost record of connecting previous
// node in set 2;
val newMask = msk or (1 shl row)
if (record[msk] != Int.MAX_VALUE) {
tmpRecord[newMask] = Math.min(tmpRecord[newMask], record[msk] + cost[row][col])
}
// if row nodes in this state has not been connected yet, and the msk is
// achievable by connecting the current node
// then check whether connect the current node multiple times will benefit the
// cost
if (msk and (1 shl row) == 0 && tmpRecord[msk] != Int.MAX_VALUE) {
tmpRecord[newMask] = Math.min(
tmpRecord[newMask],
tmpRecord[msk] + cost[row][col]
)
}
}
}
// use tmpRecord to update record
record = tmpRecord
}
return record[(1 shl m) - 1]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,141 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/game/CountPoints.kt | jangalinski | 154,946,573 | false | null | package com.github.jangalinski.tidesoftime.game
import com.github.jangalinski.tidesoftime.Card
import com.github.jangalinski.tidesoftime.CardFeature
fun countPoints(k1: Kingdom, k2: Kingdom): Pair<Result, Result> {
// assert(k1.size == k2.size)
val r1 = Result(k1)
val r2 = Result(k2)
arrayOf(r1,r2).forEach {
missingSymbols(it)
pointsPerSymbol(it)
setOfSymbols(it)
}
majorityOfSymbols(r1, r2.k)
majorityOfSymbols(r2, r1.k)
majorityOfSingle(r1,r2.k)
majorityOfSingle(r2,r1.k)
highestSingleCard(r1,r2)
highestSingleCard(r2,r1)
return r1 to r2
}
fun majorityOfSymbols(r:Result, other:Kingdom) {
r.k.filter { it.card.feature is CardFeature.MajorityOfSymbols }.forEach {
val symbol = (it.card.feature as CardFeature.MajorityOfSymbols).symbol
val majority = r.k.compare(r.k.effectiveNumberOf[symbol]!!, other.effectiveNumberOf[symbol]!!)
if (majority) {
r.points[it.card] = it.card.feature.points
}
}
}
fun majorityOfSingle(r:Result, other:Kingdom) {
r.k.filter { it.card.feature is CardFeature.MajorityOfSingleSymbols }.forEach {
val majority = r.k.compare(r.k.numberOfSingleSymbols, other.numberOfSingleSymbols)
if (majority) {
r.points[it.card] = it.card.feature.points
}
}
}
fun pointsPerSymbol(r:Result) {
r.k.filter { it.card.feature is CardFeature.PointsPerSymbol }.forEach {
val num = r.k.effectiveNumberOf[(it.card.feature as CardFeature.PointsPerSymbol).symbol]!! * it.card.feature.points
r.points.put(it.card, num)
}
}
fun missingSymbols(r: Result) {
r.k.filter { it.card.feature is CardFeature.PointsPerMissingSymbol }.forEach {
val numMissing = r.k.numberOf.filter { it.value == 0 }.count()
r.points[it.card] = numMissing * it.card.feature.points
}
}
fun setOfSymbols(r:Result) {
r.k.filter { it.card.feature is CardFeature.PointsForCompleteSetOf }.forEach {
val set = (it.card.feature as CardFeature.PointsForCompleteSetOf).symbols
val points = it.card.feature.points
val numberOfSets = set.map { r.k.numberOf[it]!! }.min()!!
r.points[it.card] = numberOfSets * points
}
}
fun highestSingleCard(r: Result, other:Result) {
r.k.filter { it.card.feature is CardFeature.HighestSingleCardScore }.forEach {
if (r.k.compare(r.highestScore, other.highestScore)) {
r.points[it.card] = it.card.feature.points
}
}
}
data class Result(val k: Kingdom, val points: MutableMap<Card, Int> = mutableMapOf()) {
val sum by lazy {
points.values.sum()
}
val highestScore by lazy {
points.values.max()!!
}
}
| 0 | Kotlin | 0 | 0 | 945109d12c3b089935f9fb1ea91633194cce8820 | 2,579 | tidesoftime | Apache License 2.0 |
aoc21/day_24/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
import kotlin.math.min
fun getVal(v: String, regs: Map<Char, Long>): Long =
if (v[0].isLetter()) regs.get(v[0])!! else v.toLong()
fun execSegment(input: Char, initZ: Long, code: List<String>): Long {
val regs = ('x'..'z').map { it to 0.toLong() }.toMap().toMutableMap()
regs.put('z', initZ)
for (line in code) {
val inst = line.split(" ")
when (inst[0]) {
"inp" -> regs.put(inst[1][0], input.toString().toLong())
"add" -> regs.put(inst[1][0], getVal(inst[1], regs) + getVal(inst[2], regs))
"mul" -> regs.put(inst[1][0], getVal(inst[1], regs) * getVal(inst[2], regs))
"div" -> regs.put(inst[1][0], getVal(inst[1], regs) / getVal(inst[2], regs))
"mod" -> regs.put(inst[1][0], getVal(inst[1], regs) % getVal(inst[2], regs))
"eql" -> regs.put(
inst[1][0],
if (getVal(inst[1], regs) == getVal(inst[2], regs)) 1 else 0
)
}
}
return regs.get('z')!!
}
fun main() {
val input = File("input").readLines().asSequence()
val segmentSize = input.drop(1).takeWhile { !it.startsWith("inp") }.count() + 1
var inputValues = mutableMapOf(0.toLong() to mutableListOf(""))
for (segment in input.chunked(segmentSize).toList().asReversed()) {
val newInputValues = mutableMapOf<Long, MutableList<String>>()
val maxZ = min(inputValues.keys.maxOrNull()!! * 26 + 26, 1000000)
for (w in '1'..'9') {
for (z in 0..maxZ) {
val segmentRes = execSegment(w, z.toLong(), segment)
val numbers = inputValues.get(segmentRes)
if (numbers != null) {
for (number in numbers) {
if (!newInputValues.containsKey(z.toLong()))
newInputValues.put(z.toLong(), mutableListOf<String>())
newInputValues.get(z.toLong())!!.add(w + number)
}
}
}
}
inputValues = newInputValues
}
println("First: ${inputValues.get(0)?.maxOrNull()!!}")
println("Second: ${inputValues.get(0)?.minOrNull()!!}")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 2,202 | advent-of-code | MIT License |
src/main/kotlin/biz/koziolek/adventofcode/year2022/day13/day13.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2022.day13
import biz.koziolek.adventofcode.findInput
import java.util.ArrayDeque
import java.util.Deque
fun main() {
val inputFile = findInput(object {})
val packetPairs = parsePacketPairs(inputFile.bufferedReader().readLines())
println("Sum of packet pairs in right order: ${getSumOfPacketPairsInRightOrder(packetPairs)}")
println("Decoder key: ${getDecoderKey(packetPairs)}")
}
val DIVIDER_PACKETS = listOf(
parseListPacket("[[2]]"),
parseListPacket("[[6]]"),
)
sealed interface Packet : Comparable<Packet>
data class IntPacket(val value: Int) : Packet {
override fun compareTo(other: Packet): Int =
when (other) {
is IntPacket -> this.value.compareTo(other.value)
is ListPacket -> ListPacket(this).compareTo(other)
}
override fun toString() = value.toString()
}
data class ListPacket(val children: List<Packet>) : Packet {
constructor(vararg ch: Packet) : this(ch.asList())
fun addChild(child: Packet): ListPacket =
copy(children = children + child)
override fun compareTo(other: Packet): Int =
when (other) {
is IntPacket -> this.compareTo(ListPacket(other))
is ListPacket -> {
val childComparison = this.children.zip(other.children)
.fold(0) { acc, (first, second) ->
if (acc != 0) {
acc
} else {
first.compareTo(second)
}
}
if (childComparison != 0) {
childComparison
} else {
this.children.size.compareTo(other.children.size)
}
}
}
override fun toString() = children.joinToString(",", "[", "]")
}
fun parsePacketPairs(lines: Iterable<String>): List<Pair<ListPacket, ListPacket>> =
lines.filter { it.isNotBlank() }
.chunked(2)
.map { (firstLine, secondLine) ->
parseListPacket(firstLine) to parseListPacket(secondLine)
}
fun parseListPacket(line: String): ListPacket {
val stack: Deque<ListPacket> = ArrayDeque()
var isParsingNumber = false
var number = 0
fun pushChildUp() {
if (stack.size > 1) {
val inner = stack.pop()
val outer = stack.pop()
stack.push(outer.addChild(inner))
}
}
fun pushNumber() {
if (isParsingNumber) {
val list = stack.pop()
stack.push(list.addChild(IntPacket(number)))
isParsingNumber = false
number = 0
}
}
for (c in line) {
when (c) {
'[' -> stack.push(ListPacket())
']' -> {
pushNumber()
pushChildUp()
}
',' -> pushNumber()
in '0'..'9' -> {
isParsingNumber = true
number = number * 10 + c.digitToInt()
}
else -> throw IllegalStateException("Unexpected character: '$c'")
}
}
while (stack.size > 1) {
pushChildUp()
}
return stack.single()
}
fun getSumOfPacketPairsInRightOrder(packetPairs: List<Pair<Packet, Packet>>): Int =
packetPairs
.withIndex()
.filter { (_, pair) -> pair.first < pair.second }
.sumOf { it.index + 1 }
fun getDecoderKey(packetPairs: List<Pair<Packet, Packet>>): Int =
packetPairs.asSequence()
.flatMap { listOf(it.first, it.second) }
.let { it + DIVIDER_PACKETS }
.sorted()
.withIndex()
.filter { (_, packet) -> packet in DIVIDER_PACKETS }
.map { (index, _) -> index + 1 }
.reduce(Int::times)
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 3,791 | advent-of-code | MIT License |
src/main/kotlin/com/github/davio/aoc/y2021/Day9.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2021
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.call
import com.github.davio.aoc.general.getInputAsList
import kotlin.system.measureTimeMillis
fun main() {
Day9.getResultPart1()
measureTimeMillis {
Day9.getResultPart2()
}.call { println("Took $it ms") }
}
object Day9 : Day() {
/*
--- Day 9: Smoke Basin ---
These caves seem to be lava tubes. Parts are even still volcanically active; small hydrothermal vents release smoke into the caves that slowly settles like rain.
If you can model how the smoke flows through the caves, you might be able to avoid it and be that much safer. The submarine generates a heightmap of the floor of the nearby caves for you (your puzzle input).
Smoke flows to the lowest point of the area it's in. For example, consider the following heightmap:
2199943210
3987894921
9856789892
8767896789
9899965678
Each number corresponds to the height of a particular location, where 9 is the highest and 0 is the lowest a location can be.
Your first goal is to find the low points - the locations that are lower than any of its adjacent locations. Most locations have four adjacent locations (up, down, left, and right); locations on the edge or corner of the map have three or two adjacent locations, respectively. (Diagonal locations do not count as adjacent.)
In the above example, there are four low points, all highlighted: two are in the first row (a 1 and a 0), one is in the third row (a 5), and one is in the bottom row (also a 5). All other locations on the heightmap have some lower adjacent location, and so are not low points.
The risk level of a low point is 1 plus its height. In the above example, the risk levels of the low points are 2, 1, 6, and 6. The sum of the risk levels of all low points in the heightmap is therefore 15.
Find all of the low points on your heightmap. What is the sum of the risk levels of all low points on your heightmap?
*/
private var cave: Array<IntArray> = arrayOf()
private const val boldRedColor = "\u001B[31m\u001B[1m"
private const val ansiReset = "\u001B[0m"
fun getResultPart1() {
cave = getCave()
val lowPoints = (cave.indices).flatMap { y ->
val result = (cave[0].indices).filter { x ->
val row = cave[y]
val height = row[x]
if (height == 9 || !isMinimumHeight(height, x, y)) {
print("$ansiReset$height")
false
} else {
print("$boldRedColor$height")
true
}
}.map { x ->
cave[y][x]
}
println()
result
}
println(lowPoints)
println(lowPoints.sum() + lowPoints.count())
}
private fun isMinimumHeight(height: Int, x: Int, y: Int): Boolean {
return getNeighborHeights(x, y).all { height < it }
}
private fun getNeighborHeights(x: Int, y: Int): Sequence<Int> {
return (y - 1..y + 1).flatMap { yNeighbor ->
(x - 1..x + 1).filter { xNeighbor ->
(yNeighbor == y || xNeighbor == x)
&& !(yNeighbor == y && xNeighbor == x)
&& yNeighbor in (cave.indices)
&& xNeighbor in (cave[0].indices)
}.map { xNeighbor ->
cave[yNeighbor][xNeighbor]
}
}.asSequence()
}
/*
--- Part Two ---
Next, you need to find the largest basins so you know what areas are most important to avoid.
A basin is all locations that eventually flow downward to a single low point. Therefore, every low point has a basin, although some basins are very small. Locations of height 9 do not count as being in any basin, and all other locations will always be part of exactly one basin.
The size of a basin is the number of locations within the basin, including the low point. The example above has four basins.
The top-left basin, size 3:
2199943210
3987894921
9856789892
8767896789
9899965678
The top-right basin, size 9:
2199943210
3987894921
9856789892
8767896789
9899965678
The middle basin, size 14:
2199943210
3987894921
9856789892
8767896789
9899965678
The bottom-right basin, size 9:
2199943210
3987894921
9856789892
8767896789
9899965678
Find the three largest basins and multiply their sizes together. In the above example, this is 9 * 14 * 9 = 1134.
What do you get if you multiply together the sizes of the three largest basins?
*/
private var basinIndex = -1
private val basinSizes: MutableList<Int> = mutableListOf()
private val pointsInBasins: MutableSet<Pair<Int, Int>> = mutableSetOf()
fun getResultPart2() {
cave = getCave()
(cave.indices).forEach { y ->
(cave[0].indices).asSequence().filter { x ->
cave[y][x] != 9 && !pointsInBasins.contains(Pair(x, y))
}.forEach { x ->
addBasin(x, y)
}
}
val largestThreeBasinSizesMultiplied = basinSizes.sortedDescending()
.take(3)
.also { println(it) }
.reduce { left, right -> left * right }
println(largestThreeBasinSizesMultiplied)
}
private fun addBasin(x: Int, y: Int) {
basinSizes.add(1)
basinIndex++
pointsInBasins.add(Pair(x, y))
addBasinNeighbors(x, y)
}
private fun addBasinNeighbors(x: Int, y: Int) {
(y - 1..y + 1).forEach { yNeighbor ->
(x - 1..x + 1).asSequence().filter { xNeighbor ->
(yNeighbor == y || xNeighbor == x)
&& !(yNeighbor == y && xNeighbor == x)
&& yNeighbor in (cave.indices)
&& xNeighbor in (cave[0].indices)
&& cave[yNeighbor][xNeighbor] != 9
&& !pointsInBasins.contains(Pair(xNeighbor, yNeighbor))
}.forEach { xNeighbor ->
pointsInBasins.add(Pair(xNeighbor, yNeighbor))
addBasinNeighbors(xNeighbor, yNeighbor)
basinSizes[basinIndex]++
}
}
}
private fun getCave(): Array<IntArray> {
return getInputAsList().map { line ->
line.toCharArray().map { it.digitToInt() }.toIntArray()
}.toTypedArray()
}
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 6,414 | advent-of-code | MIT License |
src/Day09.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | fun main() {
fun ropeTailTravel(input: List<String>, ropeLength: Int): Int {
val knots = Array(ropeLength) { Vector2d(0, 0) }
val visited = mutableSetOf(knots.last())
for (command in input) {
val (direction, steps) = command.split(" ")
repeat(steps.toInt()) {
knots[0] += when (direction) {
"U" -> Vector2d.UP
"D" -> Vector2d.DOWN
"L" -> Vector2d.LEFT
"R" -> Vector2d.RIGHT
else -> throw Exception("Unknown command $direction")
}
for (n in 1 until knots.size) {
val diff = knots[n - 1] - knots[n]
if (diff.length() > 1) // we need to move
knots[n] += diff.normalized()
}
visited.add(knots.last())
}
}
return visited.size
}
fun part1(input: List<String>) = ropeTailTravel(input, 2)
fun part2(input: List<String>) = ropeTailTravel(input, 10)
test(
day = 9,
testTarget1 = 13,
testTarget2 = 1,
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 1,221 | aoc2022 | Apache License 2.0 |
src/Day10.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
fun main() {
val input = readInput("Day10")
val n = input.size
val m = input[0].length
val south = setOf('|', '7', 'F')
val north = setOf('|', 'L', 'J')
val west = setOf('-', 'J', '7')
val east = setOf('-', 'L', 'F')
fun solve1(i0: Int, j0: Int): Pair<Int, Int> {
val len = Array(n) { IntArray(m) }
len[i0][j0] = 1
val queue = ArrayDeque(listOf(i0 to j0))
val path = mutableListOf(i0 to j0)
while (queue.isNotEmpty()) {
val (i, j) = queue.removeFirst()
val c = input[i][j]
fun go(i1: Int, j1: Int, set: Set<Char>): Boolean {
if (i1 !in input.indices || j1 !in input[i1].indices || input[i1][j1] !in set || len[i1][j1] > 0) return false
queue.add(i1 to j1)
path.add(i1 to j1)
len[i1][j1] = len[i][j] + 1
return true
}
when (c) {
'|' -> {
go(i-1, j, south)
go(i+1, j, north)
}
'-' -> {
go(i, j-1, east)
go(i, j+1, west)
}
'L' -> {
go(i-1, j, south)
go(i, j+1, west)
}
'J' -> {
go(i-1, j, south)
go(i, j-1, east)
}
'7' -> {
go(i, j-1, east)
go(i+1, j, north)
}
'F' -> {
go(i, j+1, west)
go(i+1, j, north)
}
'S' -> {
go(i-1, j, south) ||
go(i+1, j, north) ||
go(i, j-1, east) ||
go(i, j+1, west)
}
}
}
val res1 = (path.size+1)/2
var res2 = 0
for (i in input.indices) {
for (j in input[i].indices) {
if (len[i][j] > 0) continue
var ang = 0.0
for (k in path.indices) {
val a = path[k]
val b = i to j
val c = path[(k+1) % path.size]
val a1 = atan2(a.first - b.first + 0.0, a.second - b.second + 0.0)
var a2 = atan2(c.first - b.first + 0.0, c.second - b.second + 0.0)
if (a2 - a1 > PI) a2 -= 2*PI
if (a2 - a1 < -PI) a2 += 2*PI
ang += a2 - a1
}
if (abs(ang) < 1E-9) continue
res2 ++
}
}
return res1 to res2
}
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == 'S') {
val (res1, res2) = solve1(i, j)
println(res1)
println(res2)
}
}
}
} | 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 3,017 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/AddBinary.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.math.BigInteger
/**
* Given two binary strings a and b, return their sum as a binary string.
*/
fun interface AddBinaryStrategy {
operator fun invoke(a: String, b: String): String
}
/**
* Time complexity: O(max(N,M)), where N and M are lengths of the input strings a and b.
* Space complexity: O(max(N,M)) to keep the answer.
*/
class AddBinaryBitByBitComputation : AddBinaryStrategy {
/**
* Adds two binary strings and returns their sum as a binary string.
*
* @param a the first binary string
* @param b the second binary string
* @return the sum of the binary strings as a binary string
*/
override operator fun invoke(a: String, b: String): String {
val sb = StringBuilder()
var i: Int = a.length - 1
var j: Int = b.length - 1
var carry = 0
while (i >= 0 || j >= 0) {
var sum = carry
if (j >= 0) sum += b[j--] - '0'
if (i >= 0) sum += a[i--] - '0'
sb.append(sum % 2)
carry = sum / 2
}
if (carry != 0) sb.append(carry)
return sb.reverse().toString()
}
}
/**
* Time complexity : O(N+M), where N and M are lengths of the input strings a and b.
* Space complexity: O(max(N,M)) to keep the answer.
*/
class AddBinaryBitManipulation : AddBinaryStrategy {
/**
* Performs binary addition of two strings and returns the sum as a binary string.
*
* @param a The first binary string.
* @param b The second binary string.
* @return The sum of the two binary strings as a binary string.
*/
override operator fun invoke(a: String, b: String): String {
if (a.isEmpty() || b.isEmpty()) return ""
val firstOperand = BigInteger(a, 2)
val secondOperand = BigInteger(b, 2)
val zeroBigInteger = BigInteger("0", 2)
return binaryAddition(firstOperand, secondOperand, zeroBigInteger).toString(2)
}
private fun binaryAddition(
firstOperand: BigInteger,
secondOperand: BigInteger,
zeroBigInteger: BigInteger,
): BigInteger {
var tempResult: BigInteger
var carryResult: BigInteger
var x = firstOperand
var y = secondOperand
while (y.compareTo(zeroBigInteger) != 0) {
tempResult = x.xor(y)
carryResult = x.and(y).shiftLeft(1)
x = tempResult
y = carryResult
}
return x
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,107 | kotlab | Apache License 2.0 |
src/Day03.kt | rk012 | 574,169,156 | false | {"Kotlin": 9389} | private const val ITEM_TYPES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun main() {
fun part1(input: List<String>) = input.map { items ->
items.length.let {
items.slice(0 until it / 2) to items.slice(it / 2 until it)
}
}.map { (item1, item2) ->
item1.find { item2.contains(it) }!!
}.sumOf {
ITEM_TYPES.indexOf(it) + 1
}
fun part2(input: List<String>) = input.chunked(3).map { (b1, b2, b3) ->
b1.first { b2.contains(it) && b3.contains(it) }
}.sumOf {
ITEM_TYPES.indexOf(it) + 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bfb4c56c4d4c8153241fa6aa6ae0e829012e6679 | 861 | advent-of-code-2022 | Apache License 2.0 |
src/exercises/Day14.kt | Njko | 572,917,534 | false | {"Kotlin": 53729} | // ktlint-disable filename
package exercises
import readInput
data class Coord(val x: Int, val y: Int)
fun main() {
fun extractPaths(input: List<String>) = input.map { line ->
val points = line.split(" -> ")
points.map {
val coord = it.split(",")
Coord(coord[0].toInt(), coord[1].toInt())
}.toList()
}
fun fillPaths(paths: List<List<Coord>>): List<List<Coord>> {
val filledPaths = mutableListOf<List<Coord>>()
paths.forEach { path ->
val filledPath = mutableSetOf<Coord>()
path.windowed(2, 1, partialWindows = false).toList().map { edges ->
val start = edges[0]
val end = edges[1]
if (start.x == end.x) {
if (start.y < end.y) {
for (i in start.y..end.y) {
filledPath.add(Coord(start.x, i))
}
} else {
for (i in end.y..start.y) {
filledPath.add(Coord(start.x, i))
}
}
} else {
if (start.x < end.x) {
for (i in start.x..end.x) {
filledPath.add(Coord(i, start.y))
}
} else {
for (i in end.x..start.x) {
filledPath.add(Coord(i, start.y))
}
}
}
}
filledPaths.add(filledPath.toList())
}
return filledPaths.toList()
}
fun canGoDownTo(currentGrain: Coord, obstacles: List<Coord>): Coord? {
val possiblePosition =
mutableListOf(
Coord(currentGrain.x, currentGrain.y + 1),
Coord(currentGrain.x - 1, currentGrain.y + 1),
Coord(currentGrain.x + 1, currentGrain.y + 1)
)
obstacles
.filter { currentGrain.y + 1 == it.y }
.filter {
currentGrain.x - 1 == it.x ||
currentGrain.x == it.x ||
currentGrain.x + 1 == it.x
}.map { obstacle ->
possiblePosition.remove(obstacle)
}
return possiblePosition.firstOrNull()
}
fun canGoDownToV2(currentGrain: Coord, obstacles: List<Coord>, floorLevel: Int): Coord? {
val possiblePosition =
mutableListOf(
Coord(currentGrain.x, currentGrain.y + 1),
Coord(currentGrain.x - 1, currentGrain.y + 1),
Coord(currentGrain.x + 1, currentGrain.y + 1)
)
val floorPosition = listOf(
Coord(currentGrain.x, floorLevel),
Coord(currentGrain.x - 1, floorLevel),
Coord(currentGrain.x + 1, floorLevel)
)
val finalObstacles = obstacles + floorPosition
val filteredObstacles = finalObstacles
.filter { currentGrain.y + 1 == it.y }
.filter {
currentGrain.x - 1 == it.x ||
currentGrain.x == it.x ||
currentGrain.x + 1 == it.x
}
filteredObstacles.forEach { obstacle ->
possiblePosition.remove(obstacle)
}
return possiblePosition.firstOrNull()
}
fun part1(input: List<String>): Int {
val paths = extractPaths(input)
val obstacles = fillPaths(paths).flatten().toMutableSet()
val pathObstacles = obstacles.size
val theAbyss = obstacles.maxOf { it.y } + 10
var didNotFallIntoTheAbyss = true
do {
var currentGrain = Coord(500, 0)
do {
val canGoTo = canGoDownTo(currentGrain, obstacles.toList())
if (canGoTo != null) {
currentGrain = canGoTo
} else {
obstacles.add(currentGrain)
}
} while ( // EXIT : sand became stable OR sand is in abyss
canGoTo != null && currentGrain.y < theAbyss
)
if (currentGrain.y >= theAbyss) didNotFallIntoTheAbyss = false
} while (didNotFallIntoTheAbyss)
return obstacles.size - pathObstacles
}
fun part2(input: List<String>): Int {
val paths = extractPaths(input)
val obstacles = fillPaths(paths).flatten().toMutableSet()
val pathObstacles = obstacles.size
val theFloor = obstacles.maxOf { it.y } + 2
var lastGrainDidMove = true
do {
var currentGrain = Coord(500, 0)
do {
val floorPosition = listOf(
Coord(currentGrain.x, theFloor),
Coord(currentGrain.x - 1, theFloor),
Coord(currentGrain.x + 1, theFloor)
)
val canGoTo = canGoDownTo(currentGrain, obstacles.toList() + floorPosition)
if (canGoTo != null) {
currentGrain = canGoTo
} else {
obstacles.add(currentGrain)
}
} while ( // EXIT : sand became stable
canGoTo != null
)
if (currentGrain == Coord(500, 0)) lastGrainDidMove = false
} while (lastGrainDidMove)
return obstacles.size - pathObstacles
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
println("Test results:")
// println(part1(testInput))
// check(part1(testInput) == 24)
//
println(part2(testInput))
// check(part2(testInput) == 93)
val input = readInput("Day14")
println("Final results:")
// println(part1(input))
// check(part1(input) == 799)
println(part2(input))
// check(part2(input) == 0)
println("End")
}
| 0 | Kotlin | 0 | 2 | 68d0c8d0bcfb81c183786dfd7e02e6745024e396 | 5,949 | advent-of-code-2022 | Apache License 2.0 |
leetcode-75-kotlin/src/main/kotlin/IsSubsequence.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
*
* A subsequence of a string is a new string that is formed from the original string by deleting some
* (can be none) of the characters without disturbing the relative positions of the remaining characters.
* (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
*
*
*
* Example 1:
*
* Input: s = "abc", t = "ahbgdc"
* Output: true
* Example 2:
*
* Input: s = "axc", t = "ahbgdc"
* Output: false
*
*
* Constraints:
*
* 0 <= s.length <= 100
* 0 <= t.length <= 10^4
* s and t consist only of lowercase English letters.
*
*
* Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 10^9,
* and you want to check one by one to see if t has its subsequence.
* In this scenario, how would you change your code?
* @see <a href="https://leetcode.com/problems/is-subsequence/">LeetCode</a>
*/
fun isSubsequence(s: String, t: String): Boolean {
var sIndex = 0
var tIndex = 0
while (sIndex < s.length && tIndex < t.length) {
if (s[sIndex] == t[tIndex]) {
sIndex++
}
tIndex++
}
return sIndex == s.length
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,206 | leetcode-75 | Apache License 2.0 |
src/main/kotlin/com/lucaszeta/adventofcode2020/day06/day06.kt | LucasZeta | 317,600,635 | false | null | package com.lucaszeta.adventofcode2020.day06
import com.lucaszeta.adventofcode2020.ext.getResourceAsText
fun main() {
val input = parseData(getResourceAsText("/day06/customs-form-answers.txt"))
val sumQuestionsAnyoneAnswered = input
.map(::countQuestionsAnyoneAnswered)
.reduce(Int::plus)
val sumQuestionsEveryoneAnswered = input
.map(::countQuestionsEveryoneAnswered)
.reduce(Int::plus)
println("Sum of questions anyone answered: $sumQuestionsAnyoneAnswered")
println("Sum of questions everyone answered: $sumQuestionsEveryoneAnswered")
}
fun countQuestionsAnyoneAnswered(questions: List<String>) =
questions.joinToString("").toSet().size
fun countQuestionsEveryoneAnswered(questions: List<String>) = questions
.map { it.chunked(1) }
.reduce { commonQuestions, currentQuestions ->
commonQuestions.intersect(currentQuestions).toList()
}.size
fun parseData(input: String) = input
.split("\n\n")
.map { group ->
group.split("\n").filter { it.isNotEmpty() }
}
| 0 | Kotlin | 0 | 1 | 9c19513814da34e623f2bec63024af8324388025 | 1,061 | advent-of-code-2020 | MIT License |
src/Day02.kt | maewCP | 579,203,172 | false | {"Kotlin": 59412} | fun main() {
fun calcScore(a: Int, b: Int): Int {
// draw
if (a == b) return 3 + b
// win
if ((a == 1 && b == 2) || (a == 2 && b == 3) || (a == 3 && b == 1)) return 6 + b
// lose
return b
}
fun followCmd(a: Int, command: String): Int {
return when (command) {
"WIN" -> when (a) {
1 -> 2
2 -> 3
3 -> 1
else -> throw RuntimeException()
}
"DRAW" -> a
"LOSE" -> when (a) {
1 -> 3
2 -> 1
3 -> 2
else -> throw RuntimeException()
}
else -> throw RuntimeException()
}
}
fun part1(input: List<String>): Int {
var score = 0
input.forEach { match ->
val op = when (match[0]) {
'A' -> 1
'B' -> 2
'C' -> 3
else -> throw RuntimeException("Wrong input")
}
val me = when (match[2]) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> throw RuntimeException("Wrong input")
}
score += calcScore(op, me)
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach { match ->
val op = when (match[0]) {
'A' -> 1
'B' -> 2
'C' -> 3
else -> throw RuntimeException("Wrong input")
}
val cmd = when (match[2]) {
'X' -> "LOSE"
'Y' -> "DRAW"
'Z' -> "WIN"
else -> throw RuntimeException("Wrong input")
}
val me2 = followCmd(op, cmd)
score += calcScore(op, me2)
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 8924a6d913e2c15876c52acd2e1dc986cd162693 | 2,188 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2020/day9/XmasEncryption.kt | arnab | 75,525,311 | false | null | package aoc2020.day9
object XmasEncryption {
fun parse(data: String) = data.split("\n").map { it.toLong() }
fun findFirstInvalid(numbers: List<Long>, preamble: Int = 25) =
numbers.withIndex().find { (i, n) ->
if (i < preamble) {
false
} else {
val window = numbers.drop(i - preamble).take(preamble)
!satisfies(n, window)
}
}?.value
private fun satisfies(n: Long, window: List<Long>): Boolean {
println("Looking for a match for $n in $window")
val complements = window.associateBy({ it }, { n - it }).filter { it.key != it.value }
val match = complements.filterValues { window.contains(it) }
if (match.isEmpty()) {
return false.also { println("NOT satisfied! match!") }
}
return true.also { println("Satisfied: $match") }
}
fun findEncryptionWeakness(numbers: List<Long>, target: Long) =
findMatchingSubRange(numbers, target).let { matchingNumbers ->
matchingNumbers.minOrNull()!! + matchingNumbers.maxOrNull()!!
}
private fun findMatchingSubRange(numbers: List<Long>, target: Long): List<Long> {
for (i in numbers.indices) {
for (j in i + 1 until numbers.size) {
val window = numbers.subList(i, j)
if (window.sum() == target) return window
}
}
return emptyList()
}
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 1,468 | adventofcode | MIT License |
advent/src/test/kotlin/org/elwaxoro/advent/y2022/Dec02.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2022
import org.elwaxoro.advent.PuzzleDayTester
import java.lang.IllegalStateException
/**
* Day 2: Rock Paper Scissors
*/
class Dec02 : PuzzleDayTester(2, 2022) {
/**
* Parse to RPS on both sides, then play as last against first
*/
override fun part1(): Any = load().map { it.split(" ").map { it.parseRPS() } }.sumOf { it.last().play(it.first()) }// == 10718
/**
* Parse first to RPS, leave last alone, play as whatever RPS is appropriate for the desired outcome
*/
override fun part2(): Any = load().map {
it.split(" ").let { it.first().parseRPS() to it.last() }
}.sumOf { (them, us) ->
when (us) {
"X" -> them.wins().play(them) // we need to lose
"Y" -> them.play(them) // we need to tie
"Z" -> them.loses().play(them) // we need to win
else -> throw IllegalStateException("I can't believe you've done this to $us")
}
}// == 14652
/**
* Why an enum? Not really sure :shrug:
* It didn't buy me much
*/
private enum class RPS(val baseScore: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun play(that: RPS): Int =
when (that) {
wins() -> 6 // this wins
this -> 3 // this ties
else -> 0 // this loses
} + baseScore
fun wins(): RPS =
when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
fun loses(): RPS =
when (this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
private fun String.parseRPS(): RPS = when (this) {
"A" -> RPS.ROCK
"B" -> RPS.PAPER
"C" -> RPS.SCISSORS
"X" -> RPS.ROCK
"Y" -> RPS.PAPER
"Z" -> RPS.SCISSORS
else -> throw IllegalStateException("Can't parse $this into RPS")
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,015 | advent-of-code | MIT License |
leetcode/src/queue/Q1700.kt | zhangweizhe | 387,808,774 | false | null | package queue
import java.util.*
fun main() {
// 1700. 无法吃午餐的学生数量
// https://leetcode-cn.com/problems/number-of-students-unable-to-eat-lunch/
println(countStudents1(intArrayOf(1,1,1,0,0,1), intArrayOf(1,0,0,0,1,1)))
}
fun countStudents(students: IntArray, sandwiches: IntArray): Int {
val stuQueue = LinkedList<Int>()
val sandStack = Stack<Int>()
for (s in students) {
stuQueue.offer(s)
}
for (s in sandwiches.reversedArray()) {
sandStack.push(s)
}
var remainStuCount = students.size
var loopCount = 0
while (remainStuCount != loopCount-1 && stuQueue.isNotEmpty() && sandStack.isNotEmpty()) {
if (stuQueue.peek() == sandStack.peek()) {
stuQueue.poll()
sandStack.pop()
loopCount = 0
remainStuCount--
}else {
loopCount++
stuQueue.offer(stuQueue.poll())
}
}
return remainStuCount
}
/**
* 统计两种学生的数量
* 遍历三明治数组,如果当前的三明治没有学生喜欢了,退出遍历,剩下的学生数量即是无法吃午餐的学生数量
*/
fun countStudents1(students: IntArray, sandwiches: IntArray): Int {
val stuLike = IntArray(2)
for (i in students) {
stuLike[i]++
}
for (s in sandwiches) {
if (stuLike[s] > 0) {
stuLike[s]--
}else {
break
}
}
return stuLike[0] + stuLike[1]
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,486 | kotlin-study | MIT License |
AdventOfCodeDay10/src/nativeMain/kotlin/Day10.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | class Day10(private val lines:List<String>) {
fun solvePart1() = lines.map { it.decode() }.sumOf { it.score() }
fun solvePart2() = lines.filter { it.decode().score() == 0}
.map {it.fixLine()}.sorted().middle()
private fun <T> Iterable<T>.middle() = this.drop(this.count()/2).first()
private fun String.fixLine():Long {
val stack = Stack<Char>()
this.forEach {
if (it.isOpen()) {
stack.push(it)
} else {
stack.pop()
}
}
return stack.asSequence().map{it.provideClose()}.score2()
}
private fun Sequence<Char>.score2()=
this.fold(0L){a,b -> a*5 + b.score2()}
private fun Char.score2():Int =
when (this) {
')' -> 1
']' -> 2
'}' -> 3
'>' -> 4
else -> 0
}
private fun String.decode(): Char {
val stack = Stack<Char>()
this.forEach {
if (it.isOpen()) {
stack.push(it)
} else {
if (stack.isEmpty()) return it
if (!it.matchesOpen(stack.peek())) return it
stack.pop()
}
}
return '0' // no error
}
private fun Char.provideClose() =
when (this) {
'{' -> '}'
'[' -> ']'
'(' -> ')'
'<' -> '>'
else -> '0'
}
private fun Char.matchesOpen(open: Char) = this == open.provideClose()
private fun Char.isOpen() = this in setOf('(', '{', '<', '[')
private fun Char.score() =
when (this) {
'}' -> 1197
']' -> 57
'>' -> 25137
')' -> 3
else -> 0
}
} | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 1,762 | AdventOfCode2021 | The Unlicense |
src/Day01.kt | RaspiKonk | 572,875,045 | false | {"Kotlin": 17390} | /**
* Day 1: Count the calories in the elves' backpacks
*
* Part 1: Who has the most calories?
* Part 2: What are the top 3 calories combined?
*/
fun main()
{
val start = System.currentTimeMillis()
val DAY: String = "01"
println("Advent of Code 2022 - Day $DAY")
var calorieList: List<Int> = listOf()
fun part1(input: List<String>): Int
{
//println(input)
var tempAdder: Int = 0
for(line in input)
{
//println(line)
if (line.length == 0)
{
calorieList += tempAdder
tempAdder = 0
}
else
{
tempAdder += line.toInt()
}
}
return calorieList.maxOrNull() ?: 0
}
fun part2(): Int
{
//println(calorieList)
calorieList = calorieList.sorted()
//println(calorieList)
return calorieList[calorieList.size-1] + calorieList[calorieList.size-2] + calorieList[calorieList.size-3]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println("Part 1: ${part1(input)}") // 66487
println("Part 2: ${part2()}") // 197301
println("Number of elves: ${calorieList.size}") // 258
val elapsedTime = System.currentTimeMillis() - start
println("Elapsed time: $elapsedTime ms")
}
| 0 | Kotlin | 0 | 1 | 7d47bea3a5e8be91abfe5a1f750838f2205a5e18 | 1,267 | AoC_Kotlin_2022 | Apache License 2.0 |
Kotlin/src/main/kotlin/org/algorithm/problems/0055_spiral_matrix_i.kt | raulhsant | 213,479,201 | true | {"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187} | // Problem Statement
// Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
// Input:
// [
// [ 1, 2, 3 ],
// [ 4, 5, 6 ],
// [ 7, 8, 9 ]
// ]
// Output: [1,2,3,6,9,8,7,4,5]
package org.algorithm.problems
class `0055_spiral_matrix_i` {
fun canWalk(row: Int, col: Int, limits: IntArray): Boolean {
return row >= limits[0] && row < limits[1] && col >= limits[2] && col < limits[3];
}
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
val result: MutableList<Int> = mutableListOf<Int>();
if (matrix.isEmpty())
return result;
val limits: IntArray = intArrayOf(0, matrix.size, 0, matrix[0].size);
val directions: Array<Pair<Int, Int>> = arrayOf<Pair<Int, Int>>(Pair(0, 1), Pair(1, 0), Pair(0, -1), Pair(-1, 0));
val strech: Array<Pair<Int, Int>> = arrayOf<Pair<Int, Int>>(Pair(0, 1), Pair(3, -1), Pair(1, -1), Pair(2, 1));
var row: Int = 0;
var col: Int = 0;
var dir: Int = 0;
val maxResultSize: Int = matrix.size * matrix[0].size;
while (result.size < maxResultSize) {
result.add(matrix[row][col]);
while (result.size < maxResultSize && !canWalk(row + directions[dir].first, col + directions[dir].second, limits)) {
limits[strech[dir].first] += strech[dir].second;
dir = (dir + 1) % directions.size;
}
row += directions[dir].first;
col += directions[dir].second;
}
return result;
}
} | 0 | C++ | 0 | 0 | 1578a0dc0a34d63c74c28dd87b0873e0b725a0bd | 1,572 | algorithms | MIT License |
src/main/kotlin/main.kt | stury | 390,913,839 | false | null | package main.kotlin
fun distances(maze:DistanceGrid, startCell:Cell? = null ) {
var start = maze.grid[0][0]
if ( startCell != null ) {
start = startCell
}
if (start != null ) {
var distances = start.distances()
maze.distances = distances
print("\nDistances from (${start.location.x},${start.location.y}) cell\n")
print(maze.description())
}
}
fun path(maze:DistanceGrid, startCell:Cell? = null, endCell:Cell? = null) {
var start = maze.grid[0][0]
if ( startCell != null ) {
start = startCell
}
if (start != null ) {
var distances = start.distances()
maze.distances = distances
var end = maze[Location(maze.grid[maze.grid.count() - 1].count() - 1, maze.grid.count() - 1,)]
if ( endCell != null ) {
end = endCell
}
if (end != null) {
distances = distances.path(end)
print("\nPath from (${start.location.x},${start.location.y}) to (${end.location.x},${end.location.y})\n")
}
maze.distances = distances
print(maze.description())
}
}
fun main(args: Array<String>) {
val width = 10
val height = 10
val maze = DistanceGrid(Size(width,height))
//val mazeGenerator = BinaryTree()
//val mazeGenerator = RecursiveBacktracker()
val mazeGenerator = randomMazeGenerator()
val className = mazeGenerator::class.simpleName
println("Here's a maze built using the $className algorithm!")
mazeGenerator.on( maze )
print( maze.description() )
// Let's create a map of distances
distances(maze)
// Let's create a map of distances from a different start location
distances(maze, maze.grid[height/2][width/2])
// Let's create a path from upperLeft to lower right
path(maze)
// Let's create a path from a different start location
path(maze, maze.grid[height-1][0], maze.grid[0][width-1])
}
| 0 | Kotlin | 0 | 1 | d85d9ab02b70a3d7d599ed93e91c65d3f7e7bd10 | 1,943 | MazesUsingKotlin | MIT License |
2022/src/main/kotlin/de/skyrising/aoc2022/day23/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2022.day23
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
private fun parseInput(input: PuzzleInput): MutableSet<Vec2i> {
val width = input.lines.maxOf { it.length }
val height = input.lines.size
val grid = CharGrid(width, height, CharArray(width * height))
for (row in 0 until height) {
val line = input.lines[row]
for (col in 0 until width) {
grid[col, row] = if (col < line.length) line[col] else ' '
}
}
return grid.where { it == '#' }.toMutableSet()
}
private fun checkNorth(elf: Vec2i, elves: Set<Vec2i>) = elf.northWest !in elves && elf.north !in elves && elf.northEast !in elves
private fun checkSouth(elf: Vec2i, elves: Set<Vec2i>) = elf.southWest !in elves && elf.south !in elves && elf.southEast !in elves
private fun checkWest(elf: Vec2i, elves: Set<Vec2i>) = elf.northWest !in elves && elf.west !in elves && elf.southWest !in elves
private fun checkEast(elf: Vec2i, elves: Set<Vec2i>) = elf.northEast !in elves && elf.east !in elves && elf.southEast !in elves
private fun propose(elf: Vec2i, elves: Set<Vec2i>, order: Int): Vec2i {
if (elf.eightNeighbors().none { it in elves }) return elf
for (i in 0 until 4) {
when ((i + order) % 4) {
0 -> if (checkNorth(elf, elves)) return elf.north
1 -> if (checkSouth(elf, elves)) return elf.south
2 -> if (checkWest(elf, elves)) return elf.west
3 -> if (checkEast(elf, elves)) return elf.east
}
}
return elf
}
private fun round(elves: MutableSet<Vec2i>, roundCount: Int): Boolean {
val proposed = mutableMapOf<Vec2i, Vec2i>()
val proposedCount = Object2IntOpenHashMap<Vec2i>()
for (elf in elves) {
val dest = propose(elf, elves, roundCount)
proposed[elf] = dest
proposedCount.addTo(dest, 1)
}
var moved = 0
for ((elf, dest) in proposed) {
if (proposedCount.getInt(dest) == 1 && dest != elf) {
elves.remove(elf)
elves.add(dest)
moved++
}
}
return moved > 0
}
val test = TestInput("""
....#..
..###.#
#...#.#
.#...##
#.###..
##.#.##
.#..#..
""")
val test2 = TestInput("""
.....
..##.
..#..
.....
..##.
.....
""")
@PuzzleName("Unstable Diffusion")
fun PuzzleInput.part1(): Any {
val elves = parseInput(this)
repeat(10) {
round(elves, it)
}
return elves.boundingBox().area - elves.size
}
fun PuzzleInput.part2(): Any {
val elves = parseInput(this)
return 1 + countWhile { round(elves, it) }
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,647 | aoc | MIT License |
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Fenwick_Tree/Fenwick_Tree.kt | rajatenzyme | 325,100,742 | false | {"C++": 709855, "Java": 559443, "Python": 397216, "C": 381274, "Jupyter Notebook": 127469, "Go": 123745, "Dart": 118962, "JavaScript": 109884, "C#": 109817, "Ruby": 86344, "PHP": 63402, "Kotlin": 52237, "TypeScript": 21623, "Rust": 20123, "CoffeeScript": 13585, "Julia": 2385, "Shell": 506, "Erlang": 385, "Scala": 310, "Clojure": 189} | /*Fenwick Tree is used when there is a problem of range sum query with update
i.e. RMQ. Suppose you have an array and you have been asked to find sum in
range. It can be done in linear time with static array method. If will be
difficult for one to do it in linear time when you have point updates. In this
update operation is incrementing an index by some value. Brute force approach
will take O(n^2) time but Fenwick Tree will take O(nlogn) time
*/
//Sum function
fun sum(ft:Array<Int>, _index:Int):Int{
/*
Argument
ft : Fenwick Tree
index : Index upto which you want to find prefix sum
Initialize the result "s" then increment the value of
index "index".
Returns : sum of given arr[0..index]. This function assumes
that the array is preprocessed and partial sums of
array elements are stored in ft[].
*/
// Initialize sum variable to 0
var s:Int = 0
// Increment index
var index = _index + 1
while (index > 0){
// Adding tree node to sum
s += ft[index]
// Update tree node
index -= index and (-index)
}
// Return total sum
return s
}
// Update function
fun update(ft:Array<Int>,size:Int,_index:Int,value:Int){
/*
Arguments
ft : Fenwick Tree
index : Index of ft to be updated
size : Length of the original array
val : Add val to the index "index"
Traverse all ancestors and add 'val'.
Add 'val' to current node of Fenwick Tree.
Update index to that of parent in update.
*/
var index = _index + 1
while (index <= size) {
// Update tree node value
ft[index] += value
// Update node index
index += index and (-index)
}
}
// Construct function
fun construct(array:Array<Int>, size:Int):Array<Int>{
/*
Argument
arr : The original array
size : The length of the given array
This function will construct the Fenwick Tree
from the given array of length "size"
Return : Fenwick Tree array ft[]
*/
// Init ft array of length size+1 with zero value initially
var ft = Array(size+1,{0})
// Constructing Fenwick Tree by Update operation
for (i in 0 until size){
// Update operation
update(ft,size,i,array[i])
}
// Return Fenwick Tree array
return ft
}
fun main(){
/*
INPUT
-------
arr : [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]
Print sum of freq[0...5]
Update position 4 by adding 16
Print sum of freq[2....7] after update
Update position 5 by adding 10
Print sum of freq[2....7] after update
OUTPUT
------
12
33
43
*/
// Given array
var list = arrayOf(2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9)
// Build Fenwick Tree
var ft = construct(list,list.size)
// Print Sum of array from index = 0 to index = 5
println(sum(ft,5))
// Increment list[4] by 16
update(ft,list.size,4,16)
// Print sum from index = 2 to index = 7
println(sum(ft,7) - sum(ft,2))
// Increment list[5] by 10
update(ft,list.size,5,10)
// Print sum from index = 2 to index = 7
println(sum(ft,7) - sum(ft,2))
}
| 0 | C++ | 0 | 0 | 65a0570153b7e3393d78352e78fb2111223049f3 | 3,219 | Coding-Journey | MIT License |
src/main/kotlin/aoc2018/day02_inventory_management/InventoryManagement.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2018.day02_inventory_management
import util.hasCharWithExactOccurrences
fun main() {
util.solve(7776, ::partOne)
util.solve("wlkigsqyfecjqqmnxaktdrhbz", ::partTwo)
}
fun partOne(input: String): Int {
val (doubles, triples) = input
.lines()
.fold(Pair(0, 0)) { (doubles, triples), l ->
Pair(
if (l.hasCharWithExactOccurrences(2)) doubles + 1 else doubles,
if (l.hasCharWithExactOccurrences(3)) triples + 1 else triples
)
}
return doubles * triples
}
fun partTwo(input: String): String {
val lines = input.lines()
lines.forEachIndexed { currIdx, src ->
lines.subList(0, currIdx).forEach { tgt ->
var idx = -1
for (i in 0 until tgt.length) {
if (src[i] != tgt[i]) {
if (idx < 0) {
idx = i
} else {
return@forEach // continue
}
}
}
// woo!
return src.substring(0, idx) + src.substring(idx + 1)
}
}
throw IllegalStateException("huh?")
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 1,175 | aoc-2021 | MIT License |
src/main/kotlin/QuadTree.kt | hannomalie | 465,694,597 | false | {"Kotlin": 30338} | fun isInside(position: Vector2, min: Vector2, max: Vector2): Boolean {
return (position.x >= min.x && position.y >= min.y)
&& (position.x <= max.x && position.y <= max.y)
}
data class Vector2(val x: Float, val y: Float)
sealed class QuadTree(val min: Vector2, val max: Vector2) {
abstract fun insert(position: Vector2, entityId: Int)
abstract fun clear()
}
class Node(min: Vector2, max: Vector2, val children: MutableList<QuadTree> = mutableListOf()) :
QuadTree(min, max) {
val leafs: List<Leaf>
get() = children.flatMap {
when (it) {
is Leaf -> listOf(it)
is Node -> it.leafs
}
}
override fun insert(position: Vector2, entityId: Int) {
if (isInside(position, min, max)) {
children.forEach { it.insert(position, entityId) }
}
}
override fun clear() {
children.forEach {
it.clear()
}
}
}
class Leaf(min: Vector2, max: Vector2, val children: MutableList<Int> = mutableListOf()) : QuadTree(min, max) {
override fun insert(position: Vector2, entityId: Int) {
if (isInside(position, min, max)) {
children.add(entityId)
}
}
override fun clear() {
children.clear()
}
}
fun <T> QuadTree(
min: Vector2 = Vector2(0f, 0f),
max: Vector2 = Vector2(dimension.width.toFloat(), dimension.height.toFloat()),
depth: Int = 4
): Node {
var currentDepth = depth
val root = Node(min, max)
var currentNodes: List<QuadTree> = listOf(root)
while (currentDepth > 0) {
currentNodes = currentNodes.flatMap { currentNode ->
when (currentNode) {
is Leaf -> throw IllegalStateException("Can't add to quadtree leaf")
is Node -> {
val halfExtents = Vector2(
currentNode.min.x + 0.5f * (currentNode.max.x - currentNode.min.x),
currentNode.min.y + 0.5f * (currentNode.max.y - currentNode.min.y),
)
val newChildren = if (currentDepth == 1) {
listOf<Leaf>(
Leaf(currentNode.min, halfExtents),
Leaf(halfExtents, currentNode.max),
Leaf(Vector2(halfExtents.x, currentNode.min.y), Vector2(currentNode.max.x, halfExtents.y)),
Leaf(Vector2(currentNode.min.x, halfExtents.y), Vector2(halfExtents.x, currentNode.max.y))
)
} else {
listOf<Node>(
Node(currentNode.min, halfExtents),
Node(halfExtents, currentNode.max),
Node(Vector2(halfExtents.x, currentNode.min.y), Vector2(currentNode.max.x, halfExtents.y)),
Node(Vector2(currentNode.min.x, halfExtents.y), Vector2(halfExtents.x, currentNode.max.y))
)
}
currentNode.children.addAll(
newChildren
)
}
}
currentNode.children
}
currentDepth--
}
return root
}
| 0 | Kotlin | 0 | 0 | 4349e8f881fda9ec29e2c9124d7dc0520f577a03 | 3,273 | artemis-playground | MIT License |
AoC2022/src/main/kotlin/xyz/danielstefani/Day2.kt | OpenSrcerer | 572,873,135 | false | {"Kotlin": 14185} | package xyz.danielstefani
import kotlin.math.abs
val shapeToScore = mapOf(
Pair("A", 1), // Rock
Pair("B", 2), // Paper
Pair("C", 3), // Scissors
Pair("X", 1), // Rock
Pair("Y", 2), // Paper
Pair("Z", 3) // Scissors
)
fun main(args: Array<String>) {
// Prep
val rounds = object {}.javaClass
.classLoader
.getResource("Day2Input.in")
?.readText()
?.split("\n")
?.map {
it.split(", ")[0].split(" ")
.map { letter -> shapeToScore[letter]!! }
}
// Part 1
val scoreFirstAssumption = rounds?.sumOf { extractScoreFromRound(it) }
// Part 2
val scoreSecondAssumption = rounds?.map { convertToShapeToPlay(it) }
?.sumOf { extractScoreFromRound(it) }
println(scoreFirstAssumption)
println(scoreSecondAssumption)
}
fun extractScoreFromRound(elfMyChoices: List<Int>): Int {
val minChoiceDelta = abs(elfMyChoices[0] - elfMyChoices[1]) <= 1
val roundOutcome =
if (elfMyChoices[0] > elfMyChoices[1] && minChoiceDelta) 0
else if (elfMyChoices[0] < elfMyChoices[1] && !minChoiceDelta) 0
else if (elfMyChoices[0] == elfMyChoices[1]) 3
else 6
return elfMyChoices[1] + roundOutcome
}
fun convertToShapeToPlay(elfEndChoices: List<Int>): List<Int> {
return when (elfEndChoices[1]) {
1 -> listOf(
elfEndChoices[0],
if (elfEndChoices[0] == 1) 3 else elfEndChoices[0] - 1
)
2 -> listOf(elfEndChoices[0], elfEndChoices[0])
3 -> listOf(
elfEndChoices[0],
if (elfEndChoices[0] == 3) 1 else elfEndChoices[0] + 1
)
else -> emptyList() // won't happen
}
} | 0 | Kotlin | 0 | 3 | 84b9b62e15c70a4a17f8b2379dc29f9daa9f4be3 | 1,719 | aoc-2022 | The Unlicense |
advent-of-code-2021/src/main/kotlin/Day12.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 12: Passage Pathing
//https://adventofcode.com/2021/day/12
import java.io.File
private const val START = "start"
val connections = mutableMapOf<String, MutableList<String>>()
fun main() {
File("src/main/resources/Day12.txt").readLines().sorted().map { connection ->
val (cave1, cave2) = connection.split("-")
connections[cave1] = connections.getOrDefault(cave1, mutableListOf()).also { it.add(cave2) }
connections[cave2] = connections.getOrDefault(cave2, mutableListOf()).also { it.add(cave1) }
}
val paths = mutableSetOf<List<String>>()
findPaths(listOf(START), paths) { currentPath, cave -> isCaveBig(cave) || cave !in currentPath }
println(paths.size)
paths.clear()
findPaths(listOf(START), paths) { currentPath, cave ->
isCaveBig(cave) || (cave !in currentPath)
|| (cave != START &&
currentPath.filter { isCaveBig(it).not() }.groupingBy { it }.eachCount().containsValue(2).not())
}
println(paths.size)
}
fun findPaths(currentPath: List<String>, paths: MutableSet<List<String>>, check: (List<String>, String) -> Boolean) {
if (currentPath.last() == "end") {
paths.add(currentPath)
return
}
connections[currentPath.last()]?.filter { check(currentPath, it) }?.forEach { cave ->
findPaths(currentPath + cave, paths, check)
}
}
fun isCaveBig(cave: String) = cave.first().isUpperCase()
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 1,439 | advent-of-code | Apache License 2.0 |
src/Day01.kt | mcrispim | 573,449,109 | false | {"Kotlin": 46488} | fun main() {
var elvesCalories: List<Int>
fun calculateElvesCalories(input: List<String>): List<Int> {
val calories = mutableListOf<Int>()
var item = 0
var sum = 0
while(item < input.size) {
if (input[item] == "") {
calories.add(sum)
sum = 0
} else {
sum += input[item].toInt()
}
item++
}
calories.add(sum)
return calories
}
fun part1(input: List<String>): Int {
elvesCalories = calculateElvesCalories(input)
return elvesCalories.max()
}
fun part2(input: List<String>): Int {
elvesCalories = calculateElvesCalories(input)
return elvesCalories.sorted().reversed().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5fcacc6316e1576a172a46ba5fc9f70bcb41f532 | 1,076 | AoC2022 | Apache License 2.0 |
src/main/kotlin/NQueens.kt | embuc | 735,933,359 | false | {"Kotlin": 110920, "Java": 60263} | package se.embuc
fun placeQueens(boardSize: Int): List<List<String>> {
val results = mutableListOf<List<String>>()
val board = Array(boardSize) { CharArray(boardSize) { '.' } }
solveNQueens(board, 0, results)
return results
}
fun solveNQueens(board: Array<CharArray>, row: Int, results: MutableList<List<String>>) {
if (row == board.size) {
results.add(board.map { it.joinToString("") })
return
}
for (col in board.indices) {
if (isValid(board, row, col)) {
board[row][col] = 'Q' // Place the queen
solveNQueens(board, row + 1, results)
board[row][col] = '.' // Backtrack
}
}
}
fun isValid(board: Array<CharArray>, row: Int, col: Int): Boolean {
for (i in 0 until row) {
if (board[i][col] == 'Q') return false
}
var (r, c) = row to col
while (r >= 0 && c >= 0) {
if (board[r][c] == 'Q') return false
r--; c--
}
r = row; c = col
while (r >= 0 && c < board.size) {
if (board[r][c] == 'Q') return false
r--; c++
}
return true
}
fun main() {
val solutions = placeQueens(4)
solutions.forEach { solution ->
solution.forEach { println(it) }
println()
}
}
| 0 | Kotlin | 0 | 1 | 79c87068303f862037d27c1b33ea037ab43e500c | 1,104 | projecteuler | MIT License |
src/Day25.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | import kotlin.math.max
import kotlin.math.pow
class Day25 {
private val powerCountsMap = mutableMapOf<Int, Int>()
// fun part1_(input: List<String>): Long {
//
// while (currentCount !=) {
// if (currentCount % 10000000L == 0L) println(currentCount)
// var indexToIncrement: Int? = null
// for (i in currentSnafu.size - 1 downTo 0) {
// val c = currentSnafu[i]
// if (getValue(c) < 2) {
// indexToIncrement = i
// break
// }
// }
// if (indexToIncrement != null) {
// currentSnafu[indexToIncrement] = increment(currentSnafu[indexToIncrement])
// for (i in indexToIncrement + 1 until currentSnafu.size) currentSnafu[i] = '='
// } else {
// currentSnafu.add(0, '1')
// for (i in 1 until currentSnafu.size) currentSnafu[i] = '='
// }
// currentCount++
// }
// println(currentSnafu)
// println(currentCount)
//
//// var guess: Long = 0
//// while (guess != sum) {
//// var currentString = ""
//// for (i in 0..20) {
//// currentString +=
//// }
//// }
// return sum
// }
private fun add(a: CharArray, b: CharArray): CharArray {
val sum = mutableListOf<Char>()
var remainder = 0
val mappedA = a.map { if (it == '=') -2 else if (it == '-') -1 else it.digitToInt() }
val mappedB = b.map { if (it == '=') -2 else if (it == '-') -1 else it.digitToInt() }
var aIndex = mappedA.size - 1
var bIndex = mappedB.size - 1
while (aIndex >= 0 || bIndex >= 0 || remainder > 0) {
val val1 = if (aIndex >= 0) mappedA[aIndex] else 0
val val2 = if (bIndex >= 0) mappedB[bIndex] else 0
val tempS = val1 + val2 + remainder
var s: Int
when (tempS) {
3 -> {
s = -2
remainder = 1
}
4 -> {
s = -1
remainder = 1
}
5 -> {
s = 0
remainder = 1
}
-3 -> {
s = 2
remainder = -1
}
-4 -> {
s = 1
remainder = -1
}
-5 -> {
s = 0
remainder = -1
}
else -> {
s = tempS
remainder = 0
}
}
sum.add(0, if (s == -1) '-' else if (s == -2) '=' else s.toString()[0])
aIndex--
bIndex--
}
return sum.toCharArray()
}
fun part1(input: List<String>) {
var sum = "0".toCharArray()
var sumLong = 0L
for (line in input) {
val currentValue = decode(line)
println(currentValue)
sumLong += currentValue
sum = add(sum, line.toCharArray())
println(sum)
}
println("Final")
println(sum)
println(decode(sum.joinToString("")))
println(sumLong)
}
private fun decode(line: String): Long {
var currentValue = 0L
var power = 0
for (c in line.length - 1 downTo 0) {
val n = 5.0.pow(power)
if (!powerCountsMap.containsKey(power)) {
powerCountsMap[power] = 0
}
when (line[c]) {
'=' -> {
currentValue -= (n.toLong() * 2)
powerCountsMap[power] = powerCountsMap[power]!! - 2
}
'-' -> {
currentValue -= n.toLong()
powerCountsMap[power] = powerCountsMap[power]!! - 1
}
else -> {
val count = line[c].digitToInt()
currentValue += (n.toLong() * count)
powerCountsMap[power] = powerCountsMap[power]!! + count
}
}
power++
}
return currentValue
}
fun increment(c: Char): Char {
return when (c) {
'=' -> '-'
'-' -> '0'
'0' -> '1'
'1' -> '2'
else -> throw RuntimeException()
}
}
fun getValue(c: Char): Int {
return when (c) {
'=' -> -2
'-' -> -1
else -> c.digitToInt()
}
}
}
fun main() {
val input = readInput("input25_1")
println(Day25().part1(input))
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 4,771 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day17.kt | SimonMarquis | 570,868,366 | false | {"Kotlin": 50263} | import java.lang.System.lineSeparator
class Day17(private val input: String, rocks: String) {
fun part1(target: Long = 2022L) = Simulation(input.toList(), rocks).apply {
while (totalRocks != target) simulate()
}.top().inc()
fun part2(target: Long = 1_000_000_000_000L): Long = Simulation(input.toList(), rocks).apply {
while (totalRocks != target) simulate()
}.top().inc()
private val rocks = rocks.split(lineSeparator() * 2).map { rock ->
rock.lines().asReversed().flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, it -> if (it == '#') Point(x.toLong(), y.toLong()) else null }
}.toSet().let(::Rock)
}
private data class Rock(val pieces: Set<Point>) : Set<Point> by pieces
private data class Point(val x: Long, val y: Long)
private class Simulation(moves: List<Char>, rocks: List<Rock>, private val width: Int = 7) {
private val moves = moves.asSequence().repeat().iterator()
private val rocks = rocks.asSequence().repeat().iterator()
private val data = mutableSetOf<Point>()
var totalRocks = 0L
private set
fun top(): Long = data.maxOfOrNull { it.y } ?: -1L
private fun Rock.spawn() = offset(dx = 2L, dy = top().inc() + 3L)
private fun Rock.offset(dx: Long = 0, dy: Long = 0) = copy(
pieces = pieces.mapTo(mutableSetOf()) { Point(it.x + dx, it.y + dy) }
)
private fun Rock.pushed(c: Char): Rock = when (c) {
'<' -> offset(dx = -1)
'>' -> offset(dx = +1)
'v' -> offset(dy = -1)
else -> error(c)
}.let { new ->
if (new.minOf { it.x } < 0) return this
if (new.maxOf { it.x } >= width) return this
if (new.minOf { it.y < 0 }) return this
if ((new intersect data).minus(this).isNotEmpty()) return this
return new
}
private infix fun Rock.becomes(new: Rock): Rock = new.apply {
data.removeAll(this@becomes)
data.addAll(new)
}
fun simulate() {
var rock = rocks.next().spawn()
totalRocks++
while (true) {
rock.pushed(moves.next()).also { if (it != rock) rock = rock becomes it }
rock.pushed('v').also { if (it != rock) rock = rock becomes it else return }
}
}
override fun toString(): String {
val minY = data.minOfOrNull { it.y } ?: 0
val maxY = data.maxOfOrNull { it.y } ?: 0
val minX = 0L
val maxX = 6L
return (maxY downTo minY).joinToString("\n") { y ->
(minX..maxX).joinToString("") { x ->
if (Point(x, y) in data) "#" else "."
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | a2129cc558c610dfe338594d9f05df6501dff5e6 | 2,838 | advent-of-code-2022 | Apache License 2.0 |
src/Day20.kt | timhillgit | 572,354,733 | false | {"Kotlin": 69577} | fun elfMix(numbers: MutableList<Long>, rounds: Int) {
val positions = MutableList(numbers.size) { it }
repeat(rounds) {
for (originalIndex in numbers.indices) {
val index = positions.indexOf(originalIndex)
positions.removeAt(index)
val value = numbers.removeAt(index)
val newIndex = (index + value).mod(numbers.size)
numbers.add(newIndex, value)
positions.add(newIndex, originalIndex)
}
}
}
private fun List<Long>.groveSum(): Long {
val zeroIndex = indexOf(0)
val groveIndices = listOf(1000, 2000, 3000).map { (it + zeroIndex) % size }
return slice(groveIndices).sum()
}
fun main() {
var numbers = readInput("Day20").map(String::toLong).toMutableList()
elfMix(numbers, 1)
println(numbers.groveSum())
numbers = readInput("Day20")
.map(String::toLong)
.map { it * 811589153 }
.toMutableList()
elfMix(numbers, 10)
println(numbers.groveSum())
}
| 0 | Kotlin | 0 | 1 | 76c6e8dc7b206fb8bc07d8b85ff18606f5232039 | 1,005 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | Lonexera | 573,177,106 | false | null | fun main() {
fun String.splitInHalf(): Pair<String, String> {
return windowed(
size = length / 2,
step = length / 2
)
.zipWithNext()
.first()
}
fun Char.toElfErrorCode(): Int {
val alphabetString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
return alphabetString.indexOf(this) + 1
}
fun part1(input: List<String>): Int {
return input
.sumOf { ruckpack ->
val (first, second) = ruckpack.splitInHalf()
val errorChar = first.find { second.contains(it) }
errorChar?.toElfErrorCode() ?: 0
}
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.sumOf { group ->
val badgeType = group
.first()
.find { item ->
group.all { it.contains(item) }
}
badgeType?.toElfErrorCode() ?: 0
}
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c06d394cd98818ec66ba9c0311c815f620fafccb | 1,238 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/kotlin/_2022/Task08.kt | MuhammadSaadSiddique | 567,431,330 | false | {"Kotlin": 20410} | package _2022
import Task
import readInput
import utils.Matrix.adjacentRowsAndCols
import java.lang.Integer.max
typealias Grid = List<List<Int>>
object Task08 : Task {
override fun partA(): Int = traverseFold(parseInput()) { totalVisibleTrees, neighbours, treeHeight ->
neighbours
.map { neighbour -> neighbour.isEmpty() || treeHeight > neighbour.max() }
.count { isVisible -> isVisible }
.coerceAtMost(1)
.let { currentVisibleTrees -> totalVisibleTrees + currentVisibleTrees }
}
override fun partB() = traverseFold(parseInput()) { maxScore, neighbours, treeHeight ->
neighbours
.map { neighbour -> neighbour.takeWhileInclusive { treeHeight > it }.count() }
.reduce { scenicScore, viewingDistance -> scenicScore * viewingDistance }
.let { currencyScore -> max(maxScore, currencyScore) }
}
private fun parseInput() = readInput("_2022/08")
.split('\n')
.map { it.map { it.digitToInt() } }
private fun traverseFold(grid: Grid, operation: (Int, Grid, Int) -> Int): Int = grid
.mapIndexed { i, row -> row.mapIndexed { j, treeHeight -> (i to j) to treeHeight } }
.flatten()
.fold(0) { total, (position, treeHeight) ->
val (i, j) = position
val neighbours = adjacentRowsAndCols(grid, i, j)
operation(total, neighbours, treeHeight)
}
private fun <T> List<T>.takeWhileInclusive(predicate: (T) -> Boolean) = sequence {
this@takeWhileInclusive.takeWhile { predicate(it) }.forEach { yield(it) }
this@takeWhileInclusive.firstOrNull { !predicate(it) }?.let { yield(it) }
}
} | 0 | Kotlin | 0 | 0 | 3893ae1ac096c56e224e798d08d7fee60e299a84 | 1,701 | AdventCode-Kotlin | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2021/day24/ModelNumberAutomaticDetector.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day24
import com.github.michaelbull.advent2021.day24.Instruction.Literal.Div
import com.github.michaelbull.advent2021.day24.VariableName.W
import com.github.michaelbull.advent2021.day24.VariableName.Z
import kotlin.math.max
import kotlin.math.pow
class ModelNumberAutomaticDetector(
instructions: List<Instruction>
) {
private val divLiteralMin = instructions
.filterIsInstance<Div>()
.minOf(Instruction.Literal::operand)
private val divLiteralMax = instructions
.filterIsInstance<Div>()
.maxOf(Instruction.Literal::operand)
private val divLiteralRange = divLiteralMin..divLiteralMax
private val chunks = instructions.chunked(CHUNK_SIZE)
private val zStackHeight = maxStackHeight(Z, instructions)
private val maxZ = divLiteralRange.count()
.toDouble()
.pow(zStackHeight)
.toInt()
fun largest(): Long? {
return detect(LARGEST_TO_SMALLEST)
}
fun smallest(): Long? {
return detect(SMALLEST_TO_LARGEST)
}
private fun detect(
digits: IntProgression,
visited: MutableSet<DetectNode> = mutableSetOf(),
current: DetectNode = DetectNode.START,
acc: Long = 0
): Long? {
if (current in visited || current.z > maxZ) {
return null
}
visited += current
val chunk = chunks[current.chunkIndex]
val nextChunkIndex = current.chunkIndex + 1
val chunksRemaining = nextChunkIndex < chunks.size
for (digit in digits) {
val alu = ArithmeticLogicUnit()
alu[Z] = current.z
alu.onInput {
if (it == W) {
digit.toLong()
} else {
throw IllegalArgumentException("no input for variable: $it")
}
}
alu.execute(chunk)
if (chunksRemaining) {
val nextNode = DetectNode(nextChunkIndex, alu[Z])
val next = detect(digits, visited, nextNode, (acc * 10) + digit)
if (next != null) {
return next
}
} else if (alu.isValid()) {
return (acc * 10) + digit
}
}
return null
}
private fun maxStackHeight(variable: VariableName, instructions: List<Instruction>): Int {
val (_, max) = instructions.fold(0 to 0) { (current, max), instruction ->
val delta = when {
instruction.isPush(variable) -> +1
instruction.isPop(variable) -> -1
else -> 0
}
val next = current + delta
next to max(next, max)
}
return max
}
private fun Instruction.isPush(variable: VariableName): Boolean {
return this is Div && this.variable == variable && operand == divLiteralMin
}
private fun Instruction.isPop(variable: VariableName): Boolean {
return this is Div && this.variable == variable && operand == divLiteralMax
}
private data class DetectNode(
val chunkIndex: Int,
val z: Long
) {
companion object {
val START = DetectNode(0, 0)
}
}
private companion object {
private const val CHUNK_SIZE = 18
private val LARGEST_TO_SMALLEST = 9 downTo 1
private val SMALLEST_TO_LARGEST = 1..9
}
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 3,459 | advent-2021 | ISC License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.