path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/org/example/e3fxgaming/adventOfCode/aoc2023/day01/Day01.kt
E3FxGaming
726,041,587
false
{"Kotlin": 38290}
package org.example.e3fxgaming.adventOfCode.aoc2023.day01 import org.example.e3fxgaming.adventOfCode.utility.Day import org.example.e3fxgaming.adventOfCode.utility.IndividualLineInputParser import org.example.e3fxgaming.adventOfCode.utility.InputParser import org.example.e3fxgaming.adventOfCode.utility.StringAndIntTrieConstruct import org.example.e3fxgaming.adventOfCode.utility.TrieConstruct class Day01(inputLines: String) : Day<Int, Int> { companion object { val digitTrie = StringAndIntTrieConstruct().apply { listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") .forEachIndexed { index, s -> append(s, index + 1) } } } override val partOneParser: InputParser<Int> = object : IndividualLineInputParser<Int>(inputLines) { override fun parseLine(line: String): Int { var firstDigitChar: Char? = null var lastDigitChar: Char? = null line.forEach { if (it.isDigit()) { if (firstDigitChar == null) { firstDigitChar = it lastDigitChar = it } else { lastDigitChar = it } } } return "${checkNotNull(firstDigitChar)}${checkNotNull(lastDigitChar)}".toInt() } } override val partTwoParser: InputParser<Int> = object : IndividualLineInputParser<Int>(inputLines) { override fun parseLine(line: String): Int { var firstDigit: Int? = null var lastDigit: Int? = null fun foundDigit(currDigit: Int) { if (firstDigit == null) { firstDigit = currDigit } lastDigit = currDigit } var currentTrieNodes: List<TrieConstruct.Node<Char, Int>> = emptyList() line.forEach { if (it.isDigit()) foundDigit(it.digitToInt()) currentTrieNodes = buildList { digitTrie.root.children[it]?.let(::add) currentTrieNodes.mapNotNull { currentTrieNode -> currentTrieNode.children[it] }.let(::addAll) }.onEach { newTrieNode -> newTrieNode.tag?.let(::foundDigit) } } return "$firstDigit$lastDigit".toInt() } } override fun solveFirst(given: List<Int>): String = given.sum().toString() override fun solveSecond(given: List<Int>): String = solveFirst(given) } fun main() = Day01( Day01::class.java.getResource("/2023/day01/realInput1.txt")!!.readText() ).runBoth()
0
Kotlin
0
0
3ae9e8b60788733d8bc3f6446d7a9ae4b3dabbc0
2,729
adventOfCode
MIT License
src/main/kotlin/symbolik/expressions/extensions.kt
Andlon
55,359,009
false
null
package symbolik.expressions import symbolik.parser.Token import symbolik.util.isDivisible import symbolik.util.reduceOrNull import symbolik.util.repeat import kotlin.comparisons.compareBy import kotlin.comparisons.thenByDescending operator fun Expression.plus(other: Expression): Expression = sum(this, other) operator fun Expression.times(other: Expression) = product(this, other) fun product(vararg terms: Expression) = product(terms.asIterable()) fun product(terms: Iterable<Expression>): Expression = terms .filterNot { it is EmptyExpression } .let { when (it.size) { 0 -> EmptyExpression 1 -> it.single() else -> Product(it).flatten() }} fun sum(vararg terms: Expression) = sum(terms.asIterable()) fun sum(terms: Iterable<Expression>): Expression = terms .filterNot { it is EmptyExpression } .let { when (it.size) { 0 -> EmptyExpression 1 -> it.single() else -> Sum(it).flatten() }} fun negate(expr: Expression) = when(expr) { is EmptyExpression -> EmptyExpression is Negation -> expr.expression else -> Negation(expr) } fun Expression.reorderForPresentation(): Expression { return when { this is Sum -> terms .map { it.reorderForPresentation() } .sortedWith( // Push negative terms to the end compareBy<Expression> { when { it is Constant && it.decimalValue().value < 0 -> 1 it is Negation -> 1 else -> 0 } }.thenByDescending { it.complexity() } ) .let { sum(it) } this is Product -> terms .map { it.reorderForPresentation() } .sortedBy { it.complexity() } .let { product(it) } else -> this } } fun Expression.text(): String = when(this) { is Integer -> this.value.toString() is Decimal -> this.value.toString() is Variable -> this.value is Negation -> "-${this.expression.text()}" is Parentheses -> "(${this.expr.text()})" is Sum -> terms .map { applyParenthesesIfNecessary(this, it ) } .fold("", { accumulated, term -> accumulated + when { accumulated.isEmpty() -> term.text() term is Negation -> " - ${term.expression.text()}" term is Integer && term.value < 0 -> " - " + Integer(-1 * term.value).text() else -> " + " + term.text() } }) is Product -> terms .map { applyParenthesesIfNecessary(this, it ) } .map(Expression::text) .reduce { a, b -> "$a * $b" } is Division -> listOf(left, right) .map { applyParenthesesIfNecessary(this, it ) } .map(Expression::text) .reduce { a, b -> "$a / $b" } else -> "" } fun Sum.flatten(): Sum = Sum(terms.flatMap { if (it is Sum) it.terms else listOf(it) }) fun Product.flatten(): Product = Product(terms.flatMap { if (it is Product) it.terms else listOf(it) }) fun Expression.expand(): Expression = when(this) { is Product -> this.terms.fold(EmptyExpression as Expression, { acc, term -> when { acc is EmptyExpression -> term term is Sum -> Sum(term.terms.map { Product(acc, it).expand() }).flatten() acc is Sum -> Sum(acc.terms.map { Product(it, term).expand() }).flatten() else -> Product(acc, term).flatten() } }) is Sum -> sum(this.terms.map { it.expand() }) is Negation -> product(Integer(-1), this.expression).expand() else -> this } fun List<Integer>.sum(): Integer? = reduceOrNull { a, b -> Integer(a.value + b.value) } fun List<Integer>.product(): Integer? = reduceOrNull { a, b -> Integer(a.value * b.value) } fun List<Decimal>.sum(): Decimal? = reduceOrNull { a, b -> Decimal(a.value + b.value) } fun List<Decimal>.product(): Decimal? = reduceOrNull { a, b -> Decimal(a.value * b.value) } fun Expression.combineTerms(): Expression = when(this) { is Product -> { val combinedTerms = terms.map { it.combineTerms() } val (constants, remainingTerms) = combinedTerms.partition { it is Constant } val integerFactor = constants.filterIsInstance<Integer>().product() val decimalFactor = constants.filterIsInstance<Decimal>().product() val remaining = product(remainingTerms) when { integerFactor?.value == 0 -> Integer(0) integerFactor?.value == 1 -> product(decimalFactor ?: EmptyExpression, remaining).combineTerms() integerFactor == null -> product(decimalFactor ?: EmptyExpression, remaining) integerFactor.value < 0 && decimalFactor == null && remaining != EmptyExpression -> negate(product(Integer(-1 * integerFactor.value), remaining).combineTerms()) decimalFactor == null -> product(integerFactor, remaining) else -> product(Decimal(integerFactor.value * decimalFactor.value), remaining) } } is Sum -> { val combinedTerms = terms.map { it.combineTerms() } val (constants, remainingTerms) = combinedTerms.partition { it is Constant } val integerSum = constants.filterIsInstance<Integer>().sum() val decimalSum = constants.filterIsInstance<Decimal>().sum() val remaining = sum(remainingTerms) when { integerSum?.value == 0 && remaining != EmptyExpression -> sum(decimalSum ?: EmptyExpression, remaining).combineTerms() decimalSum?.value == 0.0 -> sum(integerSum ?: EmptyExpression, remaining).combineTerms() decimalSum == null -> sum(integerSum ?: EmptyExpression, remaining) integerSum == null -> sum(decimalSum, remaining) else -> sum(Decimal(integerSum.value + decimalSum.value), remaining) } } is Negation -> { val combined = expression.combineTerms() if (combined is Constant) { product(Integer(-1), combined).combineTerms() } else { Negation(combined) } } else -> this } fun Expression.simplify(): Expression = when(this) { is Negation -> negate(expression.simplify()) is Sum -> this.flatten() .let { val collected = it.collect() val expandedAndCollected = it.expand().collect() if(collected.complexity() < expandedAndCollected.complexity()) { collected } else { expandedAndCollected } } .combineTerms() is Product -> this.flatten() .let { val collected = it.collect() val expandedAndCollected = it.expand().collect() if(collected.complexity() < expandedAndCollected.complexity()) { collected } else { expandedAndCollected } } .combineTerms() is Division -> when { left is Integer && right is Integer && right != Integer(0) && isDivisible(left.value, right.value) -> Integer(left.value / right.value) left is Decimal && right is Decimal && right != Decimal(0.0) -> Decimal(left.value / right.value) left is Decimal && right is Integer && right != Integer(0) -> Decimal(left.value / right.value) left is Integer && right is Decimal && right != Decimal(0.0) -> Decimal(left.value / right.value) else -> { val simplified = Division(left.simplify(), right.simplify()) if (simplified != this) simplified.simplify() else simplified } } else -> this }.reorderForPresentation() fun Expression.complexity(): Int = when(this) { is Constant -> 1 is Variable -> 2 is Negation -> 1 + this.expression.complexity() is Sum -> this.terms.fold(0, { acc, term -> acc + term.complexity() }) + 2 * (this.terms.size - 1) is Product -> this.terms.fold(0, { acc, term -> acc + term.complexity() }) + 1 * (this.terms.size - 1) else -> throw NotImplementedError("Complexity of expression cannot be determined") } private fun applyParenthesesIfNecessary(parentOperator: Operator, expr: Expression): Expression = when { expr is Operator && expr.token().precedence() < parentOperator.token().precedence() -> Parentheses(expr) expr is Negation && expr.expression is Operator && expr.expression.token().precedence() <= parentOperator.token().precedence() -> Negation(Parentheses(expr.expression)) else -> expr } fun applyUnaryOperator(token: Token.UnaryOperator, operand: Expression) = when(token) { is Token.UnaryOperator.Plus -> operand is Token.UnaryOperator.Minus -> when(operand) { is Integer -> Integer(-1 * operand.value) is Decimal -> Decimal(-1 * operand.value) else -> Negation(operand) } } fun Expression.collect(): Expression = when(this) { is Sum -> factors() // Note: Instead of calling collect on the remainder, we should be able to compute // the same result on the remainder by using the provided factors. However, // it should yield the same result, so for now we take the easy route. .map { val multipliedOut = product(it.factor.collect(), it.operand.collect()) val remainder = it.remainder.collect() sum(multipliedOut, remainder).combineTerms() } .minBy { it.complexity() } ?: this is Product -> product(terms.map { it.collect() }) is Negation -> product(Integer(-1), this.expression).collect() else -> this } data class FactorizedExpression(val factor: Expression, val operand: Expression, val remainder: Expression = EmptyExpression) { //val expression by lazy { sum(product(factor, operand), remainder) } } private fun extractFactors(expr: Expression): List<Expression> = when (expr) { is Product -> expr.terms is Negation -> extractFactors(expr.expression) else -> listOf(expr) } /** * Computes the minimum multiplicity of the factor in the list of expressions. * * Given a sum * a_1 + a_2 + ... + a_n, * where * a_i = b_1 * b_2 * ... * b_m(i), * where m(i) is the number of factors in a_i, and * g(i) = #{ b_j == factor for j = 1, ..., m(i) }, * then this function returns * multiplicity = min g(i) for i = [1, n] */ private fun multiplicity(factor: Expression, terms: List<Expression>): Int = terms.map { when (it) { factor -> 1 is Product -> it.terms.count { it == factor } else -> 0 } }.min() ?: 0 private fun Expression.removeFactors(factors: List<Expression>): Expression { var remainingFactors = factors.toMutableList() return when { this is Product -> terms.filterNot { remainingFactors.remove(it) } .let { if (it.isEmpty()) { Integer(1) } else { product(it) } } this is Negation -> Negation(expression.removeFactors(factors)) factors.singleOrNull() == this -> Integer(1) else -> this } } fun Sum.factors(): List<FactorizedExpression> { val expr = this val factors = expr.terms .flatMap { extractFactors(it) } // Ignore constant terms, as they are not interesting to extract as factors .filterNot { it is Constant } .distinct() data class IntermediateTermCollection(val factoredTerms: MutableList<Expression>, val remainderTerms: MutableList<Expression>) val factorTable = factors.associate { it to IntermediateTermCollection(mutableListOf(), mutableListOf()) } for (factor in factors) { val intermediateCollection = factorTable[factor]!! for (term in expr.terms) { when { term == factor -> intermediateCollection.factoredTerms.add(Integer(1)) term is Product && term.terms.contains(factor) -> intermediateCollection.factoredTerms.add(Product(term.terms - factor).flatten()) term is Product -> intermediateCollection.remainderTerms.add(term) // TODO: Rewrite this block as a function and call it recursively for Negation term is Negation && term.expression == factor -> intermediateCollection.factoredTerms.add(Negation(Integer(1))) term is Negation && term.expression is Product && term.expression.terms.contains(factor) -> intermediateCollection.factoredTerms.add(Negation(product(term.expression.terms - factor))) term is Negation && term.expression is Product -> intermediateCollection.remainderTerms.add(Negation(term.expression)) else -> intermediateCollection.remainderTerms.add(term) } } } return factorTable .mapKeys { // Multiply the factor the maximum number of times, N, such that // it appears N times in each factored term. Note that in each factoredTerm it // only appears N - 1 times, as we've already factored out one val multiplicity = multiplicity(it.key, it.value.factoredTerms) repeat(multiplicity + 1, it.key) } .mapValues { val repeatedFactor = it.key // Adjust the factoredTerms accordingly, by removing the factor (N - 1) times val factoredTerms = it.value.factoredTerms.map { it.removeFactors(repeatedFactor.drop(1)) } IntermediateTermCollection(factoredTerms.toMutableList(), it.value.remainderTerms) }.mapKeys { product(it.key) } .asIterable() .groupBy { it.value.remainderTerms } .map { val remainder = sum(it.key) val individualFactors = it.value.map { it.key } val compositeFactor = product(individualFactors) val refactoredTerms = it.value.map { val factor = it.key it.value.factoredTerms.map { it.removeFactors(individualFactors - factor) } }.firstOrNull() ?: listOf(EmptyExpression) val operand = sum(refactoredTerms) FactorizedExpression(compositeFactor, operand, remainder) } }
0
Kotlin
0
0
9711157eda9a56ba622475bf994cef8ff9d16946
14,667
symbolik
MIT License
src/main/java/challenges/educative_grokking_coding_interview/merge_intervals/_4/EmployeeFreeTime.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.merge_intervals._4 import challenges.educative_grokking_coding_interview.merge_intervals.Interval import java.util.* object EmployeeFreeTime { private fun employeeFreeTime(schedule: ArrayList<ArrayList<Interval>>): List<Interval> { val heap = PriorityQueue { a: IntArray, b: IntArray -> a[0] - b[0] } // Iterate for all employees' schedules // and add start of each schedule's first interval along with // its index value and a value 0. for (i in schedule.indices) { val employeeSchedule: List<Interval> = schedule[i] val interval: Interval = employeeSchedule[0] heap.offer(intArrayOf(interval.start, i, 0)) } // Take an empty list to store results. val result: MutableList<Interval> = ArrayList<Interval>() // Set 'previous' to the start time of the first interval in heap. var previous: Int = schedule[heap.peek()[1]][heap.peek()[2]].start // Iterate until the heap is empty while (!heap.isEmpty()) { // Poll an element from the heap and get values of i and j val tuple = heap.poll() val i = tuple[1] val j = tuple[2] // Select an interval val interval: Interval = schedule[i][j] // If the selected interval's start value is greater than the previous value, // it means that this interval is free. So, add this interval // (previous, interval's end value) into the result. if (interval.start > previous) { result.add(Interval(previous, interval.start)) } // Update the previous as the maximum of previous and interval's end value. previous = Math.max(previous, interval.end) // If there is another interval in the current employee's schedule, // push that into the heap. if (j + 1 < schedule[i].size) { val nextInterval: Interval = schedule[i][j + 1] heap.offer(intArrayOf(nextInterval.start, i, j + 1)) } } // When the heap is empty, return the result. return result } // Function for displaying interval list fun display(l1: List<Interval>): String { if (l1.isEmpty()) { return "[]" } var resultStr = "[" for (i in 0 until l1.size - 1) { resultStr += "[" + l1[i].start.toString() + ", " resultStr += "${l1[i].end}], " } resultStr += "[" + l1[l1.size - 1].start.toString() + ", " resultStr += "${l1[l1.size - 1].end}]" resultStr += "]" return resultStr } @JvmStatic fun main(args: Array<String>) { val inputs1: List<List<List<Interval>>> = listOf( listOf( listOf(Interval(1, 2), Interval(5, 6)), listOf(Interval(1, 3)), listOf(Interval(4, 10)) ), listOf( listOf(Interval(1, 3), Interval(6, 7)), listOf(Interval(2, 4)), listOf(Interval(2, 5), Interval(9, 12)) ), listOf( listOf(Interval(2, 3), Interval(7, 9)), listOf(Interval(1, 4), Interval(6, 7)) ), listOf( listOf(Interval(3, 5), Interval(8, 10)), listOf(Interval(4, 6), Interval(9, 12)), listOf(Interval(5, 6), Interval(8, 10)) ), listOf( listOf(Interval(1, 3), Interval(6, 9), Interval(10, 11)), listOf(Interval(3, 4), Interval(7, 12)), listOf(Interval(1, 3), Interval(7, 10)), listOf(Interval(1, 4)), listOf(Interval(7, 10), Interval(11, 12)) ), listOf( listOf(Interval(1, 2), Interval(3, 4), Interval(5, 6), Interval(7, 8)), listOf(Interval(2, 3), Interval(4, 5), Interval(6, 8)) ), Arrays.asList( listOf( Interval(1, 2), Interval(3, 4), Interval(5, 6), Interval(7, 8), Interval(9, 10), Interval(11, 12) ), listOf( Interval(1, 2), Interval(3, 4), Interval(5, 6), Interval(7, 8), Interval(9, 10), Interval(11, 12) ), listOf( Interval(1, 2), Interval(3, 4), Interval(5, 6), Interval(7, 8), Interval(9, 10), Interval(11, 12) ), listOf( Interval(1, 2), Interval(3, 4), Interval(5, 6), Interval(7, 8), Interval(9, 10), Interval(11, 12) ) ) ) var i = 1 val inputs: ArrayList<ArrayList<ArrayList<Interval>>> = ArrayList<ArrayList<ArrayList<Interval>>>() for (j in inputs1.indices) { inputs.add(ArrayList<ArrayList<Interval>>()) for (k in inputs1[j].indices) { inputs[j].add(ArrayList<Interval>()) for (g in inputs1[j][k].indices) { inputs[j][k].add(inputs1[j][k][g]) } } } for (j in inputs.indices) { println("$i.\tEmployee Schedules:") for (s in inputs[j].indices) { println("\t\t" + display(inputs[j][s])) } println( "\tEmployees' free time " + display( employeeFreeTime( inputs[j] ) ) ) println(String(CharArray(100)).replace('\u0000', '-')) i += 1 } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
6,189
CodingChallenges
Apache License 2.0
src/Day05_part2.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { fun part2(input: List<String>): String { fun convertInput(input: List<String>): MutableList<MutableList<Char>> { val containers = mutableListOf<MutableList<Char>>() for (i in 0 until input.last().length / 4 + 1) { containers.add(mutableListOf()) } for (i in input.indices.reversed()) { if (i == input.size - 1) continue for (j in containers.indices) { val container = 1 + j * 4 if (container >= input[i].length) break val name = input[i][container] if (name != ' ') { containers[j].add(name) } } } return containers } val emptyLine = input.indexOf("") val containers = convertInput(input.subList(0, emptyLine)) val inputLineRegex = """move (\d+) from (\d+) to (\d+)""".toRegex() for (it in input.subList(emptyLine + 1, input.size)) { val (s1, s2, s3) = inputLineRegex .matchEntire(it) ?.destructured ?: throw IllegalArgumentException("Incorrect input line $it") val number = s1.toInt() val from = s2.toInt() - 1 val to = s3.toInt() - 1 val fromContainer = containers[from].takeLast(number) containers[from] = containers[from].dropLast(number).toMutableList() containers[to].addAll(fromContainer) } var answer = "" for (it in containers) { answer += it.last() } return answer } val testInput = readInput("Day05_test") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part2(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
1,838
advent-of-code-2022
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2015/Day22.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2015 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import java.util.* import kotlin.math.max import kotlin.math.min /** * [Day 22: Wizard Simulator 20XX](https://adventofcode.com/2015/day/22). */ object Day22 { @JvmStatic fun main(args: Array<String>) { measure { val character = readInput("year2015/Day22") .map { it.substringAfter(": ") } .map { it.toInt() } .let { Boss(it.first(), it.last()) } println("Part One: ${solve(character)}") println("Part Two: ${solve(character, true)}") } } fun solve(input: Boss, isPartTwo: Boolean = false): Int { var minMana = Int.MAX_VALUE val boss = input.copy() val wizards = PriorityQueue<Wizard> { a, b -> b.manaSpent.compareTo(a.manaSpent) } wizards += Wizard(50, 500, boss) while (wizards.size > 0) { val currentWizard = wizards.poll() if (isPartTwo && --currentWizard.hitpoints <= 0) continue currentWizard.applyEffect() Wizard.spells.forEach { spell -> if (currentWizard.canCast(spell)) { val nextWizard = currentWizard.clone() nextWizard.castSpell(spell) nextWizard.applyEffect() if (nextWizard.boss.hitpoints <= 0) { minMana = min(minMana, nextWizard.manaSpent) wizards.removeAll { wizard -> wizard.manaSpent > minMana } } else { nextWizard.hitpoints -= max(1, nextWizard.boss.damage - nextWizard.armor) if (nextWizard.hitpoints > 0 && nextWizard.mana > 0 && nextWizard.manaSpent < minMana) { wizards += nextWizard } } } } } return minMana } data class Boss(var hitpoints: Int, var damage: Int) : Cloneable { public override fun clone(): Boss { return Boss(hitpoints, damage) } } data class Wizard(var hitpoints: Int, var mana: Int, var boss: Boss) : Cloneable { var armor: Int = 0 var manaSpent: Int = 0 private var activeEffects = IntArray(3) companion object { var spells = listOf( Spell(53, 0), Spell(73, 0), Spell(113, 6), Spell(173, 6), Spell(229, 5) ) } fun canCast(spell: Spell): Boolean { val spellIndex = spells.indexOf(spell) return mana >= spell.cost && (spellIndex < 2 || activeEffects[spellIndex - 2] == 0) } fun castSpell(spell: Spell) { mana -= spell.cost manaSpent += spell.cost when (val spellIndex = spells.indexOf(spell)) { 0 -> boss.hitpoints -= 4 1 -> { hitpoints += 2 boss.hitpoints -= 2 } else -> activeEffects[spellIndex - 2] = spell.turns } } fun applyEffect() { activeEffects.indices.forEach { if (activeEffects[it] > 0) { activeEffects[it]-- when (it) { 0 -> armor = 7 1 -> boss.hitpoints -= 3 2 -> mana += 101 } } else if (it == 0) armor = 0 } } public override fun clone(): Wizard { val newWizard = Wizard(hitpoints, mana, boss.clone()) newWizard.armor = armor newWizard.manaSpent = manaSpent newWizard.activeEffects = activeEffects.clone() return newWizard } } class Spell(var cost: Int, var turns: Int) }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
3,976
advent-of-code
MIT License
src/main/kotlin/io/queue/NumberOfIslands.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.queue import java.util.* import kotlin.collections.HashSet // https://leetcode.com/explore/learn/card/queue-stack/231/practical-application-queue/1374/ class NumberOfIslands { fun execute(grid: Array<CharArray>): Int { val visited = HashSet<Coordinates>() var numberOfIslands = 0 grid.mapIndexed { index, chars -> chars.mapIndexed { internalIndex, char -> val coordinates = Coordinates(index, internalIndex) if (!visited.contains(coordinates)) { visited.add(coordinates) if (char != '0') { numberOfIslands += 1 visitIsland(grid, coordinates, visited, grid.size, chars.size) } } } } return numberOfIslands } private fun visitIsland(grid: Array<CharArray>, root: Coordinates, visited: HashSet<Coordinates>, maxI: Int, maxJ: Int) { val stack = Stack<List<Coordinates>>() stack.push(listOf(root)) while (stack.isNotEmpty()) { val coordinates = stack.pop() coordinates.map { coordinate -> if (!visited.contains(coordinate)) { visited.add(coordinate) } if (grid[coordinate.i][coordinate.j] != '0') { coordinate.generateChild(maxI, maxJ).filter { !visited.contains(it) }.let { if (it.isNotEmpty()) { stack.push(it) } } } } } } } data class Coordinates(val i: Int, val j: Int) { fun generateChild(maxI: Int, maxJ: Int) = mutableListOf<Coordinates>().apply { if (i + 1 < maxI) { add(Coordinates(i + 1, j)) } if (j + 1 < maxJ) { add(Coordinates(i, j + 1)) } if (i - 1 >= 0) { add(Coordinates(i - 1, j)) } if (j - 1 >= 0) { add(Coordinates(i, j - 1)) } } } fun main() { val numberOfIslands = NumberOfIslands() listOf( arrayOf( "11110", "11010", "11000", "00000"), arrayOf( "11000", "11000", "00100", "00011"), arrayOf( "111", "010", "111") ).map { grid -> println(" ${numberOfIslands.execute(grid.map { it.toCharArray() }.toTypedArray())}") } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,262
coding
MIT License
src/net/sheltem/aoc/y2022/Day13.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2022 suspend fun main() { Day13().run() } class Day13 : Day<Int>(13, 140) { private val firstDivider = "[[2]]".toSignal() private val secondDivider = "[[6]]".toSignal() override suspend fun part1(input: List<String>): Int = input.toPairsOfSignals().map { it.compare() }.mapIndexed { index, b -> if (b) (index + 1) else 0 }.sum() override suspend fun part2(input: List<String>): Int = input.filter { it.isNotBlank() }.toListOfSignals().asSequence().plus(firstDivider).plus(secondDivider).sorted() .mapIndexedNotNull { index, signal -> if (signal == firstDivider || signal == secondDivider) { index + 1 } else { null } }.reduce { acc, i -> acc * i } } private fun Pair<Signal, Signal>.compare(): Boolean = first < second private fun List<String>.toPairsOfSignals(): List<Pair<Signal, Signal>> = windowed(2, 3).map { it.toSignalPair() } private fun List<String>.toListOfSignals(): List<Signal> = this.map { it.toSignal() } private fun List<String>.toSignalPair(): Pair<Signal, Signal> = this[0].toSignal() to this[1].toSignal() private fun String.toSignal(): Signal = SignalList().readInput(this.iterator().apply { next() }) private class SignalList(var content: MutableList<Signal> = mutableListOf()) : Signal { var previous: Char = '0' fun readInput(input: Iterator<Char>): SignalList { while (input.hasNext()) { if (input.readNext()) return this } return this } private fun Iterator<Char>.readNext() = next().let { char -> when { char == ']' -> return true char == '[' -> SignalList().readInput(this).let { content.add(it) }.also { return false } char.isDigit() -> { var newDigit = char.digitToInt() newDigit = if (newDigit == 0 && previous.isDigit() && previous.digitToInt() == 1) 10 else newDigit previous = char if (newDigit == 10) { content.removeLast() content.add(SignalValue(newDigit)) } else content.add(SignalValue(newDigit)) return false } else -> { previous = char return false } } } override fun toString(): String { return content.joinToString(", ", "[", "]") } override fun compareTo(other: Signal): Int { return if (other is SignalList) { for (index in 0 until content.size) { if (index >= other.content.size) return 1 val comparison = content[index].compareTo(other.content[index]) if (comparison != 0) return comparison } if (other.content.size > content.size) return -1 else 0 } else { this.compareTo(SignalList(mutableListOf(other))) } } } private class SignalValue(val content: Int) : Signal { override fun compareTo(other: Signal): Int = if (other is SignalValue) { content - other.content } else { SignalList(mutableListOf(this)).compareTo(other) } override fun toString(): String { return content.toString() } } private sealed interface Signal : Comparable<Signal>
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
3,364
aoc
Apache License 2.0
year2019/day03/part2/src/main/kotlin/com/curtislb/adventofcode/year2019/day03/part2/Year2019Day03Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- It turns out that this circuit is very timing-sensitive; you actually need to minimize the signal delay. To do this, calculate the number of steps each wire takes to reach each intersection; choose the intersection where the sum of both wires' steps is lowest. If a wire visits a position on the grid multiple times, use the steps value from the first time it visits that position when calculating the total value of a specific intersection. The number of steps a wire takes is the total number of grid squares the wire has entered to get to that location, including the intersection being considered. Again consider the example from above: ........... .+-----+... .|.....|... .|..+--X-+. .|..|..|.|. .|.-X--+.|. .|..|....|. .|.......|. .o-------+. ........... In the above example, the intersection closest to the central port is reached after 8+5+5+2 = 20 steps by the first wire and 7+6+4+3 = 20 steps by the second wire for a total of 20+20 = 40 steps. However, the top-right intersection is better: the first wire takes only 8+5+2 = 15 and the second wire takes only 7+6+2 = 15, a total of 15+15 = 30 steps. Here are the best steps for the extra examples from above: - R75,D30,R83,U83,L12,D49,R71,U7,L72 U62,R66,U55,R34,D71,R55,D58,R83 = 610 steps - R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51 U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 = 410 steps What is the fewest combined steps the wires must take to reach an intersection? */ package com.curtislb.adventofcode.year2019.day03.part2 import com.curtislb.adventofcode.year2019.day03.wire.Wire import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2019, day 3, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int? { val (wireA, wireB) = inputPath.toFile().readLines().subList(0, 2).map { Wire(it.trim()) } val (intersection, pathLength) = wireA shortestIntersect wireB return if (intersection != null) pathLength else null } fun main() = when (val solution = solve()) { null -> println("No intersection found.") else -> println(solution) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,191
AdventOfCode
MIT License
src/year2022/day08/Day08.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2022.day08 import readInputFileByYearAndDay import readTestFileByYearAndDay fun main() { fun part1(input: List<String>): Int { val dimension = input[0].length val visibility = Array(dimension) { Array(dimension) { false } } // edges always visible visibility.indices.forEach { visibility[it][0] = true visibility[it][dimension - 1] = true } visibility[0].indices.forEach { visibility[0][it] = true } visibility[dimension - 1].indices.forEach { visibility[dimension - 1][it] = true } // check visible from left for (i in 0 until dimension) { var max = input[i][0].digitToInt() for (j in 1 until dimension) { val current = input[i][j].digitToInt() if (current > max) { visibility[i][j] = true max = current } } } // check visible from right for (i in dimension - 1 downTo 1) { var max = input[i][dimension - 1].digitToInt() for (j in dimension - 1 downTo 1) { val current = input[i][j].digitToInt() if (current > max) { visibility[i][j] = true max = current } } } // check visible from top for (i in 0 until dimension) { var max = input[0][i].digitToInt() for (j in 1 until dimension) { val current = input[j][i].digitToInt() if (current > max) { visibility[j][i] = true max = current } } } // check visible from bottom for (i in dimension - 1 downTo 1) { var max = input[dimension - 1][i].digitToInt() for (j in dimension - 1 downTo 1) { val current = input[j][i].digitToInt() if (current > max) { visibility[j][i] = true max = current } } } return visibility.flatten().count { it } } fun part2(input: List<String>): Int { val dimension = input[0].length val scenicScores = Array(dimension) { Array(dimension) { 0 } } for (x in 1 until dimension - 1) for (y in 1 until dimension - 1) { val treeHeight = input[x][y].digitToInt() var top = 1 for (j in x - 1 downTo 1) { if (input[j][y].digitToInt() >= treeHeight) break top++ } var bottom = 1 for (j in x + 1 until dimension - 1) { if (input[j][y].digitToInt() >= treeHeight) break bottom++ } val left = 1 + input[x].substring(1, y).reversed().takeWhile { it.digitToInt() < treeHeight }.count() val right = 1 + input[x].substring(y + 1).takeWhile { it.digitToInt() < treeHeight }.count() scenicScores[x][y] = top * bottom * left * right } return scenicScores.flatten().max() } val testInput = readTestFileByYearAndDay(2022, 8) check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInputFileByYearAndDay(2022, 8) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
3,471
advent-of-code-kotlin
Apache License 2.0
src/day04/Day04.kt
Ciel-MC
572,868,010
false
{"Kotlin": 55885}
package day04 import readInput fun main() { fun String.toRange(): IntRange { val (min, max) = this.split("-") return min.toInt() .. max.toInt() } fun String.toIntRanges(): Pair<IntRange, IntRange> { return this.split(",").let { (a, b) -> a.toRange() to b.toRange() } } operator fun IntRange.contains(other: IntRange): Boolean { return this.contains(other.first) && this.contains(other.last) } fun part1(input: List<String>): Int { return input.map(String::toIntRanges) .count { (a, b) -> a in b || b in a } } fun part2(input: List<String>): Int { return input.map(String::toIntRanges) .count { (a, b) -> a.firstOrNull { it in b } != null } } val testInput = readInput(4, true) check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput(4) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7eb57c9bced945dcad4750a7cc4835e56d20cbc8
979
Advent-Of-Code
Apache License 2.0
src/main/kotlin/com/dambra/adventofcode2018/day5/Polymer.kt
pauldambra
159,939,178
false
null
package com.dambra.adventofcode2018.day5 fun String.triggerPolymer(): String { val removedIndices = mutableSetOf<Int>() var triggeredPolymerCollapse: Boolean do { triggeredPolymerCollapse = false for (i in 0 until this.length) { val left = this[i] if (removedIndices.contains(i)) { continue } val next = findNext(i, removedIndices) if (next > this.length - 1) { continue } val right = this[next] if (haveSameType( left, right ) && haveOppositePolarities(left, right) ) { removedIndices.add(i) removedIndices.add(next) triggeredPolymerCollapse = true } } } while (triggeredPolymerCollapse) return this .filterIndexed { i, _ -> !removedIndices.contains(i) } } fun String.improvePolymer(): String { var shortestImprovedPolymer = this // println("improving $this") "abcdefghijklmnopqrstuvwxyz".asSequence() .forEach {polymerType -> if (this.any { x -> x.equals(polymerType, ignoreCase = true) }) { // println("filtering $this for $polymerType") val removedIndices = mutableSetOf<Int>() var triggeredPolymerCollapse: Boolean do { triggeredPolymerCollapse = false for (i in 0 until this.length) { val left = this[i] if (removedIndices.contains(i)) { continue } //filter polymer type if (left.equals(polymerType, ignoreCase = true)) { removedIndices.add(i) triggeredPolymerCollapse = true continue } val next = findNext(i, removedIndices) if (next > this.length - 1) { continue } val right = this[next] // println("comparing $left and $right") if (haveSameType(left, right) && haveOppositePolarities(left, right)) { removedIndices.add(i) removedIndices.add(next) triggeredPolymerCollapse = true } } } while (triggeredPolymerCollapse) val s = this.filterIndexed { i, _ -> !removedIndices.contains(i) } // println("$s has length ${s.length}, current best is $shortestImprovedPolymer with ${shortestImprovedPolymer.length}") if (s.length < shortestImprovedPolymer.length) { shortestImprovedPolymer = s } } } return shortestImprovedPolymer } private fun findNext(i: Int, removedIndices: MutableSet<Int>): Int { var next = i + 1 while (removedIndices.contains(next)) { next += 1 } return next } private fun haveSameType(left: Char, right: Char) = left.equals(right, ignoreCase = true) private fun haveOppositePolarities(left: Char, right: Char) = (left.isUpperCase() && right.isLowerCase() || left.isLowerCase() && right.isUpperCase())
0
Kotlin
0
1
7d11bb8a07fb156dc92322e06e76e4ecf8402d1d
3,493
adventofcode2018
The Unlicense
dcp_kotlin/src/main/kotlin/dcp/day310/day310.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day310 // day310.kt // By <NAME>, 2020. import kotlin.math.floor import kotlin.math.log2 import kotlin.math.pow /** * This is sequence A000788 in the Online Encyclopedia of Integer Sequences: * http://oeis.org/A000788 * It has a number of closed forms. We implement two below. */ /** * Brute force: count the 1s in the string representations. Assuming the conversion to string takes O(n), * this runs in time O(n). */ fun binaryCountViaStrings(n: Int): Int { require(n >= 0) return (1..n).map(Integer::toBinaryString).map { it.count { c -> c == '1' }}.sum() } /** * Count the number of 1s in the binary representation of [0,n]. * Should work in time O(log n). We can remove the recursion to prevent stack overflow but will then need mutability. */ fun binaryCount(n: Int): Int { require(n >= 0) if (n == 0) return 0 val k = floor(log2(n.toDouble())) val m = (2.toDouble().pow(k) - 1).toInt() return (k * (m + 1) / 2).toInt() + binaryCount(n - m - 1) + n - m } /** * Another formula for counting the number of 1s in the binary representation [0,n]. * Should work in time O(log n). */ fun binaryCount2(n: Int): Int = when { n < 0 -> error("n must be greater than 0: $n") n == 0 -> 0 n % 2 == 0 -> { val np = n / 2 binaryCount2(np) + binaryCount2(np - 1) + np } else -> { val np = (n - 1) / 2 2 * binaryCount2(np) + np + 1 } }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,460
daily-coding-problem
MIT License
src/day09/Day09.kt
easchner
572,762,654
false
{"Kotlin": 104604}
package day09 import readInputString data class Position(var x: Int, var y: Int) fun main() { fun moveHead(head: Position, direction: String) { when (direction) { "U" -> head.y++ "D" -> head.y-- "L" -> head.x-- "R" -> head.x++ } } fun moveKnot(head: Position, tail: Position): Boolean { if (tail.y < head.y - 1) { when { tail.x < head.x - 1 -> tail.x++ tail.x > head.x + 1 -> tail.x-- else -> tail.x = head.x } tail.y = head.y - 1 return true } if (tail.y > head.y + 1) { when { tail.x < head.x - 1 -> tail.x++ tail.x > head.x + 1 -> tail.x-- else -> tail.x = head.x } tail.y = head.y + 1 return true } if (tail.x > head.x + 1) { tail.x = head.x + 1 when { tail.y < head.y - 1 -> tail.y++ tail.y > head.y + 1 -> tail.y-- else -> tail.y = head.y } return true } if (tail.x < head.x - 1) { tail.x = head.x - 1 when { tail.y < head.y - 1 -> tail.y++ tail.y > head.y + 1 -> tail.y-- else -> tail.y = head.y } return true } return false } fun part1(input: List<String>): Int { val headPosition = Position(0, 0) val tailPosition = Position(0, 0) val positions = mutableSetOf<Position>() for (line in input) { val inputs = line.split(" ") val direction = inputs[0] val distance = inputs[1].toInt() for (i in 0 until distance) { moveHead(headPosition, direction) moveKnot(headPosition, tailPosition) positions.add(tailPosition.copy()) } } return positions.size } fun part2(input: List<String>): Int { val knots = Array(10) { Position(0, 0) } val positions = mutableSetOf<Position>() for (line in input) { val inputs = line.split(" ") val direction = inputs[0] val distance = inputs[1].toInt() for (i in 0 until distance) { moveHead(knots[0], direction) for (k in 0 until knots.size - 1) { val moved = moveKnot(knots[k], knots[k + 1]) if (!moved) break } positions.add(knots.last().copy()) } } return positions.size } val testInput = readInputString("day09/test") val testInput2 = readInputString("day09/test2") val input = readInputString("day09/input") check(part1(testInput) == 13) println(part1(input)) check(part2(testInput2) == 36) println(part2(input)) }
0
Kotlin
0
0
5966e1a1f385c77958de383f61209ff67ffaf6bf
3,032
Advent-Of-Code-2022
Apache License 2.0
2021/src/day11/day11.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day11 import java.io.File import java.lang.Integer.max import java.lang.Integer.min fun main() { val octoBoard = parseData(File("src/day11", "day11input.txt").readLines()) println(getAllFlashStep(octoBoard)) } fun getFlashCount(octoBoard: OctoBoard, stepCount: Int): Int { var sumFlashes = 0 for (i in 1..stepCount) { sumFlashes += octoBoard.runStep() } return sumFlashes } fun getAllFlashStep(octoBoard: OctoBoard): Int { var step = 0 while (!octoBoard.isAllFlash()) { octoBoard.runStep() step++ } return step } fun parseData(input: List<String>): OctoBoard { return OctoBoard(input.map { it.toCharArray().map { digit -> digit.digitToInt() }.toIntArray() }.toTypedArray()) } data class OctoBoard(val boardData: Array<IntArray>) { /** * Runs a step. * @return Number of flashed cells */ fun runStep(): Int { var cellsToFlash = ArrayDeque<Pair<Int, Int>>() var flashedCells = mutableSetOf<Pair<Int, Int>>() // First add 1 to all points var numCols: Int = 0 boardData.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, value -> boardData[rowIndex][colIndex] = value + 1 if (boardData[rowIndex][colIndex] > 9) { cellsToFlash.add(Pair(rowIndex, colIndex)) } if (colIndex > numCols) { numCols = colIndex } } } while (cellsToFlash.isNotEmpty()) { flashCell(cellsToFlash.removeFirst(), numCols + 1, cellsToFlash, flashedCells) } // Now take all flashed cells and set to 0 flashedCells.forEach { boardData[it.first][it.second] = 0 } return flashedCells.size } private fun flashCell( cell: Pair<Int, Int>, numCols: Int, cellsToFlash: ArrayDeque<Pair<Int, Int>>, flashedCells: MutableSet<Pair<Int, Int>> ) { if (flashedCells.contains(cell)) { return } flashedCells.add(cell) // Add 1 to all the neighbors val neighbors = getNeighbors(cell, boardData.size, numCols) for (neighbor in neighbors) { boardData[neighbor.first][neighbor.second] += 1 } for (neighbor in neighbors) { if (boardData[neighbor.first][neighbor.second] > 9) { cellsToFlash.add(neighbor) } } } fun isAllFlash(): Boolean { return boardData.all { row -> row.all { it == 0 } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as OctoBoard if (!boardData.contentDeepEquals(other.boardData)) return false return true } override fun hashCode(): Int { return boardData.contentDeepHashCode() } override fun toString(): String { return boardData.map { it.joinToString() }.joinToString(separator = "\n") } } fun getNeighbors(cell: Pair<Int, Int>, numRows: Int, numCols: Int): List<Pair<Int, Int>> { return buildList { for (row in (max(0, cell.first - 1)..min(cell.first + 1, numRows - 1))) { for (col in (max(0, cell.second - 1)..min(cell.second + 1, numCols - 1))) { if (row != cell.first || col != cell.second) { add(Pair(row, col)) } } } } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,569
adventofcode
Apache License 2.0
src/main/kotlin/github/walkmansit/aoc2020/Day10.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 class Day10(val input: List<String>) : DayAoc<Int, Long> { private class AdaptersChain(val adapters: List<Int>) { fun findDiffMult(): Int { val set = adapters.toMutableSet() var oneDiff = 0 var threeDiff = 1 var current = 0 fun nextIterate(current: Int): Int { for (i in 1..3) { if (set.contains(current + i)) { if (i == 1) oneDiff++ if (i == 3) threeDiff++ set.remove(current + i) return current + i } } return -1 } while (current != -1 || set.isNotEmpty()) { current = nextIterate(current) } return oneDiff * threeDiff } fun countDistinctArrangments(): Long { val sortedList = adapters.sortedDescending() val dp = Array<Long>(sortedList.size) { 0 } for ((i, v) in sortedList.withIndex()) { if (i == 0) { dp[i] = 1 continue } for (k in i - 1 downTo i - 3) { if (k >= 0 && sortedList[k] - v < 4) { dp[i] += dp[k] } } } return dp.last() } } override fun getResultPartOne(): Int { return AdaptersChain(input.map { it.toInt() }).findDiffMult() } override fun getResultPartTwo(): Long { return AdaptersChain((input + listOf("0")).map { it.toInt() }).countDistinctArrangments() } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
1,733
AdventOfCode2020
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions52.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round0.BinaryTreeNode fun test52() { printlnResult(testCase()) } /** * Questions 52: Flat binary-search tree */ private fun <T : Comparable<T>> BinaryTreeNode<T>.flat(): BinaryTreeNode<T> = flatInternal().first private fun <T : Comparable<T>> BinaryTreeNode<T>.flatInternal(): Pair<BinaryTreeNode<T>, BinaryTreeNode<T>> { val leftHead = left?.flatInternal()?.let { (head, trail) -> left = null trail.right = this head } ?: this val rightTrail = right?.flatInternal()?.let { (head, trail) -> head.left = null right = head trail } ?: this return leftHead to rightTrail } private fun <T : Comparable<T>> BinaryTreeNode<T>.flatList() = buildList { var head: BinaryTreeNode<T>? = flat() while (head != null) { add(head.value) head = head.right } } private fun testCase() = BinaryTreeNode( value = 4, left = BinaryTreeNode( value = 2, left = BinaryTreeNode(value = 1), right = BinaryTreeNode(value = 3), ), right = BinaryTreeNode( value = 5, right = BinaryTreeNode(value = 6) ), ) private fun printlnResult(root: BinaryTreeNode<Int>) = println("The binary search tree ${root.inOrderList()}(inorder), flat it we can get ${root.flatList()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,386
Algorithm
Apache License 2.0
src/Day02.kt
maximilianproell
574,109,359
false
{"Kotlin": 17586}
fun main() { fun part1(input: List<String>): Int { val allPoints = input.sumOf { val (first, second) = it.split(" ") val opponent = Shape.decryptShape(first) val me = Shape.decryptShape(second) // my points for this move me.play(opponent) } println("all points: $allPoints") return allPoints } fun part2(input: List<String>): Int { val allPoints = input.sumOf { val game = it.split(" ") val opponent = Shape.decryptShape(game.first()) val outcome = Outcome.decryptOutcome(game[1]) val me = opponent.getShapeForOutcome(outcome) // my points for this move me.play(opponent) } println("all points: $allPoints") return allPoints } val input = readInput("Day02") part1(input) part2(input) } enum class Outcome(val points: Int) { LOSE(0), DRAW(3), WIN(6); companion object { fun decryptOutcome(input: String): Outcome { return when (input) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> error("Can't decrypt input $input") } } } } sealed class Shape(val value: Int) { companion object { fun decryptShape(input: String): Shape { return when (input) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissor else -> error("Can't decrypt input $input.") } } } abstract fun play(shape: Shape): Int abstract fun getShapeForOutcome(outcome: Outcome): Shape object Rock : Shape(1) { override fun play(shape: Shape): Int { return when (shape) { is Paper -> Outcome.LOSE.points is Rock -> Outcome.DRAW.points is Scissor -> Outcome.WIN.points } + value } override fun getShapeForOutcome(outcome: Outcome): Shape { return when (outcome) { Outcome.LOSE -> Scissor Outcome.DRAW -> this Outcome.WIN -> Paper } } } object Paper : Shape(2) { override fun play(shape: Shape): Int { return when (shape) { is Paper -> Outcome.DRAW.points is Rock -> Outcome.WIN.points is Scissor -> Outcome.LOSE.points } + value } override fun getShapeForOutcome(outcome: Outcome): Shape { return when (outcome) { Outcome.LOSE -> Rock Outcome.DRAW -> this Outcome.WIN -> Scissor } } } object Scissor : Shape(3) { override fun play(shape: Shape): Int { return when (shape) { is Paper -> Outcome.WIN.points is Rock -> Outcome.LOSE.points is Scissor -> Outcome.DRAW.points } + value } override fun getShapeForOutcome(outcome: Outcome): Shape { return when (outcome) { Outcome.LOSE -> Paper Outcome.DRAW -> this Outcome.WIN -> Rock } } } }
0
Kotlin
0
0
371cbfc18808b494ed41152256d667c54601d94d
3,322
kotlin-advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day9.kt
andilau
573,139,461
false
{"Kotlin": 65955}
package days import kotlin.math.sign @AdventOfCodePuzzle( name = "Rope Bridge", url = "https://adventofcode.com/2022/day/9", date = Date(day = 9, year = 2022) ) class Day9(val input: List<String>) : Puzzle { private val instructions = input .map { line -> line.first() to line.substringAfter(' ').toInt() } override fun partOne(): Int = instructions.path().follow().toSet().size override fun partTwo(): Int = instructions.path().followKnots().toSet().size data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(x + other.x, y + other.y) operator fun minus(other: Point) = Point(x - other.x, y - other.y) infix fun adjacent(other: Point) = other.x in (this.x - 1..this.x + 1) && other.y in (this.y - 1..this.y + 1) fun move(dir: Char) = when (dir) { 'L' -> copy(x = x - 1) 'R' -> copy(x = x + 1) 'U' -> copy(y = y + 1) 'D' -> copy(y = y - 1) else -> error("Check your input $dir") } fun moveTo(other: Point): Point { if (other adjacent this) return this val diff = other - this val move = Point(diff.x.sign, diff.y.sign) return this + move } override fun toString(): String = "P($x, $y)" companion object { val ORIGIN = Point(0, 0) } } private fun List<Pair<Char, Int>>.path() = sequence() { var current = Point.ORIGIN yield(current) this@path.forEach { (dir, steps) -> repeat(steps) { current = current.move(dir) yield(current) } } } private fun Sequence<Point>.follow(): Sequence<Point> = sequence { var tail = this@follow.first() this@follow.drop(1).forEach { head -> tail = tail.moveTo(head) yield(tail) } } private fun Sequence<Point>.followKnots(): Sequence<Point> = sequence { val knots = MutableList(10) { this@followKnots.first() } this@followKnots.drop(1).forEach { head -> knots[0] = head for ((headIndex, tailIndex) in knots.indices.zipWithNext()) { val h = knots[headIndex] val t = knots[tailIndex] knots[tailIndex] = t.moveTo(h) } yield(knots.last()) } } }
0
Kotlin
0
0
da824f8c562d72387940844aff306b22f605db40
2,464
advent-of-code-2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day2.kt
jgrgt
575,475,683
false
{"Kotlin": 94368}
package days enum class Hand { ROCK, PAPER, SCISSORS; companion object { fun from(l: String): Hand { return when (l) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> throw IllegalArgumentException("Unknown hand $l") } } } } enum class Instruction { LOSE, DRAW, WIN; companion object { fun from(l: String): Instruction { return when (l) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> throw IllegalArgumentException("Unknown instruction $l") } } } } class Game2(val opponent: Hand, val instruction: Instruction) { private fun handScore(h: Hand): Int { return when (h) { Hand.ROCK -> 1 Hand.PAPER -> 2 Hand.SCISSORS -> 3 } } fun score(): Int { val myHand = when (instruction) { Instruction.LOSE -> loseHand(opponent) Instruction.DRAW -> drawHand(opponent) Instruction.WIN -> winHand(opponent) } return handScore(myHand) + instructionScore(instruction) } private fun instructionScore(instruction: Instruction): Int { return when(instruction) { Instruction.LOSE -> 0 Instruction.DRAW -> 3 Instruction.WIN -> 6 } } fun loseHand(h: Hand) : Hand{ return when(h) { Hand.ROCK -> Hand.SCISSORS Hand.PAPER -> Hand.ROCK Hand.SCISSORS -> Hand.PAPER } } fun winHand(h: Hand) : Hand{ return when(h) { Hand.ROCK -> Hand.PAPER Hand.PAPER -> Hand.SCISSORS Hand.SCISSORS -> Hand.ROCK } } fun drawHand(h: Hand) : Hand{ return h } } class Game1(val opponent: Hand, val mine: Hand) { val loss = 0 val draw = 3 val win = 6 private fun handScore(h: Hand): Int { return when (h) { Hand.ROCK -> 1 Hand.PAPER -> 2 Hand.SCISSORS -> 3 } } fun score(): Int { return handScore(mine) + winScore() } private fun winScore(): Int { return when (opponent) { Hand.ROCK -> when (mine) { Hand.ROCK -> draw Hand.PAPER -> win Hand.SCISSORS -> loss } Hand.PAPER -> when (mine) { Hand.ROCK -> loss Hand.PAPER -> draw Hand.SCISSORS -> win } Hand.SCISSORS -> when (mine) { Hand.ROCK -> win Hand.PAPER -> loss Hand.SCISSORS -> draw } } } } class Day2 : Day(2) { override fun partOne(): Any { return doPartOne(inputList) } override fun partTwo(): Any { return doPartTwo(inputList) } fun doPartOne(inputList: List<String>): Int { return inputList.sumOf { l -> val letters = l.split(" ") Game1( Hand.from(letters[0]), Hand.from(letters[1]) ).score() } } fun doPartTwo(inputList: List<String>): Int { return inputList.sumOf { l -> val letters = l.split(" ") Game2( Hand.from(letters[0]), Instruction.from(letters[1]) ).score() } } }
0
Kotlin
0
0
5174262b5a9fc0ee4c1da9f8fca6fb86860188f4
3,591
aoc2022
Creative Commons Zero v1.0 Universal
src/Day07.kt
spaikmos
573,196,976
false
{"Kotlin": 83036}
import java.util.LinkedList fun main() { // Ingest the list of input commands to generate file structure tree fun buildTree(input: List<String>): TreeNode { val rootDir = TreeNode("root", 0, FileType.DIR) var curDir = rootDir val it = input.iterator() while (it.hasNext()) { val i = it.next() if (i.startsWith("$ cd")) { val name = i.split("$ cd ")[1] if (name == "..") { curDir = curDir.parent!! } else { // Find the child directory node for (node in curDir.children) { if (node.name == name) { curDir = node break } } } } else if (i.startsWith("$ ls")) { // Do nothing. Process the ls contents in the 'else' clause below continue } else { val entry = i.split(" ") if (entry[0] == "dir") { // Add a new directory entry curDir.addChild(entry[1], 0, FileType.DIR) } else { // Add a new file entry curDir.addChild(entry[1], entry[0].toInt(), FileType.FILE) } } } return rootDir } // Find the sum of all directories that have a size < 100000 fun part1(root: TreeNode): Int { var totalSize = 0 for (node in TreeNode.dirs) { if (node.size < 100000) { totalSize += node.size } } return totalSize } // Find the smallest directory that can be deleted to free up 30000000 bytes total fun part2(root: TreeNode): Int { val totalSize = 70000000 val needSize = 30000000 val deleteSize = needSize - (totalSize - root.size) var minDelete = root.size for (node in TreeNode.dirs) { if ((node.size < minDelete) && (node.size > deleteSize)) { minDelete = node.size } } return minDelete } val input = readInput("../input/Day07") val rootNode = buildTree(input) println(part1(rootNode)) println(part2(rootNode)) } enum class FileType { FILE, DIR } class TreeNode(var name: String, var size: Int, var type: FileType) { // Create class static variables companion object { var files = ArrayList<TreeNode>() var dirs = ArrayList<TreeNode>() } // Make this nullable only because the root node doesn't have a parent. This can be avoided // by defining a new FileType: ROOT and pointing the parent back to root, but that's a hack // too... var parent: TreeNode? = null var children: MutableList<TreeNode> init { children = LinkedList() } fun addChild(name: String, size: Int, type: FileType) { // Check if child already exists for (node in children) { if (node.name == name) { val rootname = this.name println("ERROR: child $name already exists in dir: $rootname, size: $size") return } } val childNode = TreeNode(name, size, type) childNode.parent = this children.add(childNode) if (type == FileType.FILE) { files.add(childNode) // Walk the dir structure to add filesize to each parent dir var curParent: TreeNode? = this while (curParent != null) { curParent.size += size curParent = curParent.parent } } else { dirs.add(childNode) } } }
0
Kotlin
0
0
6fee01bbab667f004c86024164c2acbb11566460
3,805
aoc-2022
Apache License 2.0
src/main/kotlin/days/Day5.kt
broersma
574,686,709
false
{"Kotlin": 20754}
package days import kotlin.collections.ArrayDeque class Day5 : Day(5) { override fun partOne(): String { val input = inputString.split("\n\n") val stacks = input[0].split("\n") .reversed() .drop(1) .map { it.drop(1).filterIndexed { i, _ -> i % 4 == 0 }.toList() } .fold(Array(10) { ArrayDeque<Char>() }) { acc, row -> acc.apply { row.withIndex().filter { it.value.isLetter() }.onEach { acc[it.index].add(it.value) } } } val proc = input[1].split("\n").map { it.split(" ").mapNotNull { it.toIntOrNull() } } proc.forEach { val num = it[0] val from = it[1] - 1 val to = it[2] - 1 repeat(num) { stacks[to].add(stacks[from].removeLast()) } } return stacks.filterNot { it.isEmpty() }.joinToString("") { it.last().toString() } } override fun partTwo(): String { val input = inputString.split("\n\n") val stacks = input[0].split("\n") .reversed() .drop(1) .map { it.drop(1).filterIndexed { i, _ -> i % 4 == 0 }.toList() } .fold(Array(10) { ArrayDeque<Char>() }) { acc, row -> acc.apply { row.withIndex().filter { it.value.isLetter() }.onEach { acc[it.index].add(it.value) } } } val proc = input[1].split("\n").map { it.split(" ").mapNotNull { it.toIntOrNull() } } proc.forEach { val num = it[0] val from = it[1] - 1 val to = it[2] - 1 stacks[to].addAll( sequence { repeat(num) { yield(stacks[from].removeLast()) } } .toList() .reversed() ) } return stacks.filterNot { it.isEmpty() }.joinToString("") { it.last().toString() } } }
0
Kotlin
0
0
cd3f87e89f7518eac07dafaaeb0f6adf3ecb44f5
2,317
advent-of-code-2022-kotlin
Creative Commons Zero v1.0 Universal
src/shreckye/coursera/algorithms/Course 1 Programming Assignment #4.kts
ShreckYe
205,871,625
false
{"Kotlin": 72136}
package shreckye.coursera.algorithms import java.util.* import kotlin.collections.ArrayList val filename = args[0] class Vertex(val label: Int, val edges: MutableList<Edge>) class Edge(var vertex1: Vertex, var vertex2: Vertex) /*@Suppress("NOTHING_TO_INLINE") inline fun <T> Array<T>.getVertex(vertexLabel: Int) = get(vertexLabel - 1) @Suppress("NOTHING_TO_INLINE") inline fun <T> Array<T>.setVertex(vertexLabel: Int, vertex: T) = get(vertexLabel - 1) @Suppress("NOTHING_TO_INLINE") inline fun <T> Array<T>.withVertexLabel() = withIndex().map { (it.index + 1) to it.value }*/ val verticesLabels = readAdjacencyList(filename, 200) val INDEX_LABEL_OFFSET = 1 fun createGraph( verticesLabelsSortedByLabel: List<VertexLabels>, indexLabelOffset: Int ): Pair<Array<Vertex>, ArrayList<Edge>> { val vertices = Array(verticesLabelsSortedByLabel.size) { Vertex(it + indexLabelOffset, LinkedList()) } fun Array<Vertex>.getVertex(label: Int) = this[label - indexLabelOffset] val edges = ArrayList<Edge>(verticesLabelsSortedByLabel.sumBy { it.second.size } / 2) for ((label, adjacentLabels) in verticesLabelsSortedByLabel) { val vertex = vertices.getVertex(label) vertex.edges.addAll(adjacentLabels.filter { it > label }.map { val adjacentVertex = vertices.getVertex(it) val edge = Edge(vertex, adjacentVertex) adjacentVertex.edges.add(edge) edges.add(edge) edge }) } return vertices to edges } val n = verticesLabels.size var minNumCutEdges = Int.MAX_VALUE for (i in 0 until n * n) { println("${i}st iteration") val (vertices, edges) = createGraph(verticesLabels, INDEX_LABEL_OFFSET) val vertexMap = vertices.associateBy(Vertex::label).toMutableMap() while (vertexMap.size > 2) { val edgeToContract = edges.random() val vertex1 = edgeToContract.vertex1 val vertex2 = edgeToContract.vertex2 fun removeFilter(edge: Edge) = (edge.vertex1 === vertex1 && edge.vertex2 === vertex2) || (edge.vertex1 === vertex2 && edge.vertex2 === vertex1) vertex1.edges.removeIf(::removeFilter) vertex2.edges.removeIf(::removeFilter) edges.removeIf(::removeFilter) for (edge in vertex2.edges) { if (edge.vertex1 === vertex2) edge.vertex1 = vertex1 if (edge.vertex2 === vertex2) edge.vertex2 = vertex1 } vertex1.edges.addAll(vertex2.edges) vertexMap.remove(vertex2.label) } //assert(vertexMap.size == 2 && vertexMap.values.iterator().run { next().edges.toSet() == next().edges.toSet() }) val numCutEdges = vertexMap.values.first().edges.size if (numCutEdges < minNumCutEdges) minNumCutEdges = numCutEdges println("numCutEdges = $numCutEdges, minNumCutEdges = $minNumCutEdges") } println("With more than 1 - 1/e confidence: $minNumCutEdges")
0
Kotlin
1
2
1746af789d016a26f3442f9bf47dc5ab10f49611
2,949
coursera-stanford-algorithms-solutions-kotlin
MIT License
src/main/kotlin/day5B.kt
zlataovce
726,171,765
false
{"Kotlin": 10762}
import kotlin.math.max import kotlin.math.min fun main() = println( generateSequence(::readLine) .joinToString("\n") .split("\n\n") .let { p -> Pair( p[0].substringAfter(": ") .split(' ') .map(String::toLong), p.drop(1) .map { s -> s.split('\n') .drop(1) .map { l -> l.split(' ').let { (a, b, c) -> Triple(a.toLong(), b.toLong(), c.toLong()) } } } ) } .let { (seed, fs) -> seed.chunked(2) .map { (a, b) -> fs // this is so awful, why does it work .fold(listOf(a to a + b)) { y, t -> mutableListOf<Pair<Long, Long>>().also { l -> l.addAll( t.fold(y) { r, (dst, src, len) -> r.flatMap { (x, y) -> buildList { (x to min(y, src)) .takeIf { it.second > it.first } ?.let(::add) (max(src + len, x) to y) .takeIf { it.second > it.first } ?.let(::add) (max(x, src) to min(src + len, y)) .takeIf { it.second > it.first } ?.let { l.add((it.first - src + dst) to (it.second - src + dst)) } } } } ) } } .minOf { min(it.first, it.second) } } } .min() )
0
Kotlin
0
2
0f5317f87615ad646e390eca33973f527dc8b72b
2,320
aoc23
The Unlicense
20/part_two.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : Image { val input = File("input.txt") .readText() .split("""\r\n\r\n""".toRegex()) val enhancementAlgo = input[0] val pixels = input[1].split("\r\n").filter { it.isNotEmpty() } return Image(enhancementAlgo, pixels) } const val ALGO_STEPS = 2 class Image(enhancementAlgo : String, pixels : List<String>) { companion object { const val LIGHT_PIXEL = '#' } private var enhancementAlgo: String private var pixels : List<String> private var interestingPixels = mutableMapOf<Pair<Int, Int>, Char>() private var rows = 0 private var cols = 0 private var pixelsOutsideInterest = '.' private var stepsApplied = 0 init { this.enhancementAlgo = enhancementAlgo this.pixels = pixels rows = pixels.size cols = pixels[0].length for (i in -ALGO_STEPS..(rows + ALGO_STEPS)) { for (j in -ALGO_STEPS..(cols + ALGO_STEPS)) { val pos = Pair(i, j) if (isIn(pos)) { interestingPixels[pos] = pixels[i][j] } else { interestingPixels[pos] = pixelsOutsideInterest } } } } fun applyAlgoStep() { stepsApplied++ val newInterestingPixels = mutableMapOf<Pair<Int, Int>, Char>() for (pos in interestingPixels.keys) { val pixelValue = calcValue(pos) newInterestingPixels[pos] = enhancementAlgo[pixelValue] } interestingPixels = newInterestingPixels pixelsOutsideInterest = if (pixelsOutsideInterest == LIGHT_PIXEL) enhancementAlgo.last() else enhancementAlgo.first() } private fun calcValue(pos : Pair<Int, Int>) : Int { var result = 0 for (deltaX in -1..1) { for (deltaY in -1..1) { val posChecked = Pair(pos.first + deltaX, pos.second + deltaY) if (posChecked in interestingPixels) { result = 2 * result + (if (interestingPixels[posChecked] == LIGHT_PIXEL) 1 else 0) } else { result = 2 * result + (if (pixelsOutsideInterest == LIGHT_PIXEL) 1 else 0) } } } return result } fun countLightPixels() : Int { if (pixelsOutsideInterest == LIGHT_PIXEL) throw Exception("Infinite pixels are light") var result = 0 for (pixel in interestingPixels.values) { result += if (pixel == LIGHT_PIXEL) 1 else 0 } return result } private fun isIn(pos : Pair<Int, Int>) : Boolean { return pos.first in 0 until rows && pos.second in 0 until cols } } fun solve(image : Image) : Int { for (step in 1..ALGO_STEPS) { image.applyAlgoStep() } return image.countLightPixels() } fun main() { val image = readInput() val ans = solve(image) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
2,980
advent-of-code-2021
MIT License
src/Day05.kt
erwinw
572,913,172
false
{"Kotlin": 87621}
@file:Suppress("MagicNumber") private const val DAY = "05" private const val PART1_CHECK = "CMZ" private const val PART2_CHECK = "MCD" private typealias Stacks = MutableList<MutableList<Char>> private fun splitInput(input: List<String>): Pair<List<String>, List<String>> { val partA = mutableListOf<String>() val partB = mutableListOf<String>() val iterator = input.iterator() var item = iterator.next() while (item.isNotEmpty()) { partA.add(item) item = iterator.next() } iterator.forEachRemaining(partB::add) return partA to partB } private fun Stacks.print() = forEachIndexed { index, chars -> println(">[$index]: $chars") } private fun parseInitialStacks(input: List<String>): Stacks { val stackCount = (input.last().length + 2) / 4 val stacks = MutableList(stackCount) { mutableListOf<Char>() } input.dropLast(1).reversed().forEach { line -> for (stack in 0 until stackCount) { val charOffset = stack * 4 + 1 val char = line.getOrNull(charOffset) if (char != null && char != ' ') { stacks[stack].add(char) } } } return stacks } private val procedureRegex = Regex("""^move (\d+) from (\d+) to (\d+)$""") private fun parseProcedure(input: String): Triple<Int, Int, Int> { val (a, b, c) = procedureRegex.find(input)!!.groupValues.drop(1).map(String::toInt) return Triple(a, b, c) } fun main() { fun part1(input: List<String>): String { val (inputStacks, inputProcedures) = splitInput(input) val stacks = parseInitialStacks(inputStacks) inputProcedures.map(::parseProcedure) .forEach { (count, src, dst) -> val moving = stacks[src-1].takeLast(count) stacks[src-1] = stacks[src-1].dropLast(count).toMutableList() stacks[dst-1].addAll(moving.reversed()) } stacks.print() return stacks.map(List<*>::last).joinToString("") } fun part2(input: List<String>): String { val (inputStacks, inputProcedures) = splitInput(input) val stacks = parseInitialStacks(inputStacks) inputProcedures.map(::parseProcedure) .forEach { (count, src, dst) -> val moving = stacks[src-1].takeLast(count) stacks[src-1] = stacks[src-1].dropLast(count).toMutableList() stacks[dst-1].addAll(moving) } stacks.print() return stacks.map(List<*>::last).joinToString("") } println("Day $DAY") // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") check(part1(testInput).also { println("Part1 output: $it") } == PART1_CHECK) check(part2(testInput).also { println("Part2 output: $it") } == PART2_CHECK) val input = readInput("Day$DAY") println("Part1 final output: ${part1(input)}") println("Part2 final output: ${part2(input)}") }
0
Kotlin
0
0
57cba37265a3c63dea741c187095eff24d0b5381
3,014
adventofcode2022
Apache License 2.0
src/Day09.kt
Vlisie
572,110,977
false
{"Kotlin": 31465}
import java.io.File import kotlin.math.absoluteValue import kotlin.math.sign class Day09(file: File) { val tailList = mutableListOf<Coordinate>() val motionList = file.readLines() .map { Motion(Direction.withFirstLetter(it[0]), it.substring(2).toInt()) } fun part1(): Int { return moveHead(2) } fun part2(): Int { tailList.clear() return moveHead(10) } /* private fun updateTail() { val diffx = head.x - tail.x val diffy = head.y - tail.y if (diffx == 0 || diffy == 0) { if (diffx < -1 || diffx > 1) { tail.addToX(diffx / 2) } else if (diffy < -1 || diffy > 1) { tail.addToY(diffy / 2) } tailList.add(Coordinate(tail.x, tail.y)) } else { if (diffx < -1 || diffx > 1) { tail.addToX(diffx / 2) tail.addToY(diffy) } else if (diffy < -1 || diffy > 1) { tail.addToY(diffy / 2) tail.addToX(diffx) } tailList.add(Coordinate(tail.x, tail.y)) } } private fun updateTails() { (1 until tailArray.size).forEach { val voorganger = tailArray[it - 1] val huidigeTail = tailArray[it] val diffx = voorganger.x - huidigeTail.x val diffy = voorganger.y - huidigeTail.y if (diffx == 0 || diffy == 0) { if (diffx < -1 || diffx > 1) { huidigeTail.addToX(diffx / 2) } else if (diffy < -1 || diffy > 1) { huidigeTail.addToY(diffy / 2) } } else { if (diffx < -1 || diffx > 1) { huidigeTail.addToX(diffx / 2) huidigeTail.addToY(diffy) } else if (diffy < -1 || diffy > 1) { huidigeTail.addToY(diffy / 2) huidigeTail.addToX(diffx) } } if (it == tailArray.lastIndex) { tailList.add(Coordinate(huidigeTail.x, huidigeTail.y)) } } }*/ private fun moveHead(knopen: Int): Int { val tailArray = Array(knopen) { Coordinate() } motionList.map { motion -> repeat(motion.steps) { tailArray[0] = tailArray[0].move(motion.direction) tailArray.indices.windowed(2, 1) { (head, tail) -> if (!tailArray[head].touches(tailArray[tail])) { tailArray[tail] = tailArray[tail].moveTowards(tailArray[head]) } } tailList += tailArray.last() } } return tailList.distinct().count() } enum class Direction(val firstLetter: Char) { RIGHT('R'), LEFT('L'), UP('U'), DOWN('D'); companion object { fun withFirstLetter(value: Char) = Direction.values().first { it.firstLetter == value } } } data class Coordinate(var x: Int = 0, var y: Int = 0) { fun move(direction: Direction): Coordinate = when (direction) { Direction.RIGHT -> copy(x = x + 1) Direction.LEFT -> copy(x = x - 1) Direction.UP -> copy(y = y + 1) Direction.DOWN -> copy(y = y - 1) } fun touches(other: Coordinate): Boolean = (x - other.x).absoluteValue <= 1 && (y - other.y).absoluteValue <= 1 fun moveTowards(other: Coordinate): Coordinate = Coordinate( (other.x - x).sign + x, (other.y - y).sign + y ) } data class Motion(val direction: Direction, val steps: Int) }
0
Kotlin
0
0
b5de21ed7ab063067703e4adebac9c98920dd51e
3,638
AoC2022
Apache License 2.0
src/main/kotlin/year2015/Day06.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2015 import utils.Point2D import kotlin.math.max class Day06 { fun part1(input: String) = solution( input, mapOf( "turn on " to { _: Int -> 1 }, "turn off " to { _: Int -> 0 }, "toggle " to { i: Int -> 1 - i }, ) ) fun part2(input: String) = solution( input, mapOf( "turn on " to { i: Int -> i + 1 }, "turn off " to { i: Int -> max(0, i - 1) }, "toggle " to { i: Int -> i + 2 }, ) ) fun solution(input: String, rules: Map<String, (Int) -> Int>) = MutableList(1000) { MutableList(1000) { 0 } }.apply { input.lines().map { line -> rules.entries.find { (key, _) -> line.startsWith(key) } ?.let { (key, value) -> val (from, to) = line.substringAfter(key).split(" through ").map(Point2D::parse) for (x in from.x..to.x) { for (y in from.y..to.y) { this[x][y] = value(this[x][y]) } } } } }.flatten().sum() }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,200
aoc-2022
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/BestTimeToBuyAndSellStockIi.kt
faniabdullah
382,893,751
false
null
//You are given an integer array prices where prices[i] is the price of a given //stock on the iᵗʰ day. // // On each day, you may decide to buy and/or sell the stock. You can only hold //at most one share of the stock at any time. However, you can buy it then //immediately sell it on the same day. // // Find and return the maximum profit you can achieve. // // // Example 1: // // //Input: prices = [7,1,5,3,6,4] //Output: 7 //Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = //5-1 = 4. //Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. // //Total profit is 4 + 3 = 7. // // // Example 2: // // //Input: prices = [1,2,3,4,5] //Output: 4 //Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = //5-1 = 4. //Total profit is 4. // // // Example 3: // // //Input: prices = [7,6,4,3,1] //Output: 0 //Explanation: There is no way to make a positive profit, so we never buy the //stock to achieve the maximum profit of 0. // // // // Constraints: // // // 1 <= prices.length <= 3 * 10⁴ // 0 <= prices[i] <= 10⁴ // // Related Topics Array Dynamic Programming Greedy 👍 5910 👎 2234 package leetcodeProblem.leetcode.editor.en class BestTimeToBuyAndSellStockIi { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun maxProfit(prices: IntArray): Int { var maxProfit = 0 for (i in 1 until prices.size) { maxProfit = maxOf(maxProfit, prices[i] - prices[i - 1] + maxProfit) } return maxProfit } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,832
dsa-kotlin
MIT License
src/main/kotlin/com/gitTraining/Fibbonaci.kt
samjdixon
278,647,267
true
{"Kotlin": 4663}
package com.gitTraining fun computeFibbonaciNumber(position: Int, recursion: Boolean = false): Int { if (recursion) return recursiveFibbonachi(position) if (position == 0) return 0 if (position < 0) { val positionIsOdd = position % 2 == -1 return if (positionIsOdd) computeFibbonaciNumber(-position) else (computeFibbonaciNumber(-position) * -1) } if (position == 1 || position == 2) return 1 var smallFibbonachiNumber = 1 var largeFibbonachiNumber = 1 var currentPosition = 2 while (currentPosition < position) { val nextFibbonachiNumber = smallFibbonachiNumber + largeFibbonachiNumber smallFibbonachiNumber = largeFibbonachiNumber largeFibbonachiNumber = nextFibbonachiNumber currentPosition ++ } return largeFibbonachiNumber } fun computeFibbonachiArray(start: Int, end: Int, efficient: Boolean = false): List<Int> { if (!efficient) return (start..end).map { computeFibbonaciNumber(it) } if (start > end) return listOf() if (start == end) return listOf(computeFibbonaciNumber(start)) val output = mutableListOf(computeFibbonaciNumber(start), computeFibbonaciNumber(start + 1)) (2..(end-start)).forEach { output.add(output[it-2] + output[it-1]) } return output } fun recursiveFibbonachi(initialPosition: Int, left: Int = 0, right: Int = 1, position: Int = initialPosition): Int { if (initialPosition == 0) return 0 if (position == 0) return left if (initialPosition > 0) { return recursiveFibbonachi(initialPosition, right, left + right, position - 1) } else { return recursiveFibbonachi(initialPosition, right - left, left, position + 1) } }
0
Kotlin
0
0
c5ab05f71d7015a825144b428c73aa035fe47e88
1,706
git-training
MIT License
src/main/kotlin/io/queue/PerfectSquares.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.queue import java.util.* import kotlin.math.pow // https://leetcode.com/explore/learn/card/queue-stack/231/practical-application-queue/1371/ class PerfectSquares { fun execute(input: Int): Int { val stack = Stack<List<Int>>() var steps = 1 stack.add(listOf(input)) val perfectNumbers = generatePerfectSquareNumbers(input) while (stack.isNotEmpty()) { stack.pop().flatMap { current -> perfectNumbers.map { squareNumber -> when { current - squareNumber == 0 -> return steps current - squareNumber < 0 -> null else -> current - squareNumber } }.filterNotNull() }.let { newGeneration -> if (newGeneration.isNotEmpty()) stack.push(newGeneration) } steps += 1 } return -1 } private fun generatePerfectSquareNumbers(maximum: Int) = (1..maximum).filter { number -> (1..number).firstOrNull { it.toDouble().pow(2).toInt() == number } != null } } private data class NumbersWrapper(val value: Int, val values: List<Int>) { fun generateNewValue(minus: Int) = NumbersWrapper(value - minus, values + minus) } fun main() { val perfectSquares = PerfectSquares() println("${perfectSquares.execute(496)}") }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,258
coding
MIT License
src/commonMain/kotlin/com/dogeweb/fuzzymatcher/function/ScoringFunction.kt
dogeweb
558,010,459
false
{"Kotlin": 106948}
package com.dogeweb.fuzzymatcher.function import com.dogeweb.fuzzymatcher.domain.Match import com.dogeweb.fuzzymatcher.domain.Score import kotlin.math.pow /** * A functional interface to get a score between 2 Match objects */ typealias ScoringFunction = (Match<*>, List<Score>) -> Score object ScoringFunctions { /** * For all the childScores in a Match object it calculates the average. * To get a balanced average for 2 Match object which do not have same number of childScores. * It gives a score of 0.5 for missing children * * @return the scoring function for Average */ val averageScore: ScoringFunction = { match, childScores -> val numerator = childScores.sumOfResult + match.unmatchedChildScore val denominator = match.childCount Score(numerator / denominator, match) } /** * For all the childScores in a Match object it calculates the average. * Average is calculated with a total of child scored divided by the child count * * @return the scoring function for Simple Average */ val simpleAverageScore: ScoringFunction = { match, childScores -> val numerator = childScores.sumOfResult val denominator = match.childCount Score(numerator / denominator, match) } /** * Follows the same rules as "getAverageScore" and in addition applies weights to children. * It can be used for aggregating Elements to Documents, where weights can be provided at Element level * * @return the scoring function for WeightedAverage */ val weightedAverageScore: ScoringFunction = { match, childScores -> val numerator = (childScores.sumOfWeightedResult + match.unmatchedChildScore) val denominator = (childScores.sumOfWeights + match.childCount - childScores.size) Score(numerator / denominator, match) } /** * Follows the same rules as "getAverageScore", and in addition if more than 1 children match above a score of 0.9, * it exponentially increases the overall score by using a 1.5 exponent * * @return the scoring function for ExponentialAverage */ val exponentialAverageScore: ScoringFunction = { match, childScores -> val perfectMatchedElements = childScores.perfectMatchedElement if (perfectMatchedElements.size > 1 && perfectMatchedElements.sumOfResult > 1) { val numerator = (perfectMatchedElements.sumOfResult.exponentiallyIncreasedValue + childScores.nonPerfectMatchedElement.sumOfResult + match.unmatchedChildScore) val denominator = (perfectMatchedElements.size.toDouble().exponentiallyIncreasedValue + match.childCount - perfectMatchedElements.size) Score(numerator / denominator, match) } else averageScore(match, childScores) }// Apply Exponent if match elements > 1 /** * This is the default scoring used to calculate the Document score by aggregating the child Element scores. * This combines the benefits of weights and exponential increase when calculating the average scores. * * @return the scoring function for ExponentialWeightedAverage */ val exponentialWeightedAverageScore: ScoringFunction = { match, childScores -> val perfectMatchedElements = childScores.perfectMatchedElement // Apply Exponent if match elements > 1 if (perfectMatchedElements.size > 1 && perfectMatchedElements.sumOfWeightedResult > 1) { val notPerfectMatchedElements = childScores.nonPerfectMatchedElement val numerator = (perfectMatchedElements.sumOfWeightedResult.exponentiallyIncreasedValue + notPerfectMatchedElements.sumOfWeightedResult + match.unmatchedChildScore) val denominator = ((perfectMatchedElements.sumOfWeights.exponentiallyIncreasedValue + notPerfectMatchedElements.sumOfWeights + match.childCount) - childScores.size) Score(numerator / denominator, match) } else weightedAverageScore(match, childScores) } private inline val List<Score>.sumOfWeightedResult: Double get() = sumOf { it.result * it.match.weight } private inline val List<Score>.sumOfResult: Double get() = sumOf { it.result } private inline val List<Score>.sumOfWeights: Double get() = sumOf { it.match.weight } private inline val Double.exponentiallyIncreasedValue: Double get() = pow(EXPONENT) private inline val List<Score>.nonPerfectMatchedElement: List<Score> get() = filter { it.result < EXPONENTIAL_INCREASE_THRESHOLD } private inline val List<Score>.perfectMatchedElement: List<Score> get() = filter { it.result >= EXPONENTIAL_INCREASE_THRESHOLD } private inline val Match<*>.childCount: Double get() = data.getChildCount(matchedWith).toDouble() private inline val Match<*>.unmatchedChildScore: Double get() = DEFAULT_UNMATCHED_CHILD_SCORE * data.getUnmatchedChildCount(matchedWith) private const val EXPONENT = 1.5 private const val EXPONENTIAL_INCREASE_THRESHOLD = 0.9 private const val DEFAULT_UNMATCHED_CHILD_SCORE = 0.5 }
0
Kotlin
0
0
1d636b9b941441d92881ad36b149b3f14b2df9bd
5,515
fuzzy-matcher-kt
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2023/Day3.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2023 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.XY import com.s13g.aoc.resultFrom /** * --- Day 3: Gear Ratios --- * https://adventofcode.com/2023/day/3 */ class Day3 : Solver { override fun solve(lines: List<String>): Result { val schematic = Schematic(lines) val parts = extractParts(schematic) val gearsToNums = mapGearsToNums(parts) val answerB = gearsToNums .filter { it.value.size == 2 } .map { it.value[0].num * it.value[1].num } .sum() return resultFrom(parts.sumOf { it.num }, answerB) } private fun mapGearsToNums(parts: List<Part>): Map<XY, List<Part>> { val result = mutableMapOf<XY, MutableList<Part>>() for (part in parts) { for (sym in part.syms.filter { it.value == '*' }) { result.putIfAbsent(sym.key, mutableListOf()) result[sym.key]!!.add(part) } } return result } private fun extractParts(schematic: Schematic): MutableList<Part> { val result = mutableListOf<Part>() class TempResult { var buf = "" var symbols = mutableMapOf<XY, Char>() fun addToResult() { result.add(Part(buf.toInt(), symbols)) } fun isPart() = symbols.isNotEmpty() } var tr: TempResult for ((y, line) in schematic.lines.withIndex()) { tr = TempResult() for ((x, ch) in line.withIndex()) { if (ch.isDigit()) { tr.buf += ch tr.symbols.putAll(schematic.getSurroundingSymbols(x, y)) } if (!ch.isDigit() || x == line.indices.last) { if (tr.buf.isNotBlank() && tr.isPart()) { tr.addToResult() } tr = TempResult() } } } return result } data class Part(val num: Int, val syms: Map<XY, Char>) data class Schematic(val lines: List<String>) private fun Schematic.getSurroundingSymbols(x: Int, y: Int): Map<XY, Char> { val result = mutableMapOf<XY, Char>() for (yy in (y - 1).coerceAtLeast(0)..(y + 1).coerceAtMost(lines.size - 1)) { for (xx in (x - 1).coerceAtLeast(0)..(x + 1).coerceAtMost(lines[yy].length - 1)) { val ch = lines[yy][xx] if (!ch.isDigit() && ch != '.') { result[XY(xx, yy)] = ch } } } return result } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,295
euler
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/BinaryTreePruning.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 814. Binary Tree Pruning * @see <a href="https://leetcode.com/problems/binary-tree-pruning/">Source</a> */ fun interface BinaryTreePruning { fun pruneTree(root: TreeNode?): TreeNode? } class BinaryTreePruningRecursion : BinaryTreePruning { override fun pruneTree(root: TreeNode?): TreeNode? { return if (containsOne(root)) root else null } private fun containsOne(node: TreeNode?): Boolean { if (node == null) return false // Check if any node in the left subtree contains a 1. val leftContainsOne = containsOne(node.left) // Check if any node in the right subtree contains a 1. val rightContainsOne = containsOne(node.right) // If the left subtree does not contain a 1, prune the subtree. if (!leftContainsOne) node.left = null // If the right subtree does not contain a 1, prune the subtree. if (!rightContainsOne) node.right = null // Return true if the current node, its left or right subtree contains a 1. return node.value == 1 || leftContainsOne || rightContainsOne } } class BinaryTreePruningSimple : BinaryTreePruning { override fun pruneTree(root: TreeNode?): TreeNode? { if (root == null) return null root.left = pruneTree(root.left) root.right = pruneTree(root.right) if (root.left == null && root.right == null && root.value == 0) return null return root } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,095
kotlab
Apache License 2.0
src/Day10.kt
fmborghino
573,233,162
false
{"Kotlin": 60805}
fun main() { @Suppress("unused") fun log(message: Any?) { println(message) } fun scanAndDoStuff(input: List<String>, doStuff: (Int, Int) -> Unit) { var cycle = 1 var x = 1 // shove an extra noop before every addx to make the cycle counts simpler input.flatMap { if (it == "noop") listOf(it) else listOf("noop", it) }.forEach { line -> // log(" $cycle -> $line -> $x") when { line.startsWith("noop") -> cycle++ line.startsWith("addx") -> { val value = line.split(" ")[1].toInt() x += value cycle++ } } doStuff(cycle, x) } } fun part1(input: List<String>): Int { var result = 0 scanAndDoStuff(input) { cycle, x -> if (cycle == 20 || (cycle - 20) % 40 == 0) { // POST darn this is the same as cycle % 40 == 20 val signalStrength = cycle * x result += signalStrength // log("* $cycle -> $x -> $signalStrength -> $result") } } return result } fun part2(input: List<String>): String { val crt = MutableList(241) { ' ' } scanAndDoStuff(input) { cycle, x -> val offsetX = (cycle - 1) % 40 crt[cycle - 1] = if (x in offsetX -1 .. offsetX + 1) '#' else ' ' } return crt.joinToString("").chunked(40).joinToString("\n") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test.txt") check(part1(testInput) == 13140) // check(part2(testInput) == 999) val input = readInput("Day10.txt") println(part1(input)) check(part1(input) == 10760) println(part2(input)) // check(part2(input) == 99999) }
0
Kotlin
0
0
893cab0651ca0bb3bc8108ec31974654600d2bf1
1,892
aoc2022
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day08.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2022 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution import org.jetbrains.kotlinx.multik.api.mk import org.jetbrains.kotlinx.multik.api.zeros import org.jetbrains.kotlinx.multik.ndarray.data.* import org.jetbrains.kotlinx.multik.ndarray.operations.any import kotlin.math.max open class Part8A : PartSolution() { internal lateinit var wood: Wood override fun parseInput(text: String) { val lines = text.trim().split("\n") val trees = mk.zeros<Int>(lines.size, lines[0].length) lines.forEachIndexed { y, line -> line.forEachIndexed { x, c -> trees[y, x] = c.digitToInt() } } wood = Wood(trees) } override fun compute(): Int { var visible = 0 for (y in 0..<wood.getHeight()) { for (x in 0..<wood.getWidth()) { visible += if (wood.isVisible(x, y)) 1 else 0 } } return visible } override fun getExampleAnswer(): Int { return 21 } data class Wood(val trees: D2Array<Int>) { fun getWidth(): Int { return trees.shape[1] } fun getHeight(): Int { return trees.shape[0] } private fun getRow(y: Int, start: Int = 0, end: Int = getWidth()): MultiArray<Int, D1> { return trees[y, start..<end] } private fun getCol(x: Int, start: Int = 0, end: Int = getHeight()): MultiArray<Int, D1> { return trees[start..<end, x] } fun isVisible(x: Int, y: Int): Boolean { if (x == 0 || x == getWidth() || y == 0 || y == getWidth()) { return true } val tree = trees[y][x] var larger = 4 if (getRow(y, x + 1).any { it >= tree }) { larger -= 1 } if (getRow(y, end = x).any { it >= tree }) { larger -= 1 } if (getCol(x, y + 1).any { it >= tree }) { larger -= 1 } if (getCol(x, end = y).any { it >= tree }) { larger -= 1 } return larger > 0 } fun getDistance(x: Int, y: Int): Iterable<Int> { val distance = mutableListOf(getWidth() - x - 1, x, getHeight() - y - 1, y) val tree = trees[y][x] for (i in x + 1..<getWidth()) { if (trees[y][i] >= tree) { distance[0] = i - x break } } for (i in x - 1 downTo 0) { if (trees[y][i] >= tree) { distance[1] = x - i break } } for (i in y + 1..<getHeight()) { if (trees[i][x] >= tree) { distance[2] = i - y break } } for (i in y - 1 downTo 0) { if (trees[i][x] >= tree) { distance[3] = y - i break } } return distance } } } class Part8B : Part8A() { override fun compute(): Int { var scenicScore = 0 for (y in 1..<wood.getHeight() - 1) { for (x in 1..<wood.getWidth() - 1) { val distance = wood.getDistance(x, y) val score = distance.fold(1, Int::times) scenicScore = max(scenicScore, score) } } return scenicScore } override fun getExampleAnswer(): Int { return 8 } } fun main() { Day(2022, 8, Part8A(), Part8B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
3,681
advent-of-code-kotlin
MIT License
src/main/kotlin/roundC2021/rockpaperscissors-analysis.kt
kristofersokk
422,727,227
false
null
package roundC2021 import kotlin.random.Random.Default.nextDouble fun main() { // prod() // test(40, 40) // test(40, 20) // test(40, 4) // test(40, 0) // val seq1 = RPS.getListFromString("RSP".repeat(20)) // testSequence(seq1, 40, 40) // testSequence(seq1, 40, 20) // testSequence(seq1, 40, 4) // testSequence(seq1, 40, 0) printSequences() } private fun prod() { val days = readLine()!!.toInt() readLine() (1..days).forEach { dayIndex -> val (W, E) = readLine()!!.split(" ").map { it.toInt() } val chance = getChance(W, E) val (mySequence) = calculateSequencesFromChanceLimit(chance) // val mySequence = RPS.getListFromString("RSP".repeat(20)) println("Case #$dayIndex: ${mySequence.joinToString("")}") } } private fun getChance(W: Int, E: Int) = when (E) { W -> 0.168 W / 2 -> 0.522 W / 10 -> 0.668 0 -> 0.816 else -> 0.5 } private fun printSequences() { intArrayOf(40, 20, 4, 0).forEach { val (mySequence) = calculateSequencesFromChanceLimit(getChance(40, it)) println("E: $it") println(mySequence.joinToString(separator = "")) } } private fun test(W: Int, E: Int) { val chanceLowers = mutableListOf<Int>() val averageScores = mutableListOf<Double>() (0 until 1000 step 2).forEach { chanceLower -> val chance = chanceLower / 1000.0 val averageScore = (1..1000).map { val (mine, opponents) = calculateSequencesFromChanceLimit(chance) calculateScore(mine, opponents, W, E) }.average() chanceLowers.add(chanceLower) averageScores.add(averageScore) if (chanceLower == 0) { println(averageScore) } if (chanceLower % 10 == 0) print("\r${chanceLower}/1000") } println() val bestChanceLimit = chanceLowers.zip(averageScores).maxByOrNull { pair -> pair.second }!!.first / 1000.0 println("Best chance limit: $bestChanceLimit") println("N = (G,H)") println("G = [${chanceLowers.joinToString(separator = ",")}]") println("H = [${averageScores.joinToString(separator = ",")}]") } private fun testSequence(sequence: List<RPS>, W: Int, E: Int) { val averageScore = (1..10000).map { val opponents = calculateOpponentsSequenceFromMySequence(sequence) calculateScore(sequence, opponents, W, E) }.average() println(sequence.joinToString(separator = "")) println(calculateOpponentsSequenceFromMySequence(sequence).joinToString(separator = "")) println(averageScore) } private fun calculateOpponentsSequenceFromMySequence(mine: List<RPS>): List<RPS> { val opponents = (1..60).map { roundIndex -> chooseFromMapWithChances( RPS.values().associate { it.enemy to (if (roundIndex == 1) 0.33 else mine.subList(0, roundIndex - 1) .count { myChoice -> myChoice == it } / (roundIndex - 1).toDouble()) } ) } return opponents } private fun calculateSequencesFromChanceLimit(chance: Double): Pair<List<RPS>, List<RPS>> { val mine = mutableListOf<RPS>() val opponents = mutableListOf<RPS>() var myCurrentChoice = RPS.R (1..60).forEach { roundIndex -> if (roundIndex > 1 && mine.count { it == myCurrentChoice } / mine.size.toDouble() > chance) { myCurrentChoice = myCurrentChoice.target } mine.add(myCurrentChoice) opponents.add(chooseFromMapWithChances( RPS.values().associate { it.enemy to mine.count { myChoice -> myChoice == it } / mine.size.toDouble() } )) } return mine to opponents } private fun <T> chooseFromMapWithChances(map: Map<T, Double>): T { val pairs = map.entries.toList().map { it.key to it.value } val runningTotals = pairs.runningFold(0.0) { prev, pair -> prev + pair.second } .drop(1).mapIndexed { index, value -> value to pairs[index].first } val rand = nextDouble() for (pair in runningTotals) { val (total, choice) = pair if (rand < total) { return choice } } return pairs.first().first } private fun calculateScore(mine: List<RPS>, opponents: List<RPS>, W: Int, E: Int) = mine.zip(opponents).sumOf { (myChoice, opponentsChoice) -> if (myChoice == opponentsChoice) E else if (myChoice.target == opponentsChoice) W else 0 } private enum class RPS { R, P, S; val target: RPS get() = when (this) { P -> R R -> S S -> P } val enemy: RPS get() = when (this) { P -> S S -> R R -> P } companion object { fun getListFromString(s: String) = s.map { when (it) { 'P' -> P 'R' -> R 'S' -> S else -> P } } } }
0
Kotlin
0
0
3ebd59df60ee425b7af86a147f49361dc56ee38d
5,058
Google-coding-competitions
MIT License
src/main/kotlin/g0101_0200/s0120_triangle/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0101_0200.s0120_triangle // #Medium #Array #Dynamic_Programming #Algorithm_I_Day_12_Dynamic_Programming // #Dynamic_Programming_I_Day_13 #Udemy_Dynamic_Programming // #2022_10_08_Time_194_ms_(97.87%)_Space_40_MB_(71.28%) class Solution { fun minimumTotal(triangle: List<List<Int>>): Int { if (triangle.isEmpty()) { return 0 } val dp = Array(triangle.size) { IntArray(triangle[triangle.size - 1].size) } for (temp in dp) { temp.fill(-10001) } return dfs(triangle, dp, 0, 0) } private fun dfs(triangle: List<List<Int>>, dp: Array<IntArray>, row: Int, col: Int): Int { if (row >= triangle.size) { return 0 } if (dp[row][col] != -10001) { return dp[row][col] } val sum = ( triangle[row][col] + Math.min( dfs(triangle, dp, row + 1, col), dfs(triangle, dp, row + 1, col + 1) ) ) dp[row][col] = sum return sum } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,083
LeetCode-in-Kotlin
MIT License
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day23.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.max import fr.outadoc.aoc.scaffold.readDayInput class Day23 : Day<Long> { /** * @param cups map of cup value to next cup value in the cyclic list */ private data class State(val cups: MutableMap<Int, Int>, val currentCup: Int) { val range: IntRange = 1..cups.size } private val input: List<Int> = readDayInput() .lines() .first() .map { it.toString().toInt() } private fun List<Int>.toQuickMap(): Map<Int, Int> = mapIndexed { index, cup -> val next = if (index == size - 1) this[0] else this[index + 1] cup to next }.toMap() private val step1State = State( cups = input.toQuickMap().toMutableMap(), currentCup = input.first() ) private val step2State = State( cups = (input + (input.max() + 1..1_000_000)).toQuickMap().toMutableMap(), currentCup = input.first() ) private fun State.next(): State { // Pick up 3 cups after the current cup val c1 = cups.getValue(currentCup) val c2 = cups.getValue(c1) val c3 = cups.getValue(c2) val rangeForCupLowerThanCurrent = (currentCup - 1) downTo range.first val rangeForHighestCup = range.last downTo range.last - 3 // Select the destination cup val destinationCup: Int = rangeForCupLowerThanCurrent.firstOrNull { cup -> cup != c1 && cup != c2 && cup != c3 } ?: rangeForHighestCup.first { cup -> cup != c1 && cup != c2 && cup != c3 } // Move cups to the right position by inserting c1, c2, c3 between destinationCup and its next cups.getValue(destinationCup).let { oldDestinationNextCup -> cups[currentCup] = cups.getValue(c3) cups[destinationCup] = c1 cups[c3] = oldDestinationNextCup } return copy(currentCup = cups.getValue(currentCup)) } private fun State.nthIteration(n: Int): State { return (0 until n).fold(this) { state, _ -> state.next() } } private fun Map<Int, Int>.toList(startingCup: Int): List<Int> { var cup: Int = getValue(startingCup) val list = mutableListOf<Int>() do { list.add(cup) cup = getValue(cup) } while (cup != startingCup) return list } private fun State.toStateString(): String { return cups.toList(startingCup = 1).joinToString(separator = "") } override fun step1(): Long { return step1State .nthIteration(100) .toStateString() .toLong() } override fun step2(): Long { return step2State .nthIteration(10_000_000) .cups.toList(startingCup = 1) .take(2) .fold(1L) { acc, cup -> acc * cup.toLong() } } override val expectedStep1: Long = 53248976 override val expectedStep2: Long = 418819514477 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
3,069
adventofcode
Apache License 2.0
src/test/kotlin/Day21.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe /* --- Day 21: Allergen Assessment --- See https://adventofcode.com/2020/day/21 */ fun List<FoodInformation>.findIngredientsWithoutAllergens(): List<String> { val allergensUniqueInIngredients = findAllergensUniqueInIngredients() val ingredientsWithAllergens = allergensUniqueInIngredients.values.toSet() return flatMap { foodInformation -> foodInformation.ingredients.filter { it !in ingredientsWithAllergens } } } fun List<FoodInformation>.findAllergensUniqueInIngredients(): Map<String, String> { val allAllergens = getAllAllergens() val allergensInIngredients = findAllergensInIngredients(allAllergens) val result = mutableMapOf<String, String>() val alreadyFoundIngredient = mutableSetOf<String>() val allergensAlreadyChecked = mutableSetOf<String>() while((allAllergens - allergensAlreadyChecked).isNotEmpty()) { var somethingFound = false allAllergens.map { allergen -> if (allergen !in allergensAlreadyChecked) { val ingredients = allergensInIngredients[allergen]!! val remainingIngredients = ingredients - alreadyFoundIngredient if (remainingIngredients.isEmpty()) { println("No ingredients for allergen=$allergen") } else if (remainingIngredients.size == 1) { val ingredient = remainingIngredients.first() result[allergen] = ingredient alreadyFoundIngredient += ingredient allergensAlreadyChecked += allergen somethingFound = true } } } if (! somethingFound) { println("Nothing more found, remaining allergens=${allAllergens - allergensAlreadyChecked}") break } } return result } fun List<FoodInformation>.findAllergensInIngredients(allAllergens: Set<String>): Map<String, Set<String>> = allAllergens.map { allergen -> val ingredients = filter { foodInformation -> foodInformation.allergens.contains(allergen) } .map { it.ingredients} .reduce { acc, ingredients -> acc.intersect(ingredients)} allergen to ingredients }.toMap() fun List<FoodInformation>.getAllAllergens(): Set<String> = flatMap { foodInformation -> foodInformation.allergens }.toSet() fun parseFoodLines(foodLinesString: String): List<FoodInformation> = foodLinesString.split("\n").map { parseIngredients(it) } fun parseIngredients(ingredientsString: String): FoodInformation { val parts = ingredientsString.split("(contains") val ingredients = parts[0].split(" ") .filter { it.isNotBlank() }.map { it.trim() }.toSet() val allergens = parts[1].dropLast(1).split(", ") .filter { it.isNotBlank() }.map { it.trim() }.toSet() return FoodInformation(ingredients, allergens) } data class FoodInformation(val ingredients: Set<String>, val allergens: Set<String>) fun List<FoodInformation>.ingredientsSortedByAllergens(): List<String> { val allergensUniqueInIngredients = findAllergensUniqueInIngredients() return allergensUniqueInIngredients.entries.sortedBy { it.key }.map { it.value } } class Day21_Part1 : FunSpec({ context("parse ingredients") { val foodInformationString = "mxmxvkd kfcds sqjhc nhms (contains dairy, fish)" val foodInformation = parseIngredients(foodInformationString) test("should have parsed incredients and allergenes for one food line") { foodInformation.ingredients shouldBe setOf("mxmxvkd", "kfcds", "sqjhc", "nhms") foodInformation.allergens shouldBe setOf("dairy", "fish") } } val foodLinesString = """ mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish) """.trimIndent() val foodLines = parseFoodLines(foodLinesString) context("parse food lines") { test("should have parsed all food lines") { foodLines.size shouldBe 4 foodLines[3] shouldBe FoodInformation(setOf("sqjhc", "mxmxvkd", "sbzzf"), setOf("fish")) } } context("get all allergens") { val allAllergens = foodLines.getAllAllergens() allAllergens shouldBe setOf("dairy", "fish", "soy") context("find ingredients with allergens") { val allergensInIngredients = foodLines.findAllergensInIngredients(allAllergens) allergensInIngredients shouldBe mapOf( "dairy" to setOf("mxmxvkd"), "fish" to setOf("mxmxvkd", "sqjhc"), "soy" to setOf("sqjhc", "fvjkl"), ) } } context("ingredient with allergen") { val allergensUniqueInIngredients = foodLines.findAllergensUniqueInIngredients() allergensUniqueInIngredients shouldBe mapOf( "dairy" to "mxmxvkd", "fish" to "sqjhc", "soy" to "fvjkl", ) } context("ingredients without allergen") { val withoutAllergen = foodLines.findIngredientsWithoutAllergens() withoutAllergen shouldBe listOf("kfcds", "nhms", "trh", "sbzzf", "sbzzf") withoutAllergen.size shouldBe 5 } }) class Day21_Part1_Exercise: FunSpec({ val input = readResource("day21Input.txt")!! val foodLines = parseFoodLines(input) val allergensUniqueInIngredients = foodLines.findAllergensUniqueInIngredients() test("should have found ingredients for all allergens") { allergensUniqueInIngredients.keys.toSet() shouldBe foodLines.getAllAllergens() } val withoutAllergen = foodLines.findIngredientsWithoutAllergens() val solution = withoutAllergen.size test("should have found the right number of ingredients without allergens") { solution shouldBe 1679 } }) class Day21_Part2: FunSpec({ val foodLinesString = """ mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish) """.trimIndent() val foodLines = parseFoodLines(foodLinesString) val ingredientsWithAllergens = foodLines.ingredientsSortedByAllergens() val ingredientsWithAllergensString = ingredientsWithAllergens.joinToString(",") test("should have created the correct ingredients string") { ingredientsWithAllergensString shouldBe "mxmxvkd,sqjhc,fvjkl" } }) class Day21_Part2_Exercise: FunSpec({ val input = readResource("day21Input.txt")!! val foodLines = parseFoodLines(input) val ingredientsWithAllergens = foodLines.ingredientsSortedByAllergens() val ingredientsWithAllergensString = ingredientsWithAllergens.joinToString(",") test("should have created the correct ingredients string") { ingredientsWithAllergensString shouldBe "lmxt,rggkbpj,mxf,gpxmf,nmtzlj,dlkxsxg,fvqg,dxzq" } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
7,100
advent_of_code_2020
Apache License 2.0
src/main/kotlin/year2022/Day08.kt
simpor
572,200,851
false
{"Kotlin": 80923}
import AoCUtils.test fun main() { data class Tree(val x: Int, val y: Int, val height: Int, var visible: Boolean = false, var scenic: Int = 0) fun part1(input: String, debug: Boolean = false): Long { val treeMap = input.lines().mapIndexed { y, row -> row.mapIndexed { x, c -> Point(x, y) to Tree(x, y, "$c".toInt()) } }.flatten().toMap().toMutableMap() val maxX = treeMap.keys.map { it.x }.max() val maxY = treeMap.keys.map { it.y }.max() for (x in 0..maxX) { for (y in 0..maxY) { if (x == 0) treeMap[Point(x, y)]?.visible = true if (x == maxX) treeMap[Point(x, y)]?.visible = true if (y == 0) treeMap[Point(x, y)]?.visible = true if (y == maxY) treeMap[Point(x, y)]?.visible = true } } for (x in 0..maxX) { var edge = treeMap[Point(x, 0)]!! for (y in 0..maxY) { val current = treeMap[Point(x, y)]!! if (current.height > edge.height) { current.visible = true edge = current } } } for (x in 0..maxX) { var edge = treeMap[Point(x, maxY)]!! for (y in maxY downTo 0) { val current = treeMap[Point(x, y)]!! if (current.height > edge.height) { current.visible = true edge = current } } } for (y in 0..maxY) { var edge = treeMap[Point(0, y)]!! for (x in 0..maxX) { val current = treeMap[Point(x, y)]!! if (current.height > edge.height) { current.visible = true edge = current } } } for (y in 0..maxY) { var edge = treeMap[Point(maxX, y)]!! for (x in maxX downTo 0) { val current = treeMap[Point(x, y)]!! if (current.height > edge.height) { current.visible = true edge = current } } } return treeMap.values.filter { it.visible }.count().toLong() } fun look(height: Int, trees: MutableList<Int>): Int { if (trees.size == 0) return 0 var t = 0 trees.forEach { h -> if (h >= height) { t++ return t } else { t++ } } return t } fun calcScenic(treeMap: MutableMap<Point, Tree>, tree: Tree, maxX: Int, maxY: Int) { val yInc = mutableListOf<Int>() val yDesc = mutableListOf<Int>() val xInc = mutableListOf<Int>() val xDesc = mutableListOf<Int>() for (y in (tree.y + 1)..maxY) { val current = treeMap[Point(tree.x, y)]!! yInc.add(current.height) } for (y in (tree.y - 1) downTo 0) { val current = treeMap[Point(tree.x, y)]!! yDesc.add(current.height) } for (x in (tree.x + 1)..maxX) { val current = treeMap[Point(x, tree.y)]!! xInc.add(current.height) } for (x in (tree.x - 1) downTo 0) { val current = treeMap[Point(x, tree.y)]!! xDesc.add(current.height) } val xPlus = look(tree.height, xInc) val xMinus = look(tree.height, xDesc) val yMinus = look(tree.height, yDesc) val yPlus = look(tree.height, yInc) tree.scenic = xPlus * xMinus * yMinus * yPlus if (tree.height == 9) { if (tree.y == 29) { // println("hej") } } } fun part2(input: String, debug: Boolean = false): Long { val treeMap = input.lines().mapIndexed { y, row -> row.mapIndexed { x, c -> Point(x, y) to Tree(x, y, "$c".toInt()) } }.flatten().toMap().toMutableMap() val maxX = treeMap.keys.map { it.x }.max() val maxY = treeMap.keys.map { it.y }.max() treeMap.values .filter { (it.y in 1 until maxY) && (it.x in 1 until maxX) } .forEach { tree -> calcScenic(treeMap, tree, maxX, maxY) } val first = treeMap.values.sortedBy { it.scenic }.last() // calcScenic(treeMap, first, maxX, maxY) return first.scenic.toLong() } val testInput = "30373\n" + "25512\n" + "65332\n" + "33549\n" + "35390" val input = AoCUtils.readText("year2022/day08.txt") part1(testInput, false) test Pair(21L, "test 1 part 1") part1(input, false) test Pair(1672L, "part 1") part2(testInput, false) test Pair(8L, "test 2 part 2") part2(input) test Pair(327180L, "part 2") // no 350 }
0
Kotlin
0
0
631cbd22ca7bdfc8a5218c306402c19efd65330b
4,974
aoc-2022-kotlin
Apache License 2.0
src/day14.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import kotlin.system.exitProcess private const val DAY = 14 fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> x.toList() } val input = loadInput(DAY, false, transformer) // println(input) println(solvePart1(input)) println(solvePart2(input)) } // Part 1 private fun solvePart1(input: List<List<Char>>): Int { val new = rollNorth(input) return countNorthLoad(new) } // Part 2 private fun solvePart2(input: List<List<Char>>): Int { var res: List<List<Char>> = input val cycles = mutableMapOf<List<List<Char>>, Int>() var i = 1 do { cycles[res] = i++ res = res.run(::rollNorth).run(::rollWest).run(::rollSouth).run(::rollEast) } while (res !in cycles) val cycleStart = cycles[res]!! // Moreless trial and error - I knew what I wanted, but was hard to write it correctly val cycleLen = cycles.count() - cycleStart + 1 val mod = (1000000000 - cycleStart + 1) % (cycleLen) return countNorthLoad(cycles.filterValues { it == cycleStart + mod }.keys.first()) } fun countNorthLoad(input: List<List<Char>>): Int { var res = 0 for ((y, row) in input.withIndex()) { for (c in row) { if (c == 'O') { res += input.count() - y } } } return res } fun rollNorth(input: List<List<Char>>): List<List<Char>> { val input = input.map { it.toMutableList() } for (x in 0..<input[0].count()) { var empty: Pair<Int, Int>? = null for (y in 0..<input.count()) { val cell = input[y][x] when (cell) { '#' -> empty = null '.' -> if (empty == null) empty = Pair(x, y) 'O' -> { if (empty != null) { input[empty.second][empty.first] = 'O' empty = Pair(empty.first, empty.second + 1) input[y][x] = '.' } } } } } return input } fun rollSouth(input: List<List<Char>>): List<List<Char>> { val input = input.map { it.toMutableList() } for (x in 0..<input.count()) { var empty: Pair<Int, Int>? = null for (y in input.count() - 1 downTo 0) { val cell = input[y][x] when (cell) { '#' -> empty = null '.' -> if (empty == null) empty = Pair(x, y) 'O' -> { if (empty != null) { input[empty.second][empty.first] = 'O' empty = Pair(empty.first, empty.second - 1) input[y][x] = '.' } } } } } return input } fun rollEast(input: List<List<Char>>): List<List<Char>> { val input = input.map { it.toMutableList() } for (y in 0..<input.count()) { var empty: Pair<Int, Int>? = null for (x in input[0].count() - 1 downTo 0) { val cell = input[y][x] when (cell) { '#' -> empty = null '.' -> if (empty == null) empty = Pair(x, y) 'O' -> { if (empty != null) { input[empty.second][empty.first] = 'O' empty = Pair(empty.first - 1, empty.second) input[y][x] = '.' } } } } } return input } fun rollWest(input: List<List<Char>>): List<List<Char>> { val input = input.map { it.toMutableList() } for (y in 0..<input.count()) { var empty: Pair<Int, Int>? = null for (x in 0..<input[0].count()) { val cell = input[y][x] when (cell) { '#' -> empty = null '.' -> if (empty == null) empty = Pair(x, y) 'O' -> { if (empty != null) { input[empty.second][empty.first] = 'O' empty = Pair(empty.first + 1, empty.second) input[y][x] = '.' } } } } } return input }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
4,315
aoc2023
MIT License
Day_09/Solution_Part2.kts
0800LTT
317,590,451
false
null
import java.io.File import java.io.BufferedReader import java.math.BigInteger fun File.readData(): Array<BigInteger> = readLines().map { it.toBigInteger() }.toTypedArray() fun isValid(array: Array<BigInteger>, start: Int, end: Int, target: BigInteger) : Boolean { val complementMap = mutableMapOf<BigInteger, BigInteger>() for (i in start..end) { val number = array[i] if (complementMap.containsKey(number)) { return true } val complement: BigInteger = target - number complementMap[complement] = number } return false } fun makePrefixSum(array: Array<BigInteger>, start: Int, end: Int): Array<BigInteger> { val prefixSum = Array<BigInteger>(end - start + 1) { 0.toBigInteger() } for (i in 0..prefixSum.size-1) { if (i == 0) { prefixSum[i] = array[start + i] } else { prefixSum[i] = prefixSum[i-1] + array[start + i] } } return prefixSum } fun subarraySum(array: Array<BigInteger>, start: Int, end: Int, target: BigInteger) { val prefixSum = makePrefixSum(array, start, end) var windowStart = 0 var windowEnd = 0 while (true) { var sum = prefixSum[windowEnd] if (windowStart != windowEnd) sum -= prefixSum[windowStart] if (sum > target) { windowStart++ } else if (sum < target) { windowEnd++ } else { val subarray = array.slice(windowStart+1..windowEnd) println(subarray) val min = subarray.minOrNull()!! val max = subarray.maxOrNull()!! println(min) println(max) println(min + max) return } } } fun main() { val preambleSize = 25 val data = File("input.txt").readData() var preambleStart = 0 for (i in preambleSize until data.size) { val preambleEnd = i - 1 if (!isValid(data, preambleStart, preambleEnd, data[i])) { println(data[i]) subarraySum(data, 0, i-1, data[i]) } preambleStart++ } } main()
0
Kotlin
0
0
191c8c307676fb0e7352f7a5444689fc79cc5b54
1,894
advent-of-code-2020
The Unlicense
src/Day22.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
import java.util.* fun main() { val dr = intArrayOf(0, 1, 0, -1) val dc = intArrayOf(1, 0, -1, 0) val R = 0 val D = 1 val L = 2 val U = 3 fun solve(input: List<String>, wrap: (List<Int>) -> List<Int>): Any { val next = HashMap<List<Int>, List<Int>>() fun go(r: Int, c: Int, d: Int): List<Int> = next.getOrPut(listOf(r, c, d)) { var nr = r + dr[d] var nc = c + dc[d] var nd = d var value = input.getOrNull(nr)?.getOrNull(nc)?.takeIf { it != ' ' } if (value == null) { val wrapped = wrap(listOf(r, c, d)) nr = wrapped[0] nc = wrapped[1] value = input[nr][nc] nd = wrapped[2] } if (value == '#') return@getOrPut listOf(r, c, d) if (value == '.') return@getOrPut listOf(nr, nc, nd) error("No way") } val path = input.last() var posR = 0 var posC = input[0].indexOfFirst { it == '.' } var dir = 0 var at = 0 while (at < path.length) { if (path[at].isDigit()) { var number = 0 while (path.getOrNull(at)?.isDigit() == true) { number = number * 10 + path[at++].digitToInt() } repeat(number) { val (nr, nc, nd) = go(posR, posC, dir) posR = nr posC = nc dir = nd } } else { if (path[at] == 'R') dir++ else dir-- dir = dir.positiveModulo(4) at++ } } return 1000 * (posR + 1) + 4 * (posC + 1) + dir } fun part1(input: List<String>): Any { return solve(input) { (row, col, dir) -> var nextRow = row var nextCol = col while (true) { val nextR = nextRow - dr[dir] val nextC = nextCol - dc[dir] if (input.getOrNull(nextR)?.getOrNull(nextC)?.takeIf { it != ' ' } == null) break nextRow = nextR nextCol = nextC } listOf(nextRow, nextCol, dir) } } fun part2(input: List<String>): Any { val sideSize = (input.size - 2) / 4 val sideMap = """ 012 030 450 600 """.trimIndent().lines() fun rotateRight(p: List<Int>): List<Int> { val (r, c, d) = p val nr = c val nc = sideSize - 1 - r val nd = (d + 1).positiveModulo(4) return listOf(nr, nc, nd) } fun rotateLeft(p: List<Int>) = rotateRight(rotateRight(rotateRight(p))) fun rotateTwice(p: List<Int>) = rotateRight(rotateRight(p)) data class Action( val side: Int, val direction: Int, val nextSide: Int, val transform: (List<Int>) -> List<Int> ) val actions = HashMap<Pair<Int, Int>, Action>() fun registerAction( side: Int, dir: Int, nextSide: Int, transform: (List<Int>) -> List<Int> = { it } ) { val action = Action(side, dir, nextSide, transform) actions[side to dir] = action } registerAction(1, R, 2) registerAction(1, D, 3) registerAction(1, L, 4, ::rotateTwice) registerAction(1, U, 6, ::rotateRight) registerAction(2, R, 5, ::rotateTwice) registerAction(2, D, 3, ::rotateRight) registerAction(2, L, 1) registerAction(2, U, 6) registerAction(3, R, 2, ::rotateLeft) registerAction(3, D, 5) registerAction(3, L, 4, ::rotateLeft) registerAction(3, U, 1) registerAction(4, R, 5) registerAction(4, D, 6) registerAction(4, L, 1, ::rotateTwice) registerAction(4, U, 3, ::rotateRight) registerAction(5, R, 2, ::rotateTwice) registerAction(5, D, 6, ::rotateRight) registerAction(5, L, 4) registerAction(5, U, 3) registerAction(6, R, 5, ::rotateLeft) registerAction(6, D, 2) registerAction(6, L, 1, ::rotateLeft) registerAction(6, U, 4) fun getSide(row: Int, col: Int) = sideMap[row / sideSize][col / sideSize].digitToInt() return solve(input) { (row, col, dir) -> val action = actions[getSide(row, col) to dir]!! val normalized = listOf( (row + dr[dir]).positiveModulo(sideSize), (col + dc[dir]).positiveModulo(sideSize), dir ) val transformed = action.transform(normalized) val sideStart = sideMap.findPos(action.nextSide.digitToChar()) * sideSize val newRow = transformed[0] + sideStart.first val newCol = transformed[1] + sideStart.second val newDir = transformed[2] when (input[newRow][newCol]) { '.' -> listOf(newRow, newCol, newDir) '#' -> listOf(row, col, dir) else -> error("nope") } } } @Suppress("DuplicatedCode") run { val day = String.format("%02d", 22) val testInput = readInput("Day${day}_test") val input = readInput("Day$day") println("Part 1 test - " + part1(testInput)) println("Part 1 real - " + part1(input)) println("---") // println("Part 2 test - " + part2(testInput)) println("Part 2 real - " + part2(input)) } }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
5,682
advent-of-code-2022
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day8.kt
EmRe-One
434,793,519
false
{"Kotlin": 44202}
package tr.emreone.adventofcode.days object Day8 { fun part1(input: List<String>): Int { val regexHex = """(\\x[0-9a-fA-F]{2})""".toRegex() val regexEscaped = """(\\\\|\\")""".toRegex() return input.sumOf { val trimmed = it.substring(1, it.length - 1) val numberOfHex = regexHex.findAll(trimmed).count() val numberOfEscaped = regexEscaped.findAll(trimmed).count() // \x00 -> 4 chars in line -> equals to one char in memory // \\ or \" -> 2 chars in line -> equals to one char in memory val stringLiterals = it.length val numberOfCharsInString = trimmed.length - numberOfHex * 3 - numberOfEscaped stringLiterals - numberOfCharsInString } } fun part2(input: List<String>): Int { val regexHex = """(\\x[0-9a-fA-F]{2})""".toRegex() val regexEscaped = """(\\\\|\\")""".toRegex() return input.sumOf { val trimmed = it.substring(1, it.length - 1) val numberOfHex = regexHex.findAll(trimmed).count() val numberOfEscaped = regexEscaped.findAll(trimmed).count() // \x00 -> 4 chars in line -> adds a \ to the front --> \\x00 // \\ or \" -> 2 chars in line -> adds two \ to the line --> \\\\ or \\\" // "..." -> 2 chars in line -> adds 4 chars to the encoded line --> "\"...\"" val numberOfEncodedLine = trimmed.length + numberOfHex + numberOfEscaped * 2 + 6 val stringLiterals = it.length numberOfEncodedLine - stringLiterals } } }
0
Kotlin
0
0
57f6dea222f4f3e97b697b3b0c7af58f01fc4f53
1,652
advent-of-code-2015
Apache License 2.0
src/Day03.kt
ExpiredMinotaur
572,572,449
false
{"Kotlin": 11216}
fun main() { fun priority(input: Char): Int { return input.code - if (input.code < 97) 38 else 96 } fun part1(input: List<String>): Int { return input.map { it.chunked(it.length / 2).map { s -> s.toSet() } } .map { it[0] intersect it[1] } .sumOf { it.sumOf { item -> priority(item) } } } fun part2(input: List<String>): Int { return input.chunked(3) .map { it[0].toSet() intersect it[1].toSet() intersect it[2].toSet() } .sumOf { priority(it.single()) } } // 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("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
7ded818577737b0d6aa93cccf28f07bcf60a9e8f
857
AOC2022
Apache License 2.0
Algorithm/HackerRank/src/BigNumberMultiplication.kt
chaking
180,269,329
false
{"JavaScript": 118156, "HTML": 97206, "Jupyter Notebook": 93471, "C++": 19666, "Kotlin": 14457, "Java": 8536, "Python": 4928, "Swift": 3893, "Makefile": 2257, "Scala": 890, "Elm": 191, "CSS": 56}
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the plusMinus function below. fun multipliedBigNumbers(number1: String, number2: String): String { return realMul(number1.toCharArray(), number2.toCharArray()).joinToString("") } fun realMul(number1: CharArray, number2: CharArray): CharArray { val results = (0..9).map { mulSingle(number1, it) } results.map { it.joinToString { "" } }.forEach{println(it)} return charArrayOf('3', '4') } fun mulSingle(number1: CharArray, target: Int): CharArray { val result = CharArray(number1.size + 1){ '0' } number1.reversed().forEachIndexed { index, c -> val r = c.toInt() * target if (r > 9) result[index + 1] = 1.toChar() val sum = result[index].toInt() + r % 10 if (sum > 9 ) result[index + 1] = (result[index + 1].toInt() + 1).toChar() result[index] = (result[index].toInt() + sum % 10).toChar() } return result } fun input() { val scan = Scanner(System.`in`) val arr = scan.nextLine().split(" ").map{ it.trim() }.toTypedArray() multipliedBigNumbers(arr[0], arr[1]) } fun auto() { val result = multipliedBigNumbers("4819", "9") println(result) } fun main(args: Array<String>) { // input() auto() }
0
JavaScript
0
0
a394f100155fa4eb1032c09cdc85816b7104804b
1,652
study
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ConstructBinaryTree.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 105. Construct Binary Tree from Preorder and Inorder Traversal * @see <a href="https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal"> * Source</a> */ fun interface ConstructBinaryTree { fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? } class ConstructBinaryTreeRecursion : ConstructBinaryTree { override fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { return helper(0, 0, inorder.size - 1, preorder, inorder) } private fun helper(preStart: Int, inStart: Int, inEnd: Int, preorder: IntArray, inorder: IntArray): TreeNode? { if (preStart > preorder.size - 1 || inStart > inEnd) { return null } val root = TreeNode(preorder[preStart]) var inIndex = 0 // Index of current root in inorder for (i in inStart..inEnd) { if (inorder[i] == root.value) { inIndex = i } } root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder) root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder) return root } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,822
kotlab
Apache License 2.0
src/main/kotlin/g1801_1900/s1838_frequency_of_the_most_frequent_element/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1838_frequency_of_the_most_frequent_element // #Medium #Array #Sorting #Greedy #Binary_Search #Prefix_Sum #Sliding_Window // #Binary_Search_II_Day_9 #2023_06_22_Time_564_ms_(88.89%)_Space_50.8_MB_(100.00%) class Solution { fun maxFrequency(nums: IntArray, k: Int): Int { countingSort(nums) var start = 0 var preSum = 0 var total = 1 for (i in nums.indices) { var length = i - start + 1 var product = nums[i] * length preSum += nums[i] while (product - preSum > k) { preSum -= nums[start++] length-- product = nums[i] * length } total = total.coerceAtLeast(length) } return total } private fun countingSort(nums: IntArray) { var max = Int.MIN_VALUE for (num in nums) { max = max.coerceAtLeast(num) } val map = IntArray(max + 1) for (num in nums) { map[num]++ } var i = 0 var j = 0 while (i <= max) { if (map[i]-- > 0) { nums[j++] = i } else { i++ } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,241
LeetCode-in-Kotlin
MIT License
src/main/kotlin/g0801_0900/s0823_binary_trees_with_factors/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0823_binary_trees_with_factors // #Medium #Array #Hash_Table #Dynamic_Programming // #2023_03_25_Time_298_ms_(100.00%)_Space_45.1_MB_(100.00%)dsecx class Solution { private val dp: MutableMap<Int, Long> = HashMap() private val nums: MutableMap<Int, Int> = HashMap() fun numFactoredBinaryTrees(arr: IntArray): Int { arr.sort() for (i in arr.indices) { nums[arr[i]] = i } var ans: Long = 0 for (i in arr.indices.reversed()) { ans = (ans % MOD + recursion(arr, arr[i], i) % MOD) % MOD } return ans.toInt() } private fun recursion(arr: IntArray, v: Int, idx: Int): Long { if (dp.containsKey(v)) { return dp[v]!! } var ret: Long = 1 for (i in 0 until idx) { val child = arr[i] if (v % child == 0 && nums.containsKey(v / child)) { ret += ( ( recursion(arr, child, nums[arr[i]]!!) % MOD * recursion(arr, v / child, nums[v / child]!!) % MOD ) % MOD ) } } dp[v] = ret return ret } companion object { private const val MOD = 1e9.toInt() + 7 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,395
LeetCode-in-Kotlin
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[110]平衡二叉树.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个二叉树,判断它是否是高度平衡的二叉树。 // // 本题中,一棵高度平衡二叉树定义为: // // // 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。 // // // // // 示例 1: // // //输入:root = [3,9,20,null,null,15,7] //输出:true // // // 示例 2: // // //输入:root = [1,2,2,3,3,null,null,4,4] //输出:false // // // 示例 3: // // //输入:root = [] //输出:true // // // // // 提示: // // // 树中的节点数在范围 [0, 5000] 内 // -104 <= Node.val <= 104 // // Related Topics 树 深度优先搜索 二叉树 // 👍 804 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun isBalanced(root: TreeNode?): Boolean { //后序遍历二叉树 if (root == null) return true return treeHeight(root) != -1 } private fun treeHeight(root: TreeNode?): Int { //递归结束条件 if (root == null) return 0 //逻辑处理 进入下层循环 //左子树 var left = treeHeight(root.left) if (left == -1) return -1 //右子树 var right = treeHeight(root.right) if (right == -1) return -1 //计算高度差 if (Math.abs(left-right) > 1){ return -1 }else{ return Math.max(left,right) +1 } } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,710
MyLeetCode
Apache License 2.0
src/Day01.kt
MixusMinimax
572,717,459
false
{"Kotlin": 2016}
data class Elf(val snacks: List<Int>) { val totalCalories: Int = snacks.sum() } fun main() { // Groups of snacks are separated by a blank line. fun parseElves(lines: List<String>): List<Elf> { val elves = mutableListOf<Elf>() var snacks = mutableListOf<Int>() for (line in lines) { if (line.isBlank()) { elves.add(Elf(snacks)) snacks = mutableListOf() } else { snacks.add(line.toInt()) } } elves.add(Elf(snacks)) return elves } // Return max total calories. fun part1(input: List<String>): Int { val elves = parseElves(input) return elves.maxOf { it.totalCalories } } // return total calories of top three elves. fun part2(input: List<String>): Int { val elves = parseElves(input) return elves.sortedByDescending { it.totalCalories }.take(3).sumOf { it.totalCalories } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") val testResult = part1(testInput) println("Test max value: $testResult") val input = readInput("Day01") val result = part1(input) println("Max value: $result") val result2 = part2(input) println("Max three values: $result2") }
0
Kotlin
0
0
b7066def6aab4d248aa411ea335fab9ce94ba929
1,353
advent-of-code-2022
Apache License 2.0
src/net/sheltem/aoc/y2023/Day13.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 import net.sheltem.common.rotateCockwise suspend fun main() { Day13().run() } class Day13 : Day<Long>(405, 400) { override suspend fun part1(input: List<String>): Long = input.joinToString("\n").split("\n\n").sumOf { it.mirrorSum() } override suspend fun part2(input: List<String>): Long = input.joinToString("\n").split("\n\n").sumOf { it.mirrorSum(1) } } private fun String.mirrorSum(smudgeCount: Int = 0): Long { val mirrorMap = this.split("\n") val horizontal = horizontalMirrorLine(mirrorMap, smudgeCount)?.let { (it + 1) * 100L } ?: 0L val vertical = (if (horizontal == 0L) verticalMirrorLine(mirrorMap, smudgeCount) else null)?.let { it + 1L } ?: 0L return horizontal + vertical } private fun verticalMirrorLine(mirrorMap: List<String>, smudgeCount: Int): Int? = horizontalMirrorLine(mirrorMap.rotateCockwise(), smudgeCount) private fun horizontalMirrorLine(mirrorMap: List<String>, smudgeCount: Int = 0): Int? = mirrorMap .mapIndexedNotNull { index, _ -> val upper = mirrorMap.take(index + 1) val lower = mirrorMap.drop(upper.size) val halves = if (upper.size >= lower.size) { upper.drop(upper.size - lower.size) to lower } else { upper to lower.dropLast(lower.size - upper.size) } val identical = halves.second.reversed().zip(halves.first).sumOf { (stringA, stringB) -> stringA.zip(stringB).count { (charA, charB) -> charA != charB } } == smudgeCount if (index != mirrorMap.size - 1 && identical) index else null }.firstOrNull()
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
1,598
aoc
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem605/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem605 /** * LeetCode page: [605. Can Place Flowers](https://leetcode.com/problems/can-place-flowers/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the size of flowerbed; */ fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean { if (n == 0) return true if (n > flowerbed.size) return false var currPlot = 0 var remainingFlowers = n while (currPlot < flowerbed.size) { val hasFlower = flowerbed[currPlot] == 1 if (hasFlower) { currPlot++ } else { val emptyLength = findEmptyLength(flowerbed, currPlot) val effectiveEmptyLength = computeEffectiveEmptyLength(flowerbed, currPlot, emptyLength) remainingFlowers -= computeMaxFlowers(effectiveEmptyLength) if (remainingFlowers <= 0) return true currPlot += emptyLength + 1 } } return false } private fun findEmptyLength(flowerbed: IntArray, currPlot: Int): Int { var nextNonEmpty = currPlot while (nextNonEmpty < flowerbed.size && flowerbed[nextNonEmpty] == 0) { nextNonEmpty++ } return nextNonEmpty - currPlot } private fun computeEffectiveEmptyLength(flowerbed: IntArray, currPlot: Int, emptyLength: Int): Int { require(emptyLength >= 0) return emptyLength .let { val hasFlowerBefore = flowerbed.getOrNull(currPlot - 1) == 1 if (hasFlowerBefore) it - 1 else it } .let { val hasFlowerAfter = flowerbed.getOrNull(currPlot + emptyLength) == 1 if (hasFlowerAfter) it - 1 else it } } private fun computeMaxFlowers(effectiveEmptyLength: Int): Int { return ((effectiveEmptyLength + 1) shr 1).coerceAtLeast(0) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,955
hj-leetcode-kotlin
Apache License 2.0
src/main/day04/day04.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package day04 import fullyContains import overlapsWith import readInput fun part1(input: List<String>): Int = input.solve(IntRange::fullyContains) fun part2(input: List<String>): Int = input.solve(IntRange::overlapsWith) val regex by lazy { """(\d+)-(\d+),(\d+)-(\d+)""".toRegex() } fun main() { val input = readInput("main/day04/Day04") println(part1(input)) println(part2(input)) } private fun List<String>.solve(check: IntRange.(IntRange) -> Boolean) = map { it.toRangesPairs() }.count { it.first.check(it.second) } fun String.toRangesPairs(): Pair<IntRange, IntRange> { return regex.matchEntire(this)?.destructured?.let { (a, b, c, d) -> a.toInt()..b.toInt() to c.toInt()..d.toInt() } ?: error("invalid line") }
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
756
aoc-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2023/day24/day24.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day24 import biz.koziolek.adventofcode.* import java.time.LocalDateTime fun main() { val inputFile = findInput(object {}) val hails = parseHails(inputFile.bufferedReader().readLines()) println("Hails intersect ${countFutureIntersections(hails, testArea)} times in future in the test area") } val testArea = LongCoord(200_000_000_000_000, 200_000_000_000_000) to LongCoord(400_000_000_000_000, 400_000_000_000_000) data class Hail(val position: LongCoord3d, val velocity: Coord3d, val velocityDelta: Coord3d = Coord3d(0, 0, 0)) { override fun toString() = "$position @ $velocity" } data class Intersection(val position: DoubleCoord, val time1: Double, val time2: Double) private fun Pair<LongCoord, LongCoord>.contains(coord: DoubleCoord): Boolean = coord.x >= first.x && coord.x <= second.x && coord.y >= first.y && coord.y <= second.y fun parseHails(lines: Iterable<String>): List<Hail> = lines.map { line -> val (positionStr, velocityStr) = line.split('@') Hail( position = LongCoord3d.fromString(positionStr), velocity = Coord3d.fromString(velocityStr), ) } fun countFutureIntersections(hails: List<Hail>, testArea: Pair<LongCoord, LongCoord>): Int = generatePairs(hails) .count { (hail1, hail2) -> val intersection = findIntersection(hail1, hail2) intersection != null && intersection.time1 > 0 && intersection.time2 > 0 && testArea.contains(intersection.position) } private fun generatePairs(hails: List<Hail>): Sequence<Pair<Hail, Hail>> = sequence { hails.forEachIndexed { index1, hail1 -> hails.forEachIndexed { index2, hail2 -> if (index2 > index1) { yield(hail1 to hail2) } } } } fun findIntersection(first: Hail, second: Hail): Intersection? { // x1 + vx1 * time = x2 + vx2 * time // y1 + vy1 * time = y2 + vy2 * time // (x1 - x2) / (vx2 - vx1) = time // (y1 - y2) / (vy2 - vy1) = time // ---------------------------------------- // y = ax + b // a1 = vy1 / vx1 // b1 = y1 - a1x1 // a1x + b1 = a2x + b2 // x = (b1 - b2) / (a2 - a1) // x1 + vx1 * time1 = x + vx * time1 // y1 + vy1 * time1 = y + vy * time1 // z1 + vz1 * time1 = z + vz * time1 // x2 + vx2 * time2 = x + vx * time2 // y2 + vy2 * time2 = y + vy * time2 // z2 + vz2 * time2 = z + vz * time2 // x3 + vx3 * time3 = x + vx * time3 // y3 + vy3 * time3 = y + vy * time3 // z3 + vz3 * time3 = z + vz * time3 try { // val timeX = (first.position.x.toDouble() - second.position.x) / (second.velocity.x.toDouble() - first.velocity.x) // val timeY = (first.position.y.toDouble() - second.position.y) / (second.velocity.y.toDouble() - first.velocity.y) val a1 = (first.velocity.y + first.velocityDelta.y) / (first.velocity.x.toDouble() + first.velocityDelta.x) val b1 = first.position.y - a1 * first.position.x val a2 = (second.velocity.y + second.velocityDelta.y) / (second.velocity.x.toDouble() + second.velocityDelta.x) val b2 = second.position.y - a2 * second.position.x val x = (b1 - b2) / (a2 - a1) val y = a1 * x + b1 val time1 = (x - first.position.x) / (first.velocity.x.toDouble() + first.velocityDelta.x) val time2 = (x - second.position.x) / (second.velocity.x.toDouble() + second.velocityDelta.x) return if (x.isFinite() && y.isFinite()) { Intersection( // positionX = first.position.x + first.velocity.x * timeX, // positionY = first.position.y + first.velocity.y * timeY, // time = timeX, position = DoubleCoord(x, y), time1 = time1, time2 = time2, ) } else { null } } catch (e: Exception) { throw RuntimeException("Error while intersecting $first and $second", e) } } fun findRockPosition(hails: List<Hail>, x: IntRange, y: IntRange, z: IntRange, logPrefix: String = ""): LongCoord3d { val hailsWithDifferentVectors = generateHails(hails, x, y, z) var index = 0L val points = mutableListOf<LongCoord>() for (newHails in hailsWithDifferentVectors) { val point = findCommonIntersectsXY(newHails) if (index % 999_000_000 == 0L) { println("${logPrefix}%,12d @ %s".format(index, LocalDateTime.now())) } if (point != null) { println("${logPrefix}Found $point at $index for dv = ${newHails.first().velocityDelta}") points.add(point) } index++ } // TODO choose Z that matches println("${logPrefix}%,12d @ %s".format(index, LocalDateTime.now())) return LongCoord3d(0, 0, 0) } private fun generateHails(hails: List<Hail>, x: IntRange, y: IntRange, z: IntRange): Sequence<List<Hail>> = sequence { for (xx in x) { for (yy in y) { for (zz in z) { yield(Coord3d(xx, yy, zz)) } } } } // .sortedBy { it.distanceTo(Coord3d(0, 0, 0)) } .map { delta -> hails.map { Hail( position = it.position, velocity = it.velocity, velocityDelta = delta ) } } private fun findCommonIntersectsXY(hails: List<Hail>): LongCoord? { var commonIntersection: Intersection? = null val intersections = mutableMapOf<Intersection, Int>() for ((hail1, hail2) in generatePairs(hails)) { val intersection = findIntersection(hail1, hail2) if (intersection == null) { continue } intersections.compute(intersection) { _, v -> v?.plus(1) ?: 1 } if (commonIntersection == null) { commonIntersection = intersection } else { // x = 354954946036320 // y = 318916597757112 // z = 112745502066835 if (commonIntersection.position.distanceTo(intersection.position) > 1) { return null } } } return commonIntersection?.position?.let { LongCoord(it.x.toLong(), it.y.toLong()) } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
6,494
advent-of-code
MIT License
src/day3/Day3.kt
ZsemberiDaniel
159,921,870
false
null
package day3 import RunnablePuzzleSolver class Day3 : RunnablePuzzleSolver { private val fabricSize = 1000 private lateinit var claims: List<Claim> override fun readInput1(lines: Array<String>) { // splitting by all the delimiters and mapping to Claim objects claims = lines.map { val split = it.split("#", " @ ", ",", ": ", "x") Claim(split[1].toInt(), split[2].toInt(), split[3].toInt(), split[4].toInt(), split[5].toInt()) } } override fun readInput2(lines: Array<String>) { } override fun solvePart1(): String { val fabric: Array<Array<Int>> = Array(fabricSize + 1) { Array(fabricSize + 1) { 0 } } // go through the claims and mark where a claim begun and ended in each row for (claim in claims) { for (k in claim.start.y..claim.end.y) { fabric[claim.start.x][k]++ fabric[claim.end.x + 1][k]-- } } var overlapCount = 0 var currClaimCount = 0 // we go through the rows of the fabric for (i in 0..fabricSize) { currClaimCount = 0 // we go through the for (k in 0..fabricSize) { currClaimCount += fabric[k][i] if (currClaimCount > 1) overlapCount++ } } return overlapCount.toString() } override fun solvePart2(): String { claims = claims.sortedBy { it.start.x } // we check for each claim whether any other claim overlaps it for (i in 0 until claims.size) { var k = 0 while (k < claims.size) { if (i != k && claims[i].overlaps(claims[k])) break k++ } // we reached the end of the inner for loop -> no other claim overlaps it if (k == claims.size) return claims[i].id.toString() } return "No claim found with no other overlaps!" } data class Claim(val id: Int, val start: Coord, val end: Coord) { constructor(id: Int, startX: Int, startY: Int, sizeX: Int, sizeY: Int) : this(id, Coord(startX, startY), Coord(startX + sizeX - 1, startY + sizeY - 1)) fun overlaps(claim: Claim) = this.start.x <= claim.end.x && claim.start.x <= this.end.x && this.start.y <= claim.end.y && claim.start.y <= this.end.y } data class Coord(val x: Int, val y: Int) }
0
Kotlin
0
0
bf34b93aff7f2561f25fa6bd60b7c2c2356b16ed
2,532
adventOfCode2018
MIT License
src/main/kotlin/g2701_2800/s2711_difference_of_number_of_distinct_values_on_diagonals/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2701_2800.s2711_difference_of_number_of_distinct_values_on_diagonals // #Medium #Array #Hash_Table #Matrix #2023_07_31_Time_281_ms_(100.00%)_Space_44.5_MB_(70.00%) class Solution { fun differenceOfDistinctValues(grid: Array<IntArray>): Array<IntArray> { val m = grid.size val n = grid[0].size val arrTopLeft = Array(m) { IntArray(n) } val arrBotRight = Array(m) { IntArray(n) } for (i in m - 1 downTo 0) { var c = 0 var r: Int = i val set: MutableSet<Int> = HashSet() while (cellExists(r, c, grid)) { arrTopLeft[r][c] = set.size set.add(grid[r++][c++]) } } for (i in 1 until n) { var r = 0 var c: Int = i val set: MutableSet<Int> = HashSet() while (cellExists(r, c, grid)) { arrTopLeft[r][c] = set.size set.add(grid[r++][c++]) } } for (i in 0 until n) { var r = m - 1 var c: Int = i val set: MutableSet<Int> = HashSet() while (cellExists(r, c, grid)) { arrBotRight[r][c] = set.size set.add(grid[r--][c--]) } } for (i in m - 1 downTo 0) { var c = n - 1 var r: Int = i val set: MutableSet<Int> = HashSet() while (cellExists(r, c, grid)) { arrBotRight[r][c] = set.size set.add(grid[r--][c--]) } } for (r in 0 until m) { for (c in 0 until n) { grid[r][c] = kotlin.math.abs(arrTopLeft[r][c] - arrBotRight[r][c]) } } return grid } private fun cellExists(r: Int, c: Int, grid: Array<IntArray>): Boolean { return r >= 0 && r < grid.size && c >= 0 && c < grid[0].size } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,927
LeetCode-in-Kotlin
MIT License
src/Day20.kt
esp-er
573,196,902
false
{"Kotlin": 29675}
package patriker.day20 import patriker.utils.* import java.util.LinkedList fun main(){ val testInput = readInput("Day20_test") val input = readInput("Day20_input") solvePart1(testInput) println(solvePart1(input)) } fun solvePart1(input: List<String>): Int{ val encodedCoords = input.mapIndexed{idx, v -> idx to v.toInt()} val coords = LinkedList<Pair<Int,Int>>() encodedCoords.forEachIndexed(){ idx, p -> coords.add(p) } encodedCoords.forEach{ var currIndex = coords.indexOf(it) var start = currIndex var end = currIndex + coords[currIndex].second if (end < 0) end = Math.floorMod(end, coords.size - 1) if (end >= (coords.size - 1) ) end = end % (coords.size - 1) if(coords[currIndex].second != 0) { if(end > start) coords.add(end + 1, it) else coords.add(end,it) val r = if(end > start) coords.removeAt(start) else coords.removeAt(start+1) check(r == it) } } var zeroidx = 0 coords.forEachIndexed{ idx, p -> if(p.second ==0) zeroidx = idx } val a = (zeroidx + 1000) % coords.size val b = (zeroidx + 2000) % coords.size val c = (zeroidx + 3000) % coords.size return coords[a].second + coords[b].second + coords[c].second }
0
Kotlin
0
0
f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362
1,472
aoc2022
Apache License 2.0
Kotlin for Java Developers. Week 3/Taxi Park/Task/src/taxipark/TaxiParkTask.kt
obarcelonap
374,972,699
false
null
package taxipark /* * Task #1. Find all the drivers who performed no trips. */ fun TaxiPark.findFakeDrivers(): Set<Driver> = allDrivers.filter { findTrips(it).isEmpty() } .toSet() /* * Task #2. Find all the clients who completed at least the given number of trips. */ fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> = allPassengers.filter { findTrips(it).size >= minTrips } .toSet() /* * Task #3. Find all the passengers, who were taken by a given driver more than once. */ fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> { val driverTrips = findTrips(driver) return allPassengers.filter { passenger -> driverTrips.filter { passenger in it.passengers }.count() > 1 } .toSet() } /* * Task #4. Find the passengers who had a discount for majority of their trips. */ fun TaxiPark.findSmartPassengers(): Set<Passenger> = allPassengers.filter { passenger -> val (withDiscount, withoutDiscount) = findTrips(passenger).partition { it.hasDiscount() } withDiscount.size > withoutDiscount.size } .toSet() /* * Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on. * Return any period if many are the most frequent, return `null` if there're no trips. */ fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? { val step = 10 val maxDuration = trips.maxOfOrNull { it.duration } ?: return null val buckets = generateSequence(0) { it + step } .takeWhile { it <= maxDuration + step } .zipWithNext() .map { it.first until it.second } return trips.groupBy { trip -> buckets.find { bucket -> trip.duration in bucket } } .maxByOrNull { (_, trips) -> trips.size } ?.key } /* * Task #6. * Check whether 20% of the drivers contribute 80% of the income. */ fun TaxiPark.checkParetoPrinciple(): Boolean { val totalIncome = trips.sumByDouble { it.cost } val driversByIncomeDesc = allDrivers.map { driver -> driver to findTrips(driver).sumByDouble { it.cost } } .sortedByDescending { it.second } val top20DriversIncome = driversByIncomeDesc.subList(0, (driversByIncomeDesc.size * 0.2).toInt()) .sumByDouble { it.second } return ((top20DriversIncome / totalIncome) * 100) >= 80 } fun TaxiPark.findTrips(passenger: Passenger): List<Trip> = trips.filter { passenger in it.passengers } fun TaxiPark.findTrips(driver: Driver): List<Trip> = trips.filter { driver == it.driver } fun Trip.hasDiscount() = discount != null
0
Kotlin
0
0
d79103eeebcb4f1a7b345d29c0883b1eebe1d241
2,579
coursera-kotlin-for-java-developers
MIT License
src/Day05SupplyStacks.kt
zizoh
573,932,084
false
{"Kotlin": 13370}
fun main() { val input: List<String> = readInput("input/day05") val stacks = getStacks(input) rearrangeCrates(getRearrangementProcedure(input), stacks) println(getCratesOnTopOfStack(stacks)) } private fun getStacks(input: List<String>): Map<String, MutableList<String>> { val stacks = mutableMapOf<String, MutableList<String>>() val numberOfStacks = 9 for (number in 1..numberOfStacks) { stacks[number.toString()] = mutableListOf() } val startingStacksOfCrates = getStartingStacksOfCrates(input) startingStacksOfCrates.forEach { crates -> var count = 1 for (character in 1 until crates.length step 4) { val crate = crates[character] if (crate != ' ') { stacks[count.toString()]!!.add(0, crate.toString()) } count += 1 } } return stacks } private fun getRearrangementProcedure(input: List<String>) = input.subList(10, input.size) private fun getStartingStacksOfCrates(input: List<String>) = input.subList(0, 8) private fun rearrangeCrates( procedure: List<String>, stacks: Map<String, MutableList<String>> ) { procedure.forEach { val originStack = getOriginStack(it) val numberOfMoves = getNumberOfCratesToMove(it) val originCrates = stacks[originStack]!! val destinationStack = getDestinationStack(it) val destinationCrates: MutableList<String> = stacks[destinationStack]!! for (count in numberOfMoves downTo 1) { destinationCrates.add(originCrates.removeLast()) } } } private fun getCratesOnTopOfStack(stacks: Map<String, MutableList<String>>): String { var cratesOnTopOfStacks = "" stacks.values.map { cratesOnTopOfStacks += it.last().removePrefix("[").removeSuffix("]") } return cratesOnTopOfStacks } fun getNumberOfCratesToMove(procedure: String) = procedure.substringAfter(" ").substringBefore(" ").toInt() fun getOriginStack(procedure: String) = procedure.substringAfter("from ").substringBefore(" to") fun getDestinationStack(procedure: String): String = procedure.substringAfter("to ")
0
Kotlin
0
0
817017369d257cca648974234f1e4137cdcd3138
2,157
aoc-2022
Apache License 2.0
src/Day08.kt
YunxiangHuang
572,333,905
false
{"Kotlin": 20157}
import kotlin.math.max fun main() { class Node(h: Char) { var up = -1; var down = -1; var left = -1; var right = -1; val height = h.toString().toInt(); fun isVisiable(): Boolean { return height > up || height > down || height > left || height > right } } var map = ArrayList<ArrayList<Node>>() for (line in readInput("Day08")) { var row = ArrayList<Node>(line.length) for (h in line) { row.add(Node(h)) } map.add(row) } fun partOne(): Int { // Update highest. for ((i, row) in map.withIndex()) { // update left for ((j, node) in row.withIndex()) { if (j == 0) { continue } node.left = max(row[j - 1].height, row[j - 1].left) } // update right var j = row.size - 2 while (j >= 0) { row[j].right = max(row[j + 1].height, row[j + 1].right) j-- } // update up if (i == 0) { continue } for ((j, node) in row.withIndex()) { node.up = max(map[i - 1][j].height, map[i - 1][j].up) } } // update down var i = map.size - 2 while (i >= 0) { for ((j, node) in map[i].withIndex()) { node.down = max(map[i + 1][j].height, map[i + 1][j].down) } i-- } var total = 0 for ((i, row) in map.withIndex()) { for ((j, col) in row.withIndex()) { if (col.isVisiable()) { total++ continue } } } return total } fun partTwo(): Int { fun cal(i: Int, j: Int): Int { var left = 0 var right = 0 var up = 0 var down = 0 val base = map[i][j].height var ti = i - 1 while (ti >= 0) { up++ if (map[ti][j].height >= base) { break } ti-- } ti = i + 1 while (ti < map.size) { down++ if (map[ti][j].height >= base) { break } ti++ } var tj = j - 1 while (tj >= 0) { left++ if (map[i][tj].height >= base) { break } tj-- } tj = j + 1 while (tj < map[i].size) { right++ if (map[i][tj].height >= base) { break } tj++ } // println("[$i, $j]: $left, $right, $up, $down") return left * right * up * down } var res = 0 for (i in 0 until map.size - 1) { for (j in 0 until map[i].size - 1) { res = max(res, cal(i, j)) } } return res } println("Part I: ${partOne()}") println("Part II: ${partTwo()}") }
0
Kotlin
0
0
f62cc39dd4881f4fcf3d7493f23d4d65a7eb6d66
3,285
AoC_2022
Apache License 2.0
src/main/kotlin/day17/Day17ReservoirResearch.kt
Zordid
160,908,640
false
null
package day17 import shared.extractAllPositiveInts import shared.measureRuntime import shared.readPuzzle abstract class Clay { abstract val minY: Int abstract val maxY: Int abstract val minX: Int abstract val maxX: Int abstract fun isClay(tX: Int, tY: Int): Boolean } data class HClay(val x: Int, val y: IntRange) : Clay() { override val minY = y.start override val maxY = y.endInclusive override val minX = x override val maxX = x override fun isClay(tX: Int, tY: Int): Boolean { return (tX == x) && (tY in y) } } data class VClay(val x: IntRange, val y: Int) : Clay() { override val minY = y override val maxY = y override val minX = x.start override val maxX = x.endInclusive override fun isClay(tX: Int, tY: Int): Boolean { return (tX in x) && (tY == y) } } enum class Element(val c: Char) { Free('.'), Clay('#'), Soaked('|'), Water('~'); val blocksWater: Boolean get() = this == Clay || this == Water val isWet: Boolean get() = this == Water || this == Soaked override fun toString(): String = c.toString() } private const val initialSourceX = 500 class Scan(puzzle: List<String>) { private val clays = puzzle .map { it[0] to it.extractAllPositiveInts().toList() } .map { (c, n) -> if (c == 'x') HClay(n[0], n[1]..n[2]) else VClay(n[1]..n[2], n[0]) } private val minY = clays.minBy { it.minY }.minY private val maxY = clays.maxBy { it.maxY }.maxY private val minX = clays.minBy { it.minX }.minX - 1 private val maxX = clays.maxBy { it.maxX }.maxX + 1 val map: Array<Array<Element>> = Array(maxY + 1) { Array(maxX - minX + 1) { Element.Free } } init { for (y in 0..maxY) { for (x in minX..maxX) { if (clays.any { it.isClay(x, y) }) this[x, y] = Element.Clay } } } operator fun get(x: Int, y: Int) = if (y < map.size) map[y][x - minX] else Element.Free operator fun set(x: Int, y: Int, e: Element) { map[y][x - minX] = e } private fun leftRight(x: Int, y: Int): Pair<Int, Int> = (x - 1 downTo minX).first { this[it, y].blocksWater || !this[it, y + 1].blocksWater } to (x + 1..maxX).first { this[it, y].blocksWater || !this[it, y + 1].blocksWater } fun pourWater(x: Int = initialSourceX, y: Int = 0) { if (this[x, y].isWet) return var dropY = y var prev: Element? = null while (!this[x, dropY + 1].blocksWater && dropY <= maxY) { prev = this[x, dropY] this[x, dropY] = Element.Soaked dropY++ } val alreadySoaked = prev == Element.Soaked if (dropY < maxY && !alreadySoaked) { do { val (left, right) = leftRight(x, dropY) val blockedLeft = this[left, dropY].blocksWater val blockedRight = this[right, dropY].blocksWater val closed = blockedLeft && blockedRight val fillWith = if (closed) Element.Water else Element.Soaked for (fillX in left + 1 until right) this[fillX, dropY] = fillWith if (!blockedLeft) pourWater(left, dropY) if (!blockedRight) pourWater(right, dropY) dropY-- } while (closed) } } fun print() { for (y in 0..maxY) { for (x in minX..maxX) { if (x == initialSourceX && y == 0) print('+') else { val element = this[x, y] print(element) } } println() } println() } private fun count(predicate: (Element) -> Boolean) = (minY..maxY).sumOf { y -> (minX..maxX).count { predicate(this[it, y]) } } fun countWater() = count { it == Element.Water } fun countWaterReach() = count { it.isWet } } fun part1(puzzle: List<String>): Int { val scan = Scan(puzzle) scan.pourWater() return scan.countWaterReach() } fun part2(puzzle: List<String>): Int { val scan = Scan(puzzle) scan.pourWater() return scan.countWater() } fun main() { val puzzle = readPuzzle(17) measureRuntime { println(part1(puzzle)) println(part2(puzzle)) } }
0
Kotlin
0
0
f246234df868eabecb25387d75e9df7040fab4f7
4,417
adventofcode-kotlin-2018
Apache License 2.0
src/main/kotlin/dev/phiber/aoc2022/day3/Solution.kt
rsttst
572,967,557
false
{"Kotlin": 7688}
package dev.phiber.aoc2022.day3 import dev.phiber.aoc2022.readAllLinesUntilEmpty fun itemPriority(item: Char) : Int = if (item < 'a') { (item - 'A') + 27 } else { (item - 'a') + 1 } fun main() { val lines: List<String> = readAllLinesUntilEmpty() val doubleCompartmentItems: List<Char> = lines .map { line -> line.substring(0, line.length / 2) to line.substring(line.length / 2) } .map { (compartment1, compartment2) -> val compartment2Set: Set<Char> = compartment2.toSet() compartment1.first { item -> item in compartment2Set } } val task1PrioritySum = doubleCompartmentItems.sumOf(::itemPriority) val teamBadgeItems: List<Char> = lines .windowed(size = 3, step = 3) .map { (rucksack1, rucksack2, rucksack3) -> val rucksack2Set: Set<Char> = rucksack2.toSet() val rucksack3Set: Set<Char> = rucksack3.toSet() rucksack1.first { item -> item in rucksack2Set && item in rucksack3Set } } val task2PrioritySum = teamBadgeItems.sumOf(::itemPriority) println("Task 1: $task1PrioritySum") println("Task 2: $task2PrioritySum") }
0
Kotlin
0
0
2155029ebcee4727cd0af75543d9f6f6ab2b8995
1,169
advent-of-code-2022
Apache License 2.0
corneil/common/src/main/kotlin/permute.kt
jensnerche
317,661,818
true
{"HTML": 2739009, "Java": 348790, "Kotlin": 271053, "TypeScript": 262310, "Python": 198318, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46}
package com.github.corneil.aoc2019.common import java.math.BigInteger // found on https://rosettacode.org/wiki/Permutations#Kotlin fun <T> permute(input: List<T>): List<List<T>> { if (input.isEmpty()) return emptyList() if (input.size == 1) return listOf(input) val perms = mutableListOf<List<T>>() val toInsert = input[0] for (perm in permute(input.drop(1))) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) perms.add(newPerm) } } return perms } fun permutationsBI(n: BigInteger): BigInteger = n * if (n > BigInteger.ONE) permutationsBI(n - BigInteger.ONE) else BigInteger.ONE fun permutations(n: Int): BigInteger = permutationsBI(n.toBigInteger()) fun <T> permuteInvoke(input: List<T>, handlePermuation: (List<T>) -> Unit) { if (input.size == 1) { handlePermuation(input) } else { val toInsert = input[0] permuteInvoke(input.drop(1)) { perm -> for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) handlePermuation(newPerm) } } } } fun <T> permuteArray(input: Array<T>, makeArray: (Collection<T>) -> Array<T>): List<Array<T>> { if (input.isEmpty()) return emptyList() if (input.size == 1) return listOf(input) val perms = mutableListOf<Array<T>>() val toInsert = input[0] for (perm in permuteArray(makeArray(input.drop(1)), makeArray)) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) perms.add(makeArray(newPerm)) } } return perms }
0
HTML
0
0
a84c00ddbeb7f9114291125e93871d54699da887
1,732
aoc-2019
MIT License
src/Day05.kt
AlaricLightin
572,897,551
false
{"Kotlin": 87366}
import java.util.Stack val MOVE_REGEX = Regex("move\\s(\\d+)\\sfrom\\s(\\d+)\\sto\\s(\\d+)") fun main() { fun createStackList(input: List<String>, blankLineNumber: Int): List<Stack<Char>> { val stackList = mutableListOf<Stack<Char>>() for (i in (0..blankLineNumber - 2).reversed()) { val s = input[i] for (j in 1..s.length step 4) { val stackNumber = j / 4 if (stackNumber >= stackList.size) stackList.add(Stack<Char>()) if (s[j] != ' ') stackList[stackNumber].push(s[j]) } } return stackList } fun getBlankLineNumber(input: List<String>): Int { var blankLineNumber = 0 run findBlank@{ input.forEachIndexed { index, s -> if (s.isBlank()) { blankLineNumber = index return@findBlank } } } return blankLineNumber } fun getResult(stackList: List<Stack<Char>>): String { var result = "" for (stack in stackList) { result += stack.pop() } return result } fun part1(input: List<String>): String { val blankLineNumber = getBlankLineNumber(input) val stackList = createStackList(input, blankLineNumber) for (i in blankLineNumber + 1 until input.size) { val s = input[i] val matchResult = MOVE_REGEX.matchEntire(s) ?: continue repeat(matchResult.groupValues[1].toInt()) { val c = stackList[matchResult.groupValues[2].toInt() - 1].pop() stackList[matchResult.groupValues[3].toInt() - 1].push(c) } } return getResult(stackList) } fun part2(input: List<String>): String { val blankLineNumber = getBlankLineNumber(input) val stackList = createStackList(input, blankLineNumber) for (i in blankLineNumber + 1 until input.size) { val s = input[i] val matchResult = MOVE_REGEX.matchEntire(s) ?: continue val count = matchResult.groupValues[1].toInt() val tempStack = Stack<Char>() repeat(count) { val c = stackList[matchResult.groupValues[2].toInt() - 1].pop() tempStack.push(c) } repeat(count) { val c = tempStack.pop() stackList[matchResult.groupValues[3].toInt() - 1].push(c) } } return getResult(stackList) } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ee991f6932b038ce5e96739855df7807c6e06258
2,804
AdventOfCode2022
Apache License 2.0
Round 1C - A. Ample Syrup/src/app.kt
amirkhanyana
110,548,909
false
{"Kotlin": 20514}
import java.util.* fun main(args: Array<String>) { val input = Scanner(System.`in`) val T = input.nextInt() var Ti = 1 while (Ti <= T) { val N = input.nextInt() val K = input.nextInt() val pancakes = Array(N, { Pair(input.nextInt(), input.nextInt()) }) val pancakesByCylinderArea = pancakes.mapIndexed({ i, v -> i to v }).sortedBy { cylinderArea(it.second.first, it.second.second) }.toMap().toMutableMap() val pancakesByRad = pancakes.mapIndexed({ i, v -> i to v }).sortedByDescending { it.second.first }.toMap().toMutableMap() for (i in 0 until N - K) { val pancakesByCylinderAreaList = pancakesByCylinderArea.toList() val pancake = pancakesByCylinderAreaList[0] val pancakesByRadIterator = pancakesByRad.iterator() val largest = pancakesByRadIterator.next() val secondLargest = pancakesByRadIterator.next() if (largest.key == pancake.first) { val nextSmallestCylinder = pancakesByCylinderAreaList[1] if (cylinderArea(largest.value.first, largest.value.second) + surfaceArea(largest.value.first) - surfaceArea(secondLargest.value.first) > cylinderArea(nextSmallestCylinder.second.first, nextSmallestCylinder.second.second)) { pancakesByCylinderArea.remove(nextSmallestCylinder.first) pancakesByRad.remove(nextSmallestCylinder.first) } else{ pancakesByCylinderArea.remove(pancake.first) pancakesByRad.remove(pancake.first) } } else { pancakesByCylinderArea.remove(pancake.first) pancakesByRad.remove(pancake.first) } } val pancakesByRadAsList = pancakesByRad.toList() println("Case #" + Ti + ": " + (pancakesByRadAsList.sumByDouble { cylinderArea(it.second.first, it.second.second) } + surfaceArea(pancakesByRadAsList[0].second.first))) ++Ti } } fun cylinderArea(r: Int, h: Int) = 2 * Math.PI * r * h fun surfaceArea(r: Int) = Math.PI * r * r
0
Kotlin
0
0
25a8e6dbd5843e9d4a054d316acc9d726995fffe
2,118
Google-Code-Jam-2017-Problem-Kotlin-Solutions
The Unlicense
src/main/kotlin/days/Day23.kt
sicruse
315,469,617
false
null
package days class Day23 : Day(23) { val initalCupLabels = inputString.map { c -> c.toString().toInt() } private class CupGame(sample: List<Int>, size: Int = sample.size): Items(size) { init { currentItem = items[sample.first()] val itemsInOrder = sample + (sample.size + 1 .. size) val lastItem = items[sample.last()] // apply item links itemsInOrder .map { id -> items[id] } .fold( lastItem ) { previousItem, cup -> cup.also { previousItem.next = cup } } // link last item to first item items[itemsInOrder.last()].next = items[itemsInOrder.first()] } fun play(times: Int): Item { repeat(times) { val three: List<Item> = currentItem.next(3) moveItemsTo(insertionPoint(three.map { it.value }.toSet()), three) currentItem = currentItem.next } return items[1] } private fun insertionPoint(exempt: Set<Int>): Item { var candidate = currentItem.value - 1 while(candidate in exempt || candidate == 0) { candidate = if(candidate == 0) items.size - 1 else candidate - 1 } return items[candidate] } } private open class Items(size: Int) { val items: List<Item> = List(size + 1) { Item(it) } lateinit var currentItem: Item fun moveItemsTo(insertionPoint: Item, itemsToInsert: List<Item>) { val previousItem = insertionPoint.next currentItem.next = itemsToInsert.last().next insertionPoint.next = itemsToInsert.first() itemsToInsert.last().next = previousItem } } private class Item(val value: Int) { lateinit var next: Item fun next(n: Int): List<Item> = (1 .. n).runningFold(this) { cur, _ -> cur.next }.drop(1) fun values(): String = buildString { var current = this@Item.next while(current != this@Item) { append(current.value.toString()) current = current.next } } } override fun partOne(): Any { return CupGame(initalCupLabels) .play(100) .values() } override fun partTwo(): Any { return CupGame(initalCupLabels, 1000000) .play(10000000) .next(2) .fold(1L) { acc, cup -> acc * cup.value } } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
2,561
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
2017/src/main/kotlin/Day08.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import utils.splitNewlines import utils.splitWhitespace object Day08 { fun part1(input: String): Int { val registers = mutableMapOf<String, Int>().withDefault { 0 } val instructions = input.splitNewlines().map(this::parseInstruction) for (instruction in instructions) { execute(registers, instruction) } return registers.maxValue() } fun part2(input: String): Int { val registers = mutableMapOf<String, Int>().withDefault { 0 } var maxValue = registers.maxValue() val instructions = input.splitNewlines().map(this::parseInstruction) for (instruction in instructions) { execute(registers, instruction) maxValue = maxOf(registers.maxValue(), maxValue) } return maxValue } data class Instruction(val register: String, val amount: Int, val condition: Condition) data class Condition(val leftOperand: String, val operator: String, val rightOperand: Int) private fun parseInstruction(instruction: String): Instruction { val split = instruction.splitWhitespace() val register = split[0] val incrementing = split[1] == "inc" val amount = split[2].toInt() * if (incrementing) 1 else -1 val left = split[4] val operator = split[5] val right = split[6].toInt() return Instruction( register = register, amount = amount, condition = Condition( leftOperand = left, operator = operator, rightOperand = right ) ) } private fun execute(registers: MutableMap<String, Int>, instruction: Instruction) { if (checkCondition(registers, instruction.condition)) { val newValue = registers.getValue(instruction.register) + instruction.amount registers[instruction.register] = newValue } } private fun checkCondition(registers: Map<String, Int>, condition: Condition): Boolean { val leftOperand = registers.getValue(condition.leftOperand) return when (condition.operator) { ">" -> leftOperand > condition.rightOperand ">=" -> leftOperand >= condition.rightOperand "==" -> leftOperand == condition.rightOperand "!=" -> leftOperand != condition.rightOperand "<" -> leftOperand < condition.rightOperand "<=" -> leftOperand <= condition.rightOperand else -> throw IllegalArgumentException("Illegal operator: ${condition.operator}") } } private fun Map<String, Int>.maxValue() = values.max() ?: 0 }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
2,442
advent-of-code
MIT License
solutions/src/ValidPathOnGrid.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/ */ class ValidPathOnGrid { fun hasValidPath(grid: Array<IntArray>) : Boolean { val queue = mutableListOf(Pair(0,0)) val visited = mutableSetOf<Pair<Int,Int>>() while (queue.isNotEmpty()) { val current = queue.removeAt(0) visited.add(current) if (current.first == grid.lastIndex && current.second == grid[0].lastIndex) { return true } val possibleSteps = mutableListOf<Pair<Int,Int>>() when (grid[current.first][current.second]) { 1 -> { possibleSteps.add(Pair(current.first,current.second+1)) possibleSteps.add(Pair(current.first,current.second-1)) } 2 -> { possibleSteps.add(Pair(current.first+1,current.second)) possibleSteps.add(Pair(current.first-1,current.second)) } 3 -> { possibleSteps.add(Pair(current.first,current.second-1)) possibleSteps.add(Pair(current.first+1,current.second)) } 4 -> { possibleSteps.add(Pair(current.first,current.second+1)) possibleSteps.add(Pair(current.first+1,current.second)) } 5 -> { possibleSteps.add(Pair(current.first-1,current.second)) possibleSteps.add(Pair(current.first,current.second-1)) } else -> { possibleSteps.add(Pair(current.first-1,current.second)) possibleSteps.add(Pair(current.first,current.second+1)) } } queue.addAll(possibleSteps.filter { !visited.contains(it) && acceptsDirection(current,it,grid) }) } return false } private fun acceptsDirection(source: Pair<Int,Int>,target: Pair<Int,Int>, grid: Array<IntArray>) : Boolean { if (target.first < 0 || target.first > grid.lastIndex || target.second < 0 || target.second > grid[0].lastIndex) { return false } val streetType = grid[target.first][target.second] if (source.second > target.second) { return setOf(1,4,6).contains(streetType) } if (source.second < target.second) { return setOf(1,3,5).contains(streetType) } if (source.first > target.first) { return setOf(2,3,4).contains(streetType) } if (source.first < target.first) { return setOf(2,5,6).contains(streetType) } return false } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
2,739
leetcode-solutions
MIT License
year2022/src/main/kotlin/net/olegg/aoc/year2022/day5/Day5.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2022.day5 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2022.DayOf2022 /** * See [Year 2022, Day 5](https://adventofcode.com/2022/day/5) */ object Day5 : DayOf2022(5) { private val NUM_PATTERN = "(\\d)".toRegex() private val COMMAND_PATTERN = "move (\\d+) from (\\d+) to (\\d+)".toRegex() override fun first(): Any? { val (stacksData, commandsData) = data.split("\n\n") val stackPositions = stacksData .lines() .last() .let { line -> val columns = NUM_PATTERN.findAll(line) columns.map { it.value.toInt() to it.range.first } } val stacks = stackPositions.associate { it.first to ArrayDeque<Char>() } stacksData .lines() .dropLast(1) .forEach { line -> stackPositions.forEach { (value, position) -> if (line[position] != ' ') { stacks.getValue(value).addLast(line[position]) } } } val commands = commandsData .lines() .mapNotNull { COMMAND_PATTERN.find(it) } .map { line -> line.destructured.toList().map { it.toInt() } } .map { Triple(it[0], it[1], it[2]) } commands.forEach { (count, from, to) -> val fromStack = stacks.getValue(from) val toStack = stacks.getValue(to) repeat(count) { toStack.addFirst(fromStack.removeFirst()) } } return stacks .mapValues { it.value.first() } .toList() .sortedBy { it.first } .map { it.second } .joinToString(separator = "") { it.toString() } } override fun second(): Any? { val (stacksData, commandsData) = data.split("\n\n") val stackPositions = stacksData .lines() .last() .let { line -> val columns = NUM_PATTERN.findAll(line) columns.map { it.value.toInt() to it.range.first } } val stacks = stackPositions.associate { it.first to ArrayDeque<Char>() } stacksData .lines() .dropLast(1) .forEach { line -> stackPositions.forEach { (value, position) -> if (line[position] != ' ') { stacks.getValue(value).addLast(line[position]) } } } val commands = commandsData .lines() .mapNotNull { COMMAND_PATTERN.find(it) } .map { line -> line.destructured.toList().map { it.toInt() } } .map { Triple(it[0], it[1], it[2]) } commands.forEach { (count, from, to) -> val fromStack = stacks.getValue(from) val toStack = stacks.getValue(to) val stack = fromStack.take(count).asReversed() repeat(count) { fromStack.removeFirst() toStack.addFirst(stack[it]) } } return stacks .mapValues { it.value.first() } .toList() .sortedBy { it.first } .map { it.second } .joinToString(separator = "") { it.toString() } } } fun main() = SomeDay.mainify(Day5)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,947
adventofcode
MIT License
src/main/kotlin/com/kishor/kotlin/algo/algorithms/divideandconquer/MergeSort.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.divideandconquer val inputArray = arrayOf(9, 1, -4, 5, 8, -2, 10) val sorted = Array<Int>(inputArray.size) { 0 } fun main() { MergeSort().mergeSort(0, inputArray.size - 1) inputArray.forEach { println("$it") } } class MergeSort { fun mergeSort(low: Int, high: Int) { if (low >= high) return val mid = (low + high) / 2 mergeSort(low, mid) mergeSort(mid + 1, high) merge(low, mid, high) } fun merge(low: Int, middle: Int, high: Int): Array<Int> { // inputArray.copyInto(sorted) for (i in 0 until inputArray.size) { sorted[i] = inputArray[i] } var i = low var j = middle + 1 var k = low while (i <= middle && j <= high) { if (sorted[i] <= sorted[j]) { inputArray[k++] = sorted[i++] } else { inputArray[k++] = sorted[j++] } } while (i <= middle) { inputArray[k++] = sorted[i++] } while (j <= high) { inputArray[k++] = sorted[j++] } return inputArray } }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,187
DS_Algo_Kotlin
MIT License
advent2022/src/main/kotlin/year2022/Day25.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import kotlin.math.pow private fun Char.parseSnafuDigit() = when (this) { '2' -> 2L '1' -> 1L '0' -> 0L '-' -> -1L '=' -> -2L else -> error("unexpected Snafu digit") } fun String.parseSnafuNumber(): Long = map { it.parseSnafuDigit() }.reversed().reduceIndexed { i, acc, cur -> acc + (5.0.pow(i)).toLong() * cur } private fun Long.toSnafuDigit(): Char = when (this) { 0L -> '0' 1L -> '1' 2L -> '2' 3L -> '=' // -2 == 3 mod 5 4L -> '-' // -1 == 4 mod 5 else -> error("only can convert digit") } fun Long.toSnafuNumber(): String { if (this == 0L) return "0" return generateSequence(this to "") { (rest, currentString) -> val lowestDigit = rest % 5 (rest + 2) / 5 to lowestDigit.toSnafuDigit() + currentString }.first { it.first <= 0L }.second } class Day25 : AdventDay(2022, 25) { override fun part1(input: List<String>): Long = input.sumOf { it.parseSnafuNumber() } override fun part2(input: List<String>): String = part1(input).toSnafuNumber() } fun main() = Day25().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
1,129
advent-of-code
Apache License 2.0
src/Day05.kt
jordan-thirus
573,476,470
false
{"Kotlin": 41711}
fun main() { fun buildCrateStacks( input: List<String>, instructionSplitIndex: Int ): MutableList<MutableList<Char>> { val crateStacks: MutableList<MutableList<Char>> = mutableListOf() for (line in input.subList(0, instructionSplitIndex - 1)) { //println(line) var lineIndex = 1 var stackIndex = 0 while (lineIndex < line.length) { if (crateStacks.size < stackIndex + 1) { crateStacks.add(mutableListOf()) } val crate = line[lineIndex] if (crate != ' ') { crateStacks[stackIndex].add(0, crate) } lineIndex += 4 stackIndex += 1 } } return crateStacks } fun part1(input: List<String>): String { val instructionSplitIndex = input.indexOf("") val crateStacks: MutableList<MutableList<Char>> = buildCrateStacks(input, instructionSplitIndex) //run instructions for (line in input.subList(instructionSplitIndex + 1, input.size)) { //println(line) val instructions = line.split(" ") val count = instructions[1].toInt() val from = instructions[3].toInt() - 1 val to = instructions[5].toInt() - 1 crateStacks[to].addAll(crateStacks[from].takeLast(count).reversed()) crateStacks[from] = crateStacks[from].subList(0, crateStacks[from].size - count) //println(crateStacks) } return crateStacks.map { s -> s.lastOrNull() ?: "" } .joinToString("") } fun part2(input: List<String>): String { val instructionSplitIndex = input.indexOf("") val crateStacks: MutableList<MutableList<Char>> = buildCrateStacks(input, instructionSplitIndex) //run instructions for (line in input.subList(instructionSplitIndex + 1, input.size)) { //println(line) val instructions = line.split(" ") val count = instructions[1].toInt() val from = instructions[3].toInt() - 1 val to = instructions[5].toInt() - 1 crateStacks[to].addAll(crateStacks[from].takeLast(count)) crateStacks[from] = crateStacks[from].subList(0, crateStacks[from].size - count) //println(crateStacks) } return crateStacks.map { s -> s.lastOrNull() ?: "" } .joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e
2,800
advent-of-code-2022
Apache License 2.0
src/Day08.kt
WilsonSunBritten
572,338,927
false
{"Kotlin": 40606}
fun main() { fun part1(input: List<String>): Int { val rows = input.size val columns = input.first().toList().size val map: List<List<Int>> = input.map { row -> row.toList().map { it.digitToInt() }} val visibleMap = mutableMapOf<Pair<Int, Int>, Boolean>() // visible from left (0 until rows) .forEach { row -> var max = -1 (0 until columns) .toList() .forEach { column -> if (map[row][column] > max) { max = map[row][column] visibleMap[row to column] = true } } } //right (0 until rows) .forEach { row -> var max = -1 (0 until columns).reversed() .toList() .forEach { column -> if (map[row][column] > max) { max = map[row][column] visibleMap[row to column] = true } } } // top (0 until columns) .forEach { column -> var max = -1 (0 until rows) .toList() .forEach { row -> if (map[row][column] > max) { max = map[row][column] visibleMap[row to column] = true } } } // bottom (0 until columns) .forEach { column -> var max = -1 (0 until rows).reversed() .toList() .forEach { row -> if (map[row][column] > max) { max = map[row][column] visibleMap[row to column] = true } } } // border ones return visibleMap.values.filter { it }.count() } fun part2(input: List<String>): Int { val rows = input.size val columns = input.first().toList().size val map: List<List<Int>> = input.map { row -> row.toList().map { it.digitToInt() }} val scenicScores = mutableMapOf<Pair<Int, Int>, Int>() (0 until rows).forEach { row -> (0 until columns).forEach { column -> val currentTree = map[row][column] var leftCounter = 0 var leftIndex = row - 1 while (leftIndex >= 0) { leftCounter++ if (map[leftIndex][column] < currentTree) { leftIndex-- } else { break } } var rightCounter = 0 var rightIndex = row + 1 while (rightIndex < rows) { rightCounter++ if (map[rightIndex][column] < currentTree) { rightIndex++ } else { break } } var topCounter = 0 var topIndex = column - 1 while (topIndex >= 0) { topCounter++ if (map[row][topIndex] < currentTree) { topIndex-- }else { break } } var bottomCounter = 0 var bottomIndex = column + 1 while (bottomIndex < columns) { bottomCounter++ if (map[row][bottomIndex] < currentTree) { bottomIndex++ } else { break } } scenicScores[row to column] = topCounter * bottomCounter * leftCounter * rightCounter } } // border ones return scenicScores.values.max() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val input = readInput("Day08") val p1TestResult = part1(testInput) println(p1TestResult) check(p1TestResult == 21) println(part1(input)) println("Part 2") val p2TestResult = part2(testInput) println(p2TestResult) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
0
363252ffd64c6dbdbef7fd847518b642ec47afb8
4,596
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/days/aoc2022/Day19.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day import kotlin.math.max class Day19 : Day(2022, 19) { override fun partOne(): Any { return determineSumOfBlueprintQualityLevels(inputList, 24) } override fun partTwo(): Any { return 0 } fun determineSumOfBlueprintQualityLevels(input: List<String>, minutes: Int): Int { return input.map { parseBlueprint(it) }.sumOf { BlueprintOperation(it, minutes).getQualityOfBlueprint() } } // Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian. private fun parseBlueprint(line: String): Blueprint { Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.") .matchEntire(line)?.destructured?.let { (id, oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, obsidianRobotClayCost, geodeRobotOreCost, geodeRobotObsidianCost) -> return Blueprint(id.toInt(), oreRobotOreCost.toInt(), clayRobotOreCost.toInt(), obsidianRobotOreCost.toInt(), obsidianRobotClayCost.toInt(), geodeRobotOreCost.toInt(), geodeRobotObsidianCost.toInt()) } throw IllegalStateException() } } class BlueprintOperation(private val blueprint: Blueprint, private val minutes: Int) { private val robotFactories = listOf( OreRobotFactory(blueprint.oreRobotOreCost), ClayRobotFactory(blueprint.clayRobotOreCost), ObsidianRobotFactory(blueprint.obsidianRobotOreCost, blueprint.obsidianRobotClayCost), GeodeRobotFactory(blueprint.geodeRobotOreCost, blueprint.geodeRobotObsidianCost), ) fun getQualityOfBlueprint(): Int { return blueprint.id * findMostGeodes(minutes) } private fun findMostGeodes(minutes: Int): Int { val queue: MutableList<OperationState> = mutableListOf(OperationState( minutes, mutableMapOf(Resource.Ore to 1, Resource.Clay to 0, Resource.Obsidian to 0, Resource.Geode to 0), mutableMapOf(Resource.Ore to 0, Resource.Clay to 0, Resource.Obsidian to 0, Resource.Geode to 0), mutableListOf(), )) var maxGeodes = 0 val seen = mutableSetOf<OperationState>() while (queue.isNotEmpty()) { with(queue.removeFirst()) { if (this !in seen) { seen.add(this) val totalResources = resources.entries.associate { entry -> entry.key to entry.value + robots.getOrDefault(entry.key, 0) } val forwardRobots = robots.entries.associate { entry -> entry.key to entry.value + activeFactories.count { it == entry.key } } if (minutesLeft > 0) { robotFactories.filter { it.canAfford(totalResources) }.forEach { queue.add(OperationState( minutesLeft - 1, forwardRobots, totalResources.entries.associate { entry -> entry.key to entry.value - it.cost().getOrDefault(entry.key, 0) }, listOf(it.resource()) )) } queue.add( OperationState( minutesLeft - 1, forwardRobots, totalResources, emptyList() ) ) } else { maxGeodes = max(maxGeodes, totalResources.getOrDefault(Resource.Geode, 0)) } } } } return maxGeodes } } data class OperationState(val minutesLeft: Int, val robots: Map<Resource, Int>, val resources: Map<Resource, Int>, val activeFactories: List<Resource>) data class Blueprint(val id: Int, val oreRobotOreCost: Int, val clayRobotOreCost: Int, val obsidianRobotOreCost: Int, val obsidianRobotClayCost: Int, val geodeRobotOreCost: Int, val geodeRobotObsidianCost: Int, ) abstract class RobotFactory { abstract fun canAfford(resources: Map<Resource, Int>): Boolean abstract fun resource(): Resource abstract fun cost(): Map<Resource, Int> } class OreRobotFactory(private val oreCost: Int): RobotFactory() { override fun canAfford(resources: Map<Resource, Int>): Boolean { return resources.getOrDefault(Resource.Ore, 0) >= oreCost } override fun resource(): Resource = Resource.Ore override fun cost(): Map<Resource, Int> { return mapOf(Resource.Ore to oreCost) } } class ClayRobotFactory(private val oreCost: Int): RobotFactory() { override fun canAfford(resources: Map<Resource, Int>): Boolean { return resources.getOrDefault(Resource.Ore, 0) >= oreCost } override fun resource(): Resource = Resource.Clay override fun cost(): Map<Resource, Int> { return mapOf(Resource.Ore to oreCost) } } class ObsidianRobotFactory(private val oreCost: Int, private val clayCost: Int): RobotFactory() { override fun canAfford(resources: Map<Resource, Int>): Boolean { return resources.getOrDefault(Resource.Ore, 0) >= oreCost && resources.getOrDefault(Resource.Clay, 0) >= clayCost } override fun resource(): Resource = Resource.Obsidian override fun cost(): Map<Resource, Int> { return mapOf( Resource.Ore to oreCost, Resource.Clay to clayCost ) } } class GeodeRobotFactory(private val oreCost: Int, private val obsidianCost: Int): RobotFactory() { override fun canAfford(resources: Map<Resource, Int>): Boolean { return resources.getOrDefault(Resource.Ore, 0) >= oreCost && resources.getOrDefault(Resource.Obsidian, 0) >= obsidianCost } override fun resource(): Resource = Resource.Geode override fun cost(): Map<Resource, Int> { return mapOf( Resource.Ore to oreCost, Resource.Obsidian to obsidianCost ) } } enum class Resource { Ore, Clay, Obsidian, Geode }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
6,570
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/Day21.kt
wgolyakov
572,463,468
false
null
import kotlin.math.absoluteValue fun main() { fun parse(input: List<String>): Pair<MutableMap<String, Long>, MutableMap<String, List<String>>> { val values = mutableMapOf<String, Long>() val actions = mutableMapOf<String, List<String>>() for (line in input) { val (name, expr) = line.split(": ") if (expr[0].isDigit()) values[name] = expr.toLong() else actions[name] = expr.split(' ') } return values to actions } fun evalAction(x: Long, action: String, y: Long) = when (action) { "+" -> x + y "-" -> x - y "*" -> x * y "/" -> x / y else -> error("Unknown action: $action") } fun evalRoot(values: MutableMap<String, Long>, actions: MutableMap<String, List<String>>): Long { while (actions.isNotEmpty()) { val iter = actions.iterator() while (iter.hasNext()) { val entry = iter.next() val (a, action, b) = entry.value val x = values[a] ?: continue val y = values[b] ?: continue values[entry.key] = evalAction(x, action, y) iter.remove() } } return values["root"]!! } fun part1(input: List<String>): Long { val (values, actions) = parse(input) return evalRoot(values, actions) } fun simplify(values: MutableMap<String, Long>, actions: MutableMap<String, List<String>>) { var changed = true while (actions.isNotEmpty() && changed) { changed = false val iter = actions.iterator() while (iter.hasNext()) { val entry = iter.next() if (entry.key == "root") continue val (a, action, b) = entry.value if (a == "humn" || b == "humn") continue val x = values[a] ?: continue val y = values[b] ?: continue values[entry.key] = evalAction(x, action, y) iter.remove() changed = true } } } fun f(x: Long, values: MutableMap<String, Long>, actions: MutableMap<String, List<String>>): Long { val valuesCopy = values.toMutableMap() val actionsCopy = actions.toMutableMap() valuesCopy["humn"] = x return evalRoot(valuesCopy, actionsCopy) } fun part2(input: List<String>): Long { val (values, actions) = parse(input) simplify(values, actions) val (rootA, _, rootB) = actions["root"]!! actions["root"] = listOf(rootA, "-", rootB) var x1 = Long.MIN_VALUE / 3 var x2 = Long.MAX_VALUE / 3 var y1: Long var y2: Long while (x1 != x2 && x1 + 1 != x2) { y1 = f(x1, values, actions) y2 = f(x2, values, actions) //println("$x1, $x2 $y1, $y2") if (y1 == 0L) return x1 if (y2 == 0L) return x2 if (y1.absoluteValue < y2.absoluteValue) x2 = (x1 + x2) / 2 else x1 = (x1 + x2) / 2 } y1 = f(x1, values, actions) y2 = f(x2, values, actions) if (y1 == 0L) return x1 if (y2 == 0L) return x2 error("No result! humn: $x1, $x2, root: $y1, $y2") } val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
2,914
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxProductDifference.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max import kotlin.math.min /** * 1913. Maximum Product Difference Between Two Pairs * @see <a href="<link>">Source</a> */ fun interface MaxProductDifference { operator fun invoke(nums: IntArray): Int } class MaxProductDifferenceSort : MaxProductDifference { override fun invoke(nums: IntArray): Int { nums.sort() return nums[nums.size - 1] * nums[nums.size - 2] - nums[0] * nums[1] } } class MaxProductDifferenceTrack : MaxProductDifference { override fun invoke(nums: IntArray): Int { var biggest = 0 var secondBiggest = 0 var smallest = Int.MAX_VALUE var secondSmallest = Int.MAX_VALUE for (num in nums) { if (num > biggest) { secondBiggest = biggest biggest = num } else { secondBiggest = max(secondBiggest.toDouble(), num.toDouble()).toInt() } if (num < smallest) { secondSmallest = smallest smallest = num } else { secondSmallest = min(secondSmallest.toDouble(), num.toDouble()).toInt() } } return biggest * secondBiggest - smallest * secondSmallest } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,889
kotlab
Apache License 2.0
src/main/kotlin/Day11.kt
N-Silbernagel
573,145,327
false
{"Kotlin": 118156}
import java.util.* fun main() { val input = readFileAsList("Day11") println(Day11.part1(input)) println(Day11.part2(input)) } object Day11 { fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) repeat(20) { for (monkey in monkeys) { for (item in monkey.items) { inspectItem(monkey, item, monkeys) { it / 3 } } monkey.items.clear() } } return calculateMonkeyBusiness(monkeys) } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input) val modulus = monkeys.map { it.testDivisor }.reduce(Int::times) repeat(10_000) { for (monkey in monkeys) { for (item in monkey.items) { inspectItem(monkey, item, monkeys) { it % modulus } } monkey.items.clear() } } return calculateMonkeyBusiness(monkeys) } private fun inspectItem( monkey: Monkey, item: Long, monkeys: MutableList<Monkey>, manageWorryLevel: (Long) -> Long ) { val worryLevelAfterOperation = monkey.operation(item) val worryLevelOfItem = manageWorryLevel(worryLevelAfterOperation) val test = worryLevelOfItem % monkey.testDivisor == 0L val throwToMonkey = if (test) monkey.trueMonkey else monkey.falseMonkey monkeys[throwToMonkey].items.add(worryLevelOfItem) monkey.inspections++ } private fun calculateMonkeyBusiness(monkeys: MutableList<Monkey>): Long { val mostActiveMonkeysMonkeyBusiness = TreeSet<Long>() for (monkey in monkeys) { mostActiveMonkeysMonkeyBusiness.add(monkey.inspections) if (mostActiveMonkeysMonkeyBusiness.size > 2) { mostActiveMonkeysMonkeyBusiness.remove(mostActiveMonkeysMonkeyBusiness.first()) } } return mostActiveMonkeysMonkeyBusiness.first() * mostActiveMonkeysMonkeyBusiness.last() } private fun parseMonkeys(input: List<String>): MutableList<Monkey> { val monkeys = mutableListOf<Monkey>() val monkeyDescriptions = input.chunked(7) for (monkeyDescription in monkeyDescriptions) { var startingItems: MutableList<Long>? = null var operation: ((Long) -> Long)? = null var testDivisor: Int? = null var trueMonkey: Int? = null var falseMonkey: Int? = null for (inputLine in monkeyDescription) { if (inputLine.isBlank()) { continue } if (inputLine.startsWith("Monkey")) { continue } if (inputLine.startsWith(" Starting items")) { val startingItemsString = inputLine.substringAfter(" Starting items: ") startingItems = startingItemsString.split(", ") .map { it.toLong() } .toMutableList() } if (inputLine.startsWith(" Operation")) { val operationString = inputLine.substringAfter(" Operation: new = old ") val mathOperation = operationString[0] val operantString = operationString.substring(2) if (operantString == "old") { operation = { it * it } continue } val operant = operantString.toInt() if (mathOperation == '+') { operation = { it + operant } } if (mathOperation == '*') { operation = { it * operant } } } if (inputLine.startsWith(" Test")) { val operationString = inputLine.substringAfter(" Test: divisible by ") val divisor = operationString.toInt() testDivisor = divisor } if (inputLine.startsWith(" If true")) { val otherMonkey = inputLine.substringAfter(" If true: throw to monkey ") .toInt() trueMonkey = otherMonkey } if (inputLine.startsWith(" If false")) { val otherMonkey = inputLine.substringAfter(" If false: throw to monkey ") .toInt() falseMonkey = otherMonkey } } val monkey = Monkey(startingItems!!, operation!!, 0, testDivisor!!, trueMonkey!!, falseMonkey!!) monkeys.add(monkey) } return monkeys } data class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, var inspections: Long, val testDivisor: Int, val trueMonkey: Int, val falseMonkey: Int, ) }
0
Kotlin
0
0
b0d61ba950a4278a69ac1751d33bdc1263233d81
5,072
advent-of-code-2022
Apache License 2.0
src/main/java/com/barneyb/aoc/aoc2022/day21/MonkeyMath.kt
barneyb
553,291,150
false
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
package com.barneyb.aoc.aoc2022.day21 import com.barneyb.aoc.util.Solver import com.barneyb.aoc.util.toLong import com.barneyb.aoc.util.toSlice import com.barneyb.util.HashSet fun main() { Solver.execute( ::parse, ::rootYellsWhat, // 82,225,382,988,628 ::whatToYell, // 3,429,411,069,028 ) } internal sealed interface Monkey private typealias Op = Char internal data class Yell( val n: Long, ) : Monkey internal data class Operation( val a: CharSequence, val b: CharSequence, val op: Op, ) : Monkey // dbpl: 5 // pppw: cczh / lfqf internal fun parse(input: String) = input.toSlice() .trim() .lines() .associateBy({ l -> l.take(4) }) { l -> if (l.length < 17) Yell(l.drop(6).toLong()) else Operation( l.drop(6).take(4), l.drop(13).take(4), l[11], ) } private val ROOT = "root".toSlice() private val HUMAN = "humn".toSlice() private fun doOp(a: Long, op: Op, b: Long) = when (op) { '+' -> a + b '-' -> a - b '*' -> a * b '/' -> a / b else -> throw IllegalStateException("Unknown '$op' operator") } private fun whoYellsWhat( who: CharSequence, byName: Map<CharSequence, Monkey> ): Long { val map = HashMap(byName) fun compute(name: CharSequence): Long = when (val it = map[name]!!) { is Yell -> it.n is Operation -> { val a = compute(it.a) val b = compute(it.b) val n = doOp(a, it.op, b) map[name] = Yell(n) n } } return compute(who) } internal fun rootYellsWhat(byName: Map<CharSequence, Monkey>) = whoYellsWhat(ROOT, byName) // r = x + b, what is x? private fun invOp(r: Long, op: Op, b: Long) = when (op) { '+' -> r - b '-' -> r + b '*' -> r / b '/' -> r * b else -> throw IllegalStateException("Unknown '$op' operator") } // r = a + x, what is x? private fun invOp(r: Long, a: Long, op: Op) = when (op) { '+' -> r - a '-' -> a - r '*' -> r / a '/' -> a / r else -> throw IllegalStateException("Unknown '$op' operator") } internal fun whatToYell(byName: Map<CharSequence, Monkey>): Long { val humanBased = HashSet<CharSequence>(HUMAN) fun hasHuman(name: CharSequence): Boolean { return when (val it = byName[name]!!) { is Yell -> name == HUMAN is Operation -> if (hasHuman(it.a) || hasHuman(it.b)) { humanBased.add(name) true } else false } } fun toYell(name: CharSequence, answer: Long): Long { return when (val it = byName[name]!!) { is Yell -> if (name == HUMAN) answer else it.n is Operation -> { if (humanBased.contains(it.a)) { val other = whoYellsWhat(it.b, byName) val next = invOp(answer, it.op, other) // println("$answer = x ${it.op} $other :: x=$next") toYell(it.a, next) } else { // b has/is the human val other = whoYellsWhat(it.a, byName) val next = invOp(answer, other, it.op) // println("$answer = $other ${it.op} x :: x=$next") toYell(it.b, next) } } } } val root = byName[ROOT] as Operation val (base, other) = if (hasHuman(root.a)) Pair(root.a, root.b) else Pair(root.b, root.a) val goal = whoYellsWhat(other, byName) // println("$base must yell $goal (like ${other})") return toYell(base, goal) }
0
Kotlin
0
0
8b5956164ff0be79a27f68ef09a9e7171cc91995
3,896
aoc-2022
MIT License
src/test/kotlin/com/igorwojda/list/sort/quicksort/Solution.kt
igorwojda
159,511,104
false
{"Kotlin": 254856}
package com.igorwojda.list.sort.quicksort // Time complexity (Best): Ω(n log(n)) // Time complexity (Average): Θ(l log(n)) // Time complexity (Worst): O(n^2) // Space complexity: O(log(n)) private object Solution1 { private fun quickSort(list: MutableList<Int>, left: Int = 0, right: Int = list.lastIndex): List<Number> { // Rearrange elements and returns correct index of the pivot // All elements smaller than element will be on the left side of the array (smaller indexes) // All elements larger than element will be on the left side of the array (lager indexes) fun pivot(list: MutableList<Int>, start: Int = 0, end: Int = list.lastIndex): Int { val pivot = list[start] // We decide that pivot is our first element (it can be any element) var swapIndex = start // first index that we can swap (number of element that are less than pivot) (start + 1..end).forEach { if (pivot > list[it]) { swapIndex++ list.swap(it, swapIndex) } } list.swap(start, swapIndex) return swapIndex } if (left < right) { val pivotIndex = pivot(list, left, right) // Sort left part quickSort(list, left, pivotIndex - 1) // Sort right part quickSort(list, pivotIndex + 1, right) } return list } private fun <T> MutableList<T>.swap(index1: Int, index2: Int) { val tmp = this[index1] this[index1] = this[index2] this[index2] = tmp } } // Time complexity (Best): Ω(n^2) // Time complexity (Average): Θ(n^2) // Time complexity (Worst): O(n^2) // Space complexity: O(n) private object Solution2 { private fun quickSort(list: MutableList<Int>): List<Number> { if (list.isEmpty()) { return list } val pivot = list.first() // We selected first element as pivot (it can be any element) var pivotIndex = 0 // first index that we can swap (number of element that are less than pivot) (0..list.lastIndex).forEach { if (pivot > list[it]) { list.swap(it, pivotIndex + 1) pivotIndex++ } } // Move element to the correct index // All elements smaller than element will be on the left side of the array (smaller indexes) // All elements larger than element will be on the left side of the array (lager indexes) list.swap(0, pivotIndex) // Create left sub-list val left = list.subList(0, pivotIndex) // Create right sub-list val right = list.subList(pivotIndex + 1, list.size) return quickSort(left) + listOf(pivot) + quickSort(right) } private fun <T> MutableList<T>.swap(index1: Int, index2: Int) { val tmp = this[index1] this[index1] = this[index2] this[index2] = tmp } } private object KtLintWillNotComplain
9
Kotlin
225
895
b09b738846e9f30ad2e9716e4e1401e2724aeaec
3,030
kotlin-coding-challenges
MIT License
kotlin/src/main/kotlin/AoC_Day22.kt
sviams
115,921,582
false
null
import kotlin.collections.HashMap object AoC_Day22 { // So...in Kotlin, Map<K,V> is actually a LinkedHashMap behind the scenes // because JetBrains want to preserve order, which might be useful when doing // transformations from List -> Map -> List or whatever. // It is however most harmful to insertion/removal performance when the map // grows large. Hence, in lieu of a native Kotlin unordered map implementation // I opted to extend HashMap with plus and pretend it's immutable fun <K,V> HashMap<K,V>.plus(pair: Pair<K,V>) : HashMap<K,V> { return this.apply { put(pair.first, pair.second) } } data class Position(val x: Int, val y: Int) fun turn(from: Position, change: Position) : Position = when (from) { UP -> if (change == RIGHT) RIGHT else LEFT LEFT -> if (change == RIGHT) UP else DOWN DOWN -> if (change == RIGHT) LEFT else RIGHT else -> if (change == RIGHT) DOWN else UP } fun reverse(from: Position) : Position = when (from) { UP -> DOWN LEFT -> RIGHT DOWN -> UP else -> LEFT } fun move(from: Position, direction: Position) = Position((from.x + direction.x), (from.y + direction.y)) data class State(val pos: Position, val direction: Position, val accInfected: Int, val infected: HashMap<Position, Int>) val UP = Position(0,1) val LEFT = Position(-1,0) val DOWN = Position(0,-1) val RIGHT = Position(1, 0) val CLEAN : Int = 0 val WEAK: Int = 1 val INFECTED : Int = 2 val FLAGGED : Int = 3 fun parseStartState(input: List<String>): State { val center : Int = Math.ceil((input.size / 2).toDouble()).toInt() val infected = input.foldIndexed(emptyList<Position>()) { y, acc, row -> acc + lineToCoords(row, center-y, center)} val infMap: HashMap<Position, Int> = infected.associate { it to INFECTED }.toMap(HashMap(16)) return AoC_Day22.State(Position(0, 0), UP, 0, infMap) } fun lineToCoords(row: String, y: Int, size: Int) : List<Position> = row.toCharArray().foldIndexed(emptyList()) {x, acc, c -> if (c == '#') acc + Position((x-size), y) else acc} fun solvePt1(input: List<String>, iterations: Int) : Int = generateSequence(parseStartState(input)) { state -> val current = state.infected.getOrDefault(state.pos, CLEAN) if (current == INFECTED) { val newDir = turn(state.direction, RIGHT) State(move(state.pos, newDir), newDir, state.accInfected, state.infected.plus(state.pos to CLEAN)) } else { val newDir = turn(state.direction, LEFT) State(move(state.pos, newDir), newDir, state.accInfected + 1, state.infected.plus(state.pos to INFECTED)) } }.take(iterations + 1).last().accInfected fun solvePt2(input: List<String>, iterations: Int) : Int = generateSequence(parseStartState(input)) { state -> when (state.infected[state.pos]) { INFECTED -> { val newDir = turn(state.direction, RIGHT) State(move(state.pos, newDir), newDir, state.accInfected, state.infected.plus(state.pos to FLAGGED)) } WEAK -> { State(move(state.pos, state.direction), state.direction, state.accInfected + 1, state.infected.plus(state.pos to INFECTED)) } FLAGGED -> { val newDir = reverse(state.direction) State(move(state.pos, newDir), newDir, state.accInfected, state.infected.plus(state.pos to CLEAN)) } else -> { val newDir = turn(state.direction, LEFT) State(move(state.pos, newDir), newDir, state.accInfected, state.infected.plus(state.pos to WEAK)) } } }.take(iterations + 1).last().accInfected }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
4,068
aoc17
MIT License
src/Day10.kt
mihansweatpants
573,733,975
false
{"Kotlin": 31704}
import java.lang.IllegalStateException import kotlin.math.abs fun main() { fun part1(instructions: List<CPUInstruction>): Int { val interestingCycles = setOf(20, 60, 100, 140, 180, 220) var sumOfInterestingSignalStrengths = 0 var register = 1 var currentCycle = 0 for (instruction in instructions) { repeat(instruction.cyclesToComplete) { currentCycle++ if (currentCycle in interestingCycles) { sumOfInterestingSignalStrengths += currentCycle * register } } when (instruction.operator) { "addx" -> register += instruction.argument } } return sumOfInterestingSignalStrengths } fun part2(instructions: List<CPUInstruction>): String { val crtRows = mutableListOf<List<String>>() var register = 1 var currentCycle = 0 var currentCrtRow = mutableListOf<String>() for (instruction in instructions) { repeat(instruction.cyclesToComplete) { val currentPixel = currentCrtRow.size if (abs(register - currentPixel) <= 1) { currentCrtRow.add("#") } else { currentCrtRow.add(".") } if (currentCrtRow.size == 40) { crtRows.add(currentCrtRow) currentCrtRow = mutableListOf() } currentCycle++ } when (instruction.operator) { "addx" -> register += instruction.argument } } return crtRows.joinToString("\n") { it.joinToString() .replace(".", " ") .replace(",", " ") } } val input = readInput("Day10") .lines() .map { it.parseInstruction() } println(part1(input)) println(part2(input)) } private class CPUInstruction( val operator: String, val argument: Int = 0 ) { val cyclesToComplete: Int get() = when (operator) { "addx" -> 2 "noop" -> 1 else -> throw IllegalStateException("Unknown operator $operator") } } private fun String.parseInstruction(): CPUInstruction { val components = this.split(" ") return if (components.size == 1) { CPUInstruction(components[0]) } else { CPUInstruction(components[0], components[1].toInt()) } }
0
Kotlin
0
0
0de332053f6c8f44e94f857ba7fe2d7c5d0aae91
2,521
aoc-2022
Apache License 2.0
src/Day08.kt
maciekbartczak
573,160,363
false
{"Kotlin": 41932}
fun main() { fun part1(input: List<String>): Int { val grid = makeGrid(input) return getVisibleTrees(grid) } fun part2(input: List<String>): Int { val grid = makeGrid(input) return grid .flatMapIndexed { y, row -> List(row.size) { x -> grid.getScenicScore(x, y) } } .maxOf { it } } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) } private fun makeGrid(input: List<String>): List<List<Int>> { val grid = mutableListOf<List<Int>>() input .map { it.toIntArray() } .forEach { grid.add(it) } return grid } private fun getVisibleTrees(grid: List<List<Int>>): Int { val width = grid.first().size val height = grid.size var visibleTrees = (width + height) * 2 - 4 println(visibleTrees) for (y in 1 until height - 1) { for (x in 1 until width - 1) { if (grid.isTreeVisible(x, y)) { println("tree at $x, $y is visible") visibleTrees++ } } } return visibleTrees } private fun String.toIntArray(): List<Int> { return this .toCharArray() .map { it.digitToInt() } } private fun List<List<Int>>.isTreeVisible(x: Int, y: Int): Boolean { return this.checkRowVisibility(x, y) || this.checkColumnVisibility(x, y) } private fun List<List<Int>>.checkRowVisibility(x: Int, y: Int): Boolean { val row = this[y] val tree = this[y][x] var visible = true for (i in 0 until x) { if (row[i] >= tree) { visible = false } } if (visible) { return true } for (i in x + 1 until row.size) { if (row[i] >= tree) { return false } } return true } private fun List<List<Int>>.checkColumnVisibility(x: Int, y: Int): Boolean { val tree = this[y][x] var visible = true // check the upper side first for (i in 0 until y) { if (this[i][x] >= tree) { visible = false } } if (visible) { return true } for (i in y + 1 until this.size) { if (this[i][x] >= tree) { return false } } return true } private fun List<List<Int>>.getScenicScore(x: Int, y: Int): Int { val visibleTrees = mutableMapOf( 'L' to 0, 'R' to 0, 'U' to 0, 'D' to 0 ) val row = this[y] val tree = row[x] for (i in x - 1 downTo 0) { visibleTrees['L'] = visibleTrees['L']!! + 1 if (row[i] >= tree) { break } } for (i in x + 1 until row.size) { visibleTrees['R'] = visibleTrees['R']!! + 1 if (row[i] >= tree) { break } } for (i in y - 1 downTo 0) { visibleTrees['U'] = visibleTrees['U']!! + 1 if (this[i][x] >= tree) { break } } for (i in y + 1 until this.size) { visibleTrees['D'] = visibleTrees['D']!! + 1 if (this[i][x] >= tree) { break } } return visibleTrees .values .reduce { acc, i -> acc * i } }
0
Kotlin
0
0
53c83d9eb49d126e91f3768140476a52ba4cd4f8
3,334
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/freekdb/aoc2019/Day06.kt
FreekDB
228,241,398
false
null
package com.github.freekdb.aoc2019 import java.io.File private const val CENTER_OF_MASS = "COM" private const val SANTA = "SAN" private const val YOU = "YOU" // https://adventofcode.com/2019/day/6 fun main() { val orbitMap = mutableMapOf<String, MutableList<String>>() val reverseOrbitMap = mutableMapOf<String, String>() File("input/day-06--input.txt") .readLines() .filter { it.isNotEmpty() } .map { it.split(")") } .forEach { val sourceObject = it[0] val destinationObject = it[1] val destinations = orbitMap.getOrPut(sourceObject, { mutableListOf() }) destinations.add(destinationObject) reverseOrbitMap[destinationObject] = sourceObject } val orbitCountMap = mutableMapOf(CENTER_OF_MASS to 0) extendOrbitCountMap( CENTER_OF_MASS, orbitMap, orbitCountMap ) // Part 1. println("Total number of direct and indirect orbits: ${orbitCountMap.values.sum()}.") // Part 2. val pathToYou = getPathToStart(YOU, reverseOrbitMap) val pathToSanta = getPathToStart(SANTA, reverseOrbitMap) val firstIntersection = pathToYou.intersect(pathToSanta).first() val minimumOrbitalTransfers = pathToYou.indexOf(firstIntersection) - 1 + pathToSanta.indexOf(firstIntersection) - 1 println("Minimum number of orbital transfers: $minimumOrbitalTransfers") } fun extendOrbitCountMap(sourceObject: String, orbitMap: Map<String, List<String>>, orbitCountMap: MutableMap<String, Int>) { val sourceOrbitCount = orbitCountMap[sourceObject] ?: 0 val destinations = orbitMap[sourceObject] destinations?.forEach { orbitCountMap[it] = sourceOrbitCount + 1 extendOrbitCountMap(it, orbitMap, orbitCountMap) } } fun getPathToStart(finalDestination: String, reverseOrbitMap: MutableMap<String, String>) = generateSequence(finalDestination) { objectName -> reverseOrbitMap[objectName].takeIf { it != CENTER_OF_MASS } }.toList()
0
Kotlin
0
1
fd67b87608bcbb5299d6549b3eb5fb665d66e6b5
2,055
advent-of-code-2019
Apache License 2.0
src/main/kotlin/days/Day14.kt
hughjdavey
159,955,618
false
null
package days class Day14 : Day(14) { override fun partOne(): Any { return recipeScoresAfter(inputString.trim().toInt()) } override fun partTwo(): Any { println("// Day 14 Part 2 takes about 9 seconds...") return recipeScoresBefore(inputString.trim()) } data class Elf(var indexOfCurrentRecipe: Int) { fun chooseNext(scoreboard: List<Int>) { val steps = scoreboard[indexOfCurrentRecipe] + 1 for (i in 0 until steps) { if (++indexOfCurrentRecipe > scoreboard.lastIndex) { indexOfCurrentRecipe = 0 } } } } companion object { // todo performance of next 2 methods isn't ideal but i have already improved it a lot! fun recipeScoresAfter(after: Int): String { val minSize = after + 10 val elves = Day14.Elf(0) to Day14.Elf(1) var scoreboard = mutableListOf(3, 7) while (scoreboard.size <= minSize) { scoreboard = foo(elves, scoreboard) //System.err.println(minSize - scoreboard.size) } return scoreboard.dropLast(scoreboard.size - minSize).takeLast(10).joinToString("") } fun recipeScoresBefore(pattern: String): Int { val elves = Day14.Elf(0) to Day14.Elf(1) var scoreboard = mutableListOf(3, 7) while (!scoreboard.takeLast(10).joinToString("").contains(pattern)) { scoreboard = foo(elves, scoreboard) //System.err.println(scoreboard.size) } return scoreboard.joinToString("").indexOf(pattern) } fun foo(elves: Pair<Elf, Elf>, scoreboard: MutableList<Int>): MutableList<Int> { val elf1Current = scoreboard[elves.first.indexOfCurrentRecipe] val elf2Current = scoreboard[elves.second.indexOfCurrentRecipe] val sum = (elf1Current + elf2Current).toString() val newRecipes = sum.map { Character.getNumericValue(it) } //val toReturn = scoreboard.plus(newRecipes) scoreboard.addAll(newRecipes) elves.toList().forEach { it.chooseNext(scoreboard) } return scoreboard } fun scoreboardToString(elves: Pair<Elf, Elf>, scoreboard: List<Int>): String { return scoreboard.mapIndexed { index, recipe -> when (index) { elves.first.indexOfCurrentRecipe -> "($recipe)" elves.second.indexOfCurrentRecipe -> "[$recipe]" else -> recipe.toString() } }.joinToString(" ") } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
2,705
aoc-2018
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/PossiblyEquals.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.DECIMAL import java.lang.Character.isDigit /** * 2060. Check if an Original String Exists Given Two Encoded Strings * @see <a href="https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings"> * Source</a> */ fun interface PossiblyEquals { operator fun invoke(s1: String, s2: String): Boolean } class PossiblyEqualsDFS : PossiblyEquals { override operator fun invoke(s1: String, s2: String): Boolean { val l1: Int = s1.length val l2: Int = s2.length val dp = Array(l1 + 1) { Array(l2 + 1) { arrayOfNulls<Boolean>(LIMIT2) } } return dfs(0, 0, 0, s1.toCharArray(), s2.toCharArray(), dp) } private fun dfs( i: Int, j: Int, diff: Int, s1: CharArray, s2: CharArray, dp: Array<Array<Array<Boolean?>>>, ): Boolean { if (i == s1.size && j == s2.size) { return diff == 0 } if (dp[i][j][diff + LIMIT1] != null) return dp[i][j][diff + LIMIT1]!! if (i < s1.size && j < s2.size && diff == 0 && s1[i] == s2[j] && dfs(i + 1, j + 1, 0, s1, s2, dp)) { dp[i][j][LIMIT1] = true return true } if (i < s1.size && !isDigit(s1[i]) && diff > 0 && dfs(i + 1, j, diff - 1, s1, s2, dp)) { dp[i][j][diff + LIMIT1] = true return true } if (j < s2.size && !isDigit(s2[j]) && diff < 0 && dfs(i, j + 1, diff + 1, s1, s2, dp)) { return true.also { dp[i][j][diff + LIMIT1] = it } } var k = j var value = 0 while (k < s2.size && isDigit(s2[k])) { value = value * DECIMAL + (s2[k].code - '0'.code) if (dfs(i, k + 1, diff + value, s1, s2, dp)) { dp[i][j][diff + LIMIT1] = true return true } ++k } dp[i][j][diff + LIMIT1] = true return false } companion object { private const val LIMIT1 = 1000 private const val LIMIT2 = 2000 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,762
kotlab
Apache License 2.0
src/me/anno/knoq/KNoqSolver.kt
AntonioNoack
504,659,355
false
null
package me.anno.knoq import me.anno.Engine import me.anno.utils.strings.StringHelper.levenshtein import java.util.* fun findIsEqual(rules: List<Rule>, input: String, output: String, maxTries: Int) = findIsEqual(rules, KNoqLang.parse(input), KNoqLang.parse(output), maxTries) fun findIsEqual(rules: List<Rule>, input: Expr, output: Expr, maxTries: Int): List<Expr>? { class NewExpr(val value: Expr, val cost: Int, val depth: Int) { operator fun component1() = value operator fun component2() = cost operator fun component3() = depth } fun Expr.length(): Int { return when (this) { is String -> length is Func -> size else -> toString().length } } val added = HashSet<Expr>() val map = HashMap<Expr, Expr>() val todo = PriorityQueue<NewExpr> { a, b -> val c = a.cost.compareTo(b.cost) if (c == 0) a.value.toString().compareTo(b.value.toString()) else c } todo.add(NewExpr(input, 0, 0)) added.add(input) var maxCost = 10 var lastTime = Engine.nanoTime val outputStr = output.toString() search@ while (todo.isNotEmpty()) { val (term, cost, depth) = todo.poll() if (cost >= 2 * maxCost || (Engine.nanoTime > 1e9 + lastTime)) { maxCost = cost lastTime = Engine.nanoTime println("checking cost $cost, ${added.size} checked, $term") } for (rule in rules) { val all = rule.applyAll2(term) val numRuleMatches = all.size for (i in all.indices) { val newTerm = all[i] if (newTerm == output) { println("found path after ${added.size} entries, cost $cost") // found path :) val answer = ArrayList<Expr>() answer.add(newTerm) var path = term while (true) { answer.add(path) path = map[path] ?: break } answer.reverse() return answer } if (added.add(newTerm)) { map[newTerm] = term val newCost = depth + // ancestry cost newTerm.length() + // cost for length 1 + // base cost numRuleMatches + // rules that can be applied everywhere should be less desirable // 731,502 -> 601,438 // cost for having a different structure from the target // 13615,1058 -> 1832,1218 (so yes, helps sometimes) newTerm.toString().levenshtein(outputStr, ignoreCase = false) todo.add(NewExpr(newTerm, newCost, depth + 1)) } } if (added.size > maxTries) { println("exceeded trial limit of $maxTries, last cost: $cost") return null } } } return null }
0
Kotlin
0
0
e163430c52f92fa71a32052c72581076e3f1ae71
3,097
KNoq
Apache License 2.0
src/main/kotlin/codes/jakob/aoc/solution/Day06.kt
The-Self-Taught-Software-Engineer
433,875,929
false
{"Kotlin": 56277}
package codes.jakob.aoc.solution object Day06 : Solution() { override fun solvePart1(input: String): Any { return simulateDays(parseInput(input), 80) } override fun solvePart2(input: String): Any { return simulateDays(parseInput(input), 256) } private fun simulateDays(initialTimerValues: List<Int>, days: Int): ULong { var fishToAmount: Map<Int, ULong> = initialTimerValues.countBy { it }.mapValues { it.value.toULong() } println("Starting with ${fishToAmount.values.sum()} fish") repeat(days) { day -> fishToAmount = fishToAmount .flatMap { (timeUntilProcreation, amount) -> if (timeUntilProcreation == 0) { listOf(6 to amount, 8 to amount) } else { listOf((timeUntilProcreation - 1) to amount) } } .groupBy({ it.first }, { it.second }) .mapValues { (_, amounts) -> amounts.sum() } println("Population reached ${fishToAmount.values.sum()} fish after day ${day + 1}") } return fishToAmount.values.sum() } private fun parseInput(input: String): List<Int> { return input.split(",").map { it.toInt() } } } fun main() { Day06.solve() }
0
Kotlin
0
6
d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c
1,336
advent-of-code-2021
MIT License
solution/kotlin/day20/src/main/kotlin/domain/yahtzee/original/YahtzeeCalculator.kt
advent-of-craft
721,598,788
false
{"Java": 240720, "C#": 208054, "Kotlin": 162843, "TypeScript": 162359, "Shell": 16244, "JavaScript": 10227}
package domain.yahtzee.original object YahtzeeCalculator { private const val ROLL_LENGTH = 5 private const val MINIMUM_DIE = 1 private const val MAXIMUM_DIE = 6 fun number(dice: IntArray, number: Int): Int = calculate( { d -> d.filter { die -> die == number }.sum() }, dice ) fun threeOfAKind(dice: IntArray): Int = calculateNOfAKind(dice, 3) fun fourOfAKind(dice: IntArray): Int = calculateNOfAKind(dice, 4) fun yahtzee(dice: IntArray): Int = calculate( { d -> if (hasNOfAKind(d, 5)) Scores.YAHTZEE_SCORE else 0 }, dice ) private fun calculateNOfAKind(dice: IntArray, n: Int): Int = calculate( { d -> if (hasNOfAKind(d, n)) d.sum() else 0 }, dice ) fun fullHouse(dice: IntArray): Int = calculate( { d -> groupDieByFrequency(d) .let { dieFrequency -> if (dieFrequency.containsValue(3) && dieFrequency.containsValue(2)) Scores.HOUSE_SCORE else 0 } }, dice ) fun largeStraight(dice: IntArray): Int = calculate({ d -> if (d.sorted() .windowed(2) .all { pair -> pair[0] + 1 == pair[1] } ) Scores.LARGE_STRAIGHT_SCORE else 0 }, dice) fun smallStraight(dice: IntArray): Int = calculate({ d -> toSortedString(d) .let { diceString -> if (isSmallStraight(diceString)) 30 else 0 } }, dice) private fun isSmallStraight(diceString: String): Boolean = diceString.contains("1234") || diceString.contains("2345") || diceString.contains("3456") private fun hasNOfAKind(dice: IntArray, n: Int): Boolean = groupDieByFrequency(dice) .values .any { count -> count >= n } private fun toSortedString(dice: IntArray): String = dice.sorted() .distinct() .joinToString("") fun chance(dice: IntArray): Int = calculate( { d -> d.sum() }, dice ) private fun groupDieByFrequency(dice: IntArray): Map<Int, Int> = dice.toList() .groupingBy { x -> x } .eachCount() private fun calculate(compute: (dice: IntArray) -> Int, dice: IntArray): Int { dice.validateRoll() return compute(dice) } private fun IntArray.validateRoll() { require(!hasInvalidLength()) { "Invalid dice... A roll should contain 6 dice." } require(!containsInvalidDie()) { "Invalid die value. Each die must be between 1 and 6." } } private fun IntArray.hasInvalidLength(): Boolean = size != ROLL_LENGTH private fun IntArray.containsInvalidDie(): Boolean = any { die -> die.isValid() } private fun Int.isValid(): Boolean = this < MINIMUM_DIE || this > MAXIMUM_DIE private object Scores { const val YAHTZEE_SCORE = 50 const val HOUSE_SCORE = 25 const val LARGE_STRAIGHT_SCORE = 40 } }
0
Java
60
71
3cc9e8b2c59963db97919b808a8285fbe3157c34
2,872
advent-of-craft
MIT License
06/part_two.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File const val LAST_DAY = 80 fun readInput() : List<Int> { return File("input.txt") .readLines() .flatMap { it.split(",") } .map { it.toInt() } } class LanternFishPopulation(timers : List<Int>) { companion object { const val MAX_TIMER = 8 const val TIMER_AFTER_0 = 6 } private val timersFreq = MutableList<Int>(MAX_TIMER + 1) { 0 } private var daysPassed = 0 init { for (timer in timers) { timersFreq[timer]++ } } fun passDay() { daysPassed++ val freqWithTimerZero = timersFreq[0] for (i in 1..MAX_TIMER) { timersFreq[i - 1] = timersFreq[i] } timersFreq[MAX_TIMER] = freqWithTimerZero timersFreq[TIMER_AFTER_0] += freqWithTimerZero } fun totalPopulation() : Int { return timersFreq.sum() } } fun solve(timers : List<Int>) : Int { val lanternFishPopulation = LanternFishPopulation(timers) for (day in 1..LAST_DAY) { lanternFishPopulation.passDay() } return lanternFishPopulation.totalPopulation() } fun main() { val timers = readInput() val ans = solve(timers) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
1,231
advent-of-code-2021
MIT License
src/main/kotlin/dev/bogwalk/batch4/Problem46.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch4 import dev.bogwalk.util.maths.isPrime import dev.bogwalk.util.maths.primeNumbers import kotlin.math.floor import kotlin.math.sqrt /** * Problem 46: Goldbach's Other Conjecture * * https://projecteuler.net/problem=46 * * Goal: Return the number of ways an odd composite number, N, can be represented as proposed by * Goldbach's Conjecture, detailed below. * * Constraints: 9 <= N < 5e5 * * Goldbach's False Conjecture: Every odd composite number can be written as the sum of a prime * and twice a square. Proven to be FALSE. * * e.g. 9 = 7 + 2 * 1^2 * 15 = 7 + 2 * 2^2 || 13 + 2 * 1^2 * 21 = 3 + 2 * 3^2 || 13 + 2 * 2^2 || 19 + 2 * 1^2 * 25 = 7 + 2 * 3^2 || 17 + 2 * 2^2 || 23 + 2 * 1^2 * 27 = 19 + 2 * 2^2 * 33 = 31 + 2 * 1^2 * * e.g.: N = 9 * result = 1 * N = 15 * result = 2 */ class GoldbachsOtherConjecture { /** * Returns count of primes that allow [n] to be represented as per Goldbach's false conjecture. * * @param [n] an odd composite number (no in-built check to ensure it is not prime). */ fun countGoldbachRepresentations(n: Int): Int { return primeNumbers(n) .drop(1) .count { prime -> n.isGoldbachOther(prime) } } private fun Int.isGoldbachOther(prime: Int): Boolean { val repr = sqrt((this - prime) / 2.0) return repr == floor(repr) } /** * Project Euler specific implementation that returns the smallest odd composite that cannot * be written, as proposed, as the sum of a prime and twice a square. * * The found value can be confirmed by using it as an argument in the HackerRank problem * solution above, as seen in the test cases. */ fun smallestFailingComposite(): Int { // starting limit guessed with contingency block later down var limit = 5000 var primes = primeNumbers(limit).drop(1) // starting point as provided in example var composite = 33 nextC@while (true) { composite += 2 if (composite.isPrime()) continue@nextC for (prime in primes) { if (prime > composite) break@nextC if (composite.isGoldbachOther(prime)) continue@nextC } // if reached, means not enough primes for current composite limit += 5000 primes = primeNumbers(limit).drop(1) composite -= 2 } return composite } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,587
project-euler-kotlin
MIT License
src/Day03.kt
tristanrothman
572,898,348
false
null
fun main() { fun Char.priority(): Int { return if (this.isLowerCase()) { this - 'a' + 1 } else { this - 'A' + 27 } } fun part1(input: List<String>): Int { return input.map { rucksack -> val compartmentSize = rucksack.length / 2 rucksack.substring(0, compartmentSize).toCharArray() to rucksack.substring(compartmentSize).toCharArray() }.flatMap { it.first intersect it.second.toSet() }.sumOf { it.priority() } } fun part2(input: List<String>): Int { return input.map { it.toCharArray() } .chunked(3) .flatMap { it.component1() intersect it.component2().toSet() intersect it.component3().toSet() }.sumOf { it.priority() } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e794ab7e0d50f22d250c65b20e13d9b5aeba23e2
986
advent-of-code-2022
Apache License 2.0
kotlin/src/main/kotlin/supermarket/model/offers/BundleDiscountOffer.kt
vinaysshenoy
197,952,789
true
{"Kotlin": 92616, "C++": 16827, "Java": 13115, "C#": 12980, "TypeScript": 12246, "Ruby": 7985, "CMake": 1669}
package supermarket.model.offers import supermarket.ProductQuantities import supermarket.model.Discount import supermarket.model.Product import supermarket.model.ProductQuantity import supermarket.model.SupermarketCatalog data class BundleDiscountOffer( val bundle: Set<ProductQuantity>, val discountPercent: Double ) : Offer { init { if (bundle.size <= 1) throw IllegalArgumentException("Bundle must have at least 2 products!") } override fun discount(allProducts: ProductQuantities, catalog: SupermarketCatalog): Discount { val applicableProductsInDiscount: Set<Product> = applicableProducts() val productQuantitiesInOffer: Set<ProductQuantity> = allProducts .filter { (product, _) -> product in applicableProductsInDiscount } .filter { (product, totalQuantity) -> totalQuantity >= minimumQuantityOfProductInBundle(product) } .map { (product, totalQuantity) -> ProductQuantity(product, totalQuantity) } .toSet() val occurrencesOfBundle: Int = bundle .map { productQuantity -> occurrencesOfProductWithQuantity(productQuantity, productQuantitiesInOffer) } .toList() // The only case where !! can be thrown is if the list // returns no elements, i.e, the bundle is an empty set. // We already check for this during initialization. .min()!! val combinedUnitPriceOfBundle: Double = bundle .map { (product, quantity) -> quantity * catalog.getUnitPrice(product) } .sum() val totalPriceOfBundleProductsBeforeDiscount = occurrencesOfBundle * combinedUnitPriceOfBundle val discountAmount = totalPriceOfBundleProductsBeforeDiscount * (discountPercent / 100.0) val discountProducts = productQuantitiesInOffer .map { productQuantity -> productQuantityIncludedInBundle(productQuantity, occurrencesOfBundle) } .toSet() return Discount(discountProducts, discountAmount) } private fun productQuantityIncludedInBundle( productQuantity: ProductQuantity, occurrencesOfBundle: Int ): ProductQuantity { return ProductQuantity( product = productQuantity.product, quantity = bundle.find { it.product == productQuantity.product }!!.quantity * occurrencesOfBundle ) } private fun occurrencesOfProductWithQuantity( bundleProductToFind: ProductQuantity, products: Set<ProductQuantity> ): Int { val foundProduct = products.find { it.product == bundleProductToFind.product } return foundProduct?.quantity?.div(bundleProductToFind.quantity)?.toInt() ?: 0 } private fun minimumQuantityOfProductInBundle(product: Product): Double { return bundle.find { it.product == product }!!.quantity } override fun applicableProducts(): Set<Product> { return bundle .map { it.product } .toSet() } override fun isOfferApplicable(productQuantities: ProductQuantities): Boolean { return bundle .map { (bundleProduct, minimumQuantity) -> productQuantities.getOrDefault( bundleProduct, 0.0 ) >= minimumQuantity } .reduce { isBundleApplicable, isProductQuantityGreaterThanMinimumBundleQuantity -> isBundleApplicable && isProductQuantityGreaterThanMinimumBundleQuantity } } }
1
Kotlin
0
0
015533297f1a84f3cd5e0f48d5fa37d09cf5b977
3,526
SupermarketReceipt-Refactoring-Kata
MIT License
src/main/kotlin/com/ginsberg/advent2023/Day03.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 3 - Gear Ratios * Problem Description: http://adventofcode.com/2023/day/3 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day3/ */ package com.ginsberg.advent2023 class Day03(private val input: List<String>) { fun solvePart1(): Int { val (numbers, symbols) = parseInput(input) return numbers .filter { number -> number.isAdjacentToAny(symbols) } .sumOf { it.toInt() } } fun solvePart2(): Int { val (numbers, symbols) = parseInput(input) { it == '*' } return symbols .sumOf { symbol -> val neighbors = numbers.filter { it.isAdjacentTo(symbol) } if(neighbors.size == 2) { neighbors.first().toInt() * neighbors.last().toInt() } else 0 } } private fun parseInput( input: List<String>, takeSymbol: (Char) -> Boolean = { it != '.' } ): Pair<Set<NumberLocation>, Set<Point2D>> { val numbers = mutableSetOf<NumberLocation>() val symbols = mutableSetOf<Point2D>() var workingNumber = NumberLocation() input .forEachIndexed { y, row -> row.forEachIndexed { x, c -> if (c.isDigit()) { workingNumber.add(c, Point2D(x, y)) } else { if (workingNumber.isNotEmpty()) { numbers.add(workingNumber) workingNumber = NumberLocation() } if(takeSymbol(c)) { symbols.add(Point2D(x, y)) } } } // Check at end of row that we don't miss a number. if (workingNumber.isNotEmpty()) { numbers.add(workingNumber) workingNumber = NumberLocation() } } return numbers to symbols } private class NumberLocation { val number = mutableListOf<Char>() val locations = mutableSetOf<Point2D>() fun add(c: Char, location: Point2D) { number.add(c) locations.addAll(location.neighbors()) } fun isNotEmpty() = number.isNotEmpty() fun isAdjacentToAny(points: Set<Point2D>): Boolean = locations.intersect(points).isNotEmpty() fun isAdjacentTo(point: Point2D): Boolean = point in locations fun toInt(): Int = number.joinToString("").toInt() } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
2,699
advent-2023-kotlin
Apache License 2.0
src/array/CodeSignam1.kt
develNerd
456,702,818
false
{"Kotlin": 37635, "Java": 5892}
package array import hackerankhone.solutionR import kotlin.math.absoluteValue fun main(){ //println(solution3(mutableListOf(2,4,7,5,3,5,8,5,1,7),4,10)) val m = "WhereIsJohn" val regex = Regex("[A-Z]") var finalString = "" m.forEachIndexed { index, char -> if(regex.matches(char.toString()) && index != 0 && index != m.lastIndex){ finalString = "$finalString " finalString += char.toString() } else{ finalString += char.toString() } } println(finalString.lowercase()) } fun solution1(a:MutableList<Int>):MutableList<Int>{ val b = a val result = mutableListOf<Int>() for (i in a.indices){ fun first() = try { a[i - 1] } catch (e:Exception){ 0 } fun second() = try { a[i] } catch (e:Exception){ 0 } fun third() = try { a[i + 1] } catch (e:Exception){ 0 } val sum = first() + second() + third() result.add(sum) } return result } fun solution2(a:MutableList<Int>,b:MutableList<Int>,k:Int):Int{ val bR = b.asReversed() var numberOfTiny = 0 for (i in a.indices){ val concat = a[i].toString() + bR[i].toString() val value = concat.toInt() if (value < k){ numberOfTiny++ } } return numberOfTiny } fun solution3(a:MutableList<Int>,m:Int,K:Int):Int{ val end = m var numberOFC = 0 for (i in 0 until a.size - 1){ if (i + end > a.size) break val subArray = a.toIntArray().copyOfRange(i,i + end) if (isEqualToK(subArray,K)){ numberOFC++ } } return numberOFC } fun isEqualToK(nums: IntArray, target: Int): Boolean { val sumMap = mutableMapOf<Int,Int>() val list = mutableListOf<String>() for (i in nums.indices){ sumMap[nums[i]] = i } for (i in nums.indices){ val compl = target - nums[i] if (sumMap[compl] != null && sumMap[compl] != i){ return true } } return false } fun solution(a: MutableList<MutableList<Int>>): MutableList<MutableList<Int>> { val mut = mutableMapOf<Double,MutableList<Int>>() for (i in a.indices){ val mean = a[i].average() if (mut[mean] == null){ mut[mean] = mutableListOf(i) }else{ mut[mean] = mut[mean]!!.apply { add(i) } } } return mut.values.toMutableList() }
0
Kotlin
0
0
4e6cc8b4bee83361057c8e1bbeb427a43622b511
2,498
Blind75InKotlin
MIT License
hacker-rank/strings/SpecialPalindromeAgain.kt
piazentin
62,427,919
false
{"Python": 34824, "Jupyter Notebook": 29307, "Kotlin": 19570, "C++": 2465, "R": 2425, "C": 158}
fun main() { readLine() // ignore first input val str = readLine().orEmpty() var count = 0L val freqTable = buildFreqTable(str) // all singles for (freq in freqTable) count += triangleNumber(freq.second) // all "middle" cases for (i in 0 until freqTable.size - 2) { if (freqTable[i + 1].second == 1 && freqTable[i].first == freqTable[i + 2].first) { count += Math.min(freqTable[i].second, freqTable[i + 2].second) } } println(count) } private fun buildFreqTable(str: String): List<Pair<Char, Int>> { if (str.length == 1) return listOf(Pair(str[0], 1)) val table = mutableListOf<Pair<Char, Int>>() var lastChar = str[0] var count = 1 for (i in 1 until str.length) { if (str[i] == lastChar) count++ else { table.add(Pair(lastChar, count)) lastChar = str[i] count = 1 } } table.add(Pair(lastChar, count)) return table } private fun triangleNumber(n: Int) = (n * (n + 1L)) / 2L
0
Python
0
0
db490b1b2d41ed6913b4cacee1b4bb40e15186b7
1,048
programming-challenges
MIT License
2019/src/main/kotlin/y2019/D6.kt
ununhexium
113,359,669
false
null
package y2019 object D6 { fun parse(input: String): Map<String, String> { val parents = mutableMapOf<String, String>() input.split("\n").forEach { line -> // B orbits A val (A, B) = line.split(')') parents[B] = A } return parents } } object D6A { fun solve(parents: Map<String, String>): Int { return parents.keys.sumBy { countOrbits(parents, it) } } private fun countOrbits(parents: Map<String, String>, it: String): Int { var count = 0; var current = it while (current != "COM") { count++ current = parents[current] ?: error("No parent for $current") } return count } } object D6B { fun solve(parents: Map<String, String>): Int { val parentChain1 = getParentChain(parents, "YOU") val parentChain2 = getParentChain(parents, "SAN") val common = parentChain1.intersect(parentChain2) val toCommon1 = parentChain1.dropLastWhile { it in common } val toCommon2 = parentChain2.dropLastWhile { it in common } return toCommon1.size + toCommon2.size + 1 /* the common orbit */ -2 /* YOU and SAN */ -1 /* Count the jumps between nodes, not the nodes */ } private fun getParentChain( parents: Map<String, String>, what: String ): List<String> { val chain = mutableListOf<String>() var current = what while (current != "COM") { chain.add(current) current = parents[current] ?: error("No parent for $current") } return chain } }
6
Kotlin
0
0
d5c38e55b9574137ed6b351a64f80d764e7e61a9
1,484
adventofcode
The Unlicense
src/Day01.kt
rbraeunlich
573,282,138
false
{"Kotlin": 63724}
fun main() { fun part1(input: List<String>): Int { var maxCalories = 0 var currentCalories = 0 input.forEach { line -> if(line.isBlank()) { if(currentCalories > maxCalories) { println("$currentCalories is more than $maxCalories") maxCalories = currentCalories } currentCalories = 0 } else { currentCalories += line.toInt() } } return maxCalories } fun part2(input: List<String>): Int { val allCalories = mutableListOf<Int>() var currentCalories = 0 input.forEach { line -> if(line.isBlank()) { allCalories.add(currentCalories) currentCalories = 0 } else { currentCalories += line.toInt() } } allCalories.sort() return allCalories.takeLast(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") // check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
3c7e46ddfb933281be34e58933b84870c6607acd
1,222
advent-of-code-2022
Apache License 2.0
src/main/kotlin/io/math/DivideTwoIntegers.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.math import io.utils.runTests import kotlin.math.absoluteValue // https://leetcode.com/problems/divide-two-integers/ class DivideTwoIntegers { // Time O(logN) // Space O(logN) fun executeWithExtraSpace(dividendInput: Int, divisor: Int): Int { // Special case: overflow. if (dividendInput == Int.MIN_VALUE && divisor == -1) return Int.MAX_VALUE if (divisor == 1) return dividendInput val isNegative = (dividendInput > 0) xor (divisor > 0) var dividend = dividendInput.absoluteValue val dp = generateDp(dividendInput.absoluteValue, divisor.absoluteValue) var result = 0 if (dp.size == 1) result++ else (dp.lastIndex downTo 0).forEach { index -> val (power, value) = dp[index] if (value < dividend) { result += power dividend -= value } } return if (isNegative) -result else result } private fun generateDp(dividend: Int, divisor: Int) = mutableListOf<Pair<Int, Int>>().apply { var powerOfTwo = 1 var value = divisor while (value <= dividend) { add(powerOfTwo to value) powerOfTwo += powerOfTwo value += value } } // Time O(log2N) // Space O(1) fun execute0(dividendInput: Int, divisorInput: Int): Int { // Special case: overflow. if (dividendInput == Int.MIN_VALUE && divisorInput == -1) return Int.MAX_VALUE var dividend = dividendInput.absoluteValue val divisor = divisorInput.absoluteValue val isNegative = (dividendInput > 0) xor (divisorInput > 0) var result = 0 while (divisor <= dividend) { var powerOfTwo = 1 var value = divisor while (value + value <= dividend) { // while (value >= HALF_INT_MIN && value + value >= dividend) { value += value powerOfTwo += powerOfTwo } result += powerOfTwo dividend -= value } return if (isNegative) -result else result } // Time O(logN) //Space O(1) fun execute(dividendInput: Int, divisorInput: Int): Int { // Special case: overflow. if (dividendInput == Int.MIN_VALUE && divisorInput == -1) return Int.MAX_VALUE val isNegative = (dividendInput > 0) xor (divisorInput > 0) if (divisorInput.absoluteValue == 1) return if (isNegative) -(dividendInput.absoluteValue) else dividendInput.absoluteValue var dividend = dividendInput.absoluteValue val divisor = divisorInput.absoluteValue var highestDouble = divisor var highestPowerOfTwo = 1 while (dividend >= highestDouble + highestDouble) { highestPowerOfTwo += highestPowerOfTwo highestDouble += highestDouble } var result = 0 while (dividend >= divisor) { if (dividend >= highestDouble) { result += highestPowerOfTwo dividend -= highestDouble } highestPowerOfTwo = highestPowerOfTwo shr 1 highestDouble = highestDouble shr 1 } return if (isNegative) -result else result } } fun main() { runTests(listOf( Triple(10, 3, 3), Triple(10, -3, -3), Triple(Int.MAX_VALUE, 1, Int.MAX_VALUE), Triple(1, -1, -1), Triple(Int.MAX_VALUE, 2, Int.MAX_VALUE / 2) )) { (dividend, divisor, result) -> result to DivideTwoIntegers().execute(dividend, divisor) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
3,237
coding
MIT License
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day13.kt
loehnertz
573,145,141
false
{"Kotlin": 53239}
package codes.jakob.aoc import codes.jakob.aoc.shared.map import codes.jakob.aoc.shared.splitMultiline import codes.jakob.aoc.shared.toPair import com.google.gson.Gson class Day13 : Solution() { private val gson = Gson() override fun solvePart1(input: String): Any { val pairs = input .split("\n\n") .map { it.splitMultiline().toPair().map { packet -> parsePacket(packet) } } .mapIndexed { index, pair -> index + 1 to isInRightOrder(pair) } .filter { it.second } .map { it.first } return 0 } private fun isInRightOrder(pair: Pair<Any, Any>): Boolean { fun recurse(left: Any, right: Any): Boolean { return when (left) { is Double -> { when (right) { is Double -> left < right is List<*> -> right.find { recurse(left, it as Any) } != null else -> error("") } } is List<*> -> { when (right) { is Double -> recurse(left.first() as Any, right) is List<*> -> recurse(left.first() as Any, right.first() as Any) else -> error("") } } else -> error("") } } return recurse(pair.first, pair.second) } override fun solvePart2(input: String): Any { TODO("Not yet implemented") } private fun parsePacket(toParse: String): Any { return gson.fromJson(toParse, Any::class.java) } data class Packet( val content: List<Any> ) { data class Node( val content: List<Int> ) } } fun main() = Day13().solve()
0
Kotlin
0
0
ddad8456dc697c0ca67255a26c34c1a004ac5039
1,823
advent-of-code-2022
MIT License