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/g2001_2100/s2014_longest_subsequence_repeated_k_times/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2014_longest_subsequence_repeated_k_times
// #Hard #String #Greedy #Backtracking #Counting #Enumeration
// #2023_06_23_Time_333_ms_(100.00%)_Space_39_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
fun longestSubsequenceRepeatedK(s: String, k: Int): String {
val ca = s.toCharArray()
val freq = CharArray(26)
for (value in ca) {
++freq[value.code - 'a'.code]
}
val cand: Array<ArrayList<String>?> = arrayOfNulls(8)
cand[1] = ArrayList()
var ans = ""
for (i in 0..25) {
if (freq[i].code >= k) {
ans = "" + ('a'.code + i).toChar()
cand[1]?.add(ans)
}
}
for (i in 2..7) {
cand[i] = ArrayList()
for (prev in cand[i - 1]!!) {
for (c in cand[1]!!) {
val next = prev + c
if (isSubsequenceRepeatedK(ca, next, k)) {
ans = next
cand[i]?.add(ans)
}
}
}
}
return ans
}
private fun isSubsequenceRepeatedK(ca: CharArray, t: String, k: Int): Boolean {
var k = k
val ta = t.toCharArray()
val n = ca.size
val m = ta.size
var i = 0
while (k-- > 0) {
var j = 0
while (i < n && j < m) {
if (ca[i] == ta[j]) {
j++
}
i++
}
if (j != m) {
return false
}
}
return true
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,645 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/daytwelve/DayTwelve.kt | pauliancu97 | 619,525,509 | false | null | package daytwelve
import getLines
import java.util.PriorityQueue
import kotlin.math.abs
import kotlin.math.min
private typealias Matrix = MutableList<MutableList<Int>>
private val Matrix.rows: Int
get() = this.size
private val Matrix.cols: Int
get() = this.first().size
private operator fun Matrix.get(coordinate: Coordinate): Int = this[coordinate.row][coordinate.col]
private operator fun Matrix.set(coordinate: Coordinate, value: Int) {
this[coordinate.row][coordinate.col] = value
}
private fun Matrix.isInbounds(coordinate: Coordinate): Boolean =
coordinate.row in 0 until this.rows && coordinate.col in 0 until this.cols
private fun Matrix(rows: Int, cols: Int, func: (Int, Int) -> Int): Matrix =
MutableList(rows) { row ->
MutableList(cols) { col ->
func(row, col)
}
}
private fun Matrix.getString(): String {
var string = ""
for (row in 0 until this.rows) {
for (col in 0 until this.cols) {
string += if (this[row][col] < 10) " ${this[row][col]} " else "${this[row][col]} "
}
string += "\n"
}
return string
}
private data class Coordinate(
val row: Int = 0,
val col: Int = 0
) {
companion object {
private val OFFSETS = arrayOf(
Coordinate(row = -1, col = 0),
Coordinate(row = 0, col = +1),
Coordinate(row = +1, col = 0),
Coordinate(row = 0, col = -1),
)
}
operator fun plus(other: Coordinate): Coordinate =
Coordinate(row = this.row + other.row, col = this.col + other.col)
fun getNeighbours(): List<Coordinate> =
OFFSETS.map { offset -> this + offset }
}
private fun getValidNeighbours(coordinate: Coordinate, heights: Matrix, visited: Set<Coordinate>): List<Coordinate> =
coordinate.getNeighbours()
.filter { updatedCoordinate ->
if (heights.isInbounds(updatedCoordinate)) {
val isNotVisited = updatedCoordinate !in visited
val originalHeight = heights[coordinate]
val updatedHeight = heights[updatedCoordinate]
val isHeightDifferenceValid = updatedHeight - originalHeight <= 1
isHeightDifferenceValid && isNotVisited
} else {
false
}
}
private fun getEnergyCost(
start: Coordinate,
destination: Coordinate,
heights: Matrix
): Int {
val queue: PriorityQueue<Pair<Int, Coordinate>> = PriorityQueue(compareBy { (numOfSteps, _) -> -numOfSteps })
val visited: MutableSet<Coordinate> = mutableSetOf()
val costs = Matrix(heights.rows, heights.cols) { row, col ->
if (start.row == row && start.col == col) 0 else -1
}
queue.add(0 to start)
while (queue.isNotEmpty()) {
val (numOfSteps, coordinate) = queue.poll()
visited.add(coordinate)
for (updatedCoordinate in getValidNeighbours(coordinate, heights, visited)) {
val updatedCost = numOfSteps + 1 + abs(heights[updatedCoordinate] - heights[coordinate])
if (costs[updatedCoordinate] == -1 || updatedCost < costs[updatedCoordinate]) {
costs[updatedCoordinate] = updatedCost
queue.add(updatedCost to updatedCoordinate)
}
}
}
return costs[destination]
}
private fun getNumOfSteps(
start: Coordinate,
destination: Coordinate,
heights: Matrix
): Int {
val queue: MutableList<Pair<Coordinate, Int>> = mutableListOf(start to 0)
val visited: MutableSet<Coordinate> = mutableSetOf(start)
while (queue.isNotEmpty()) {
val (coordinate, numOfSteps) = queue.removeFirst()
if (coordinate == destination) {
return numOfSteps
}
for (updatedCoordinate in getValidNeighbours(coordinate, heights, visited)) {
queue.add(updatedCoordinate to (numOfSteps + 1))
visited.add(updatedCoordinate)
}
}
return -1
}
private fun getHeights(path: String): Triple<Coordinate, Coordinate, Matrix> {
val strings = getLines(path)
val heightsMatrix = strings.map { string ->
string.map { char ->
when (char) {
'S' -> 0
'E' -> 'z'.code - 'a'.code
else -> char.code - 'a'.code
}
}
}
val rows = strings.size
val cols = strings.first().length
var start = Coordinate()
var destination = Coordinate()
for (row in 0 until rows) {
for (col in 0 until cols) {
when (strings[row][col]) {
'S' -> start = Coordinate(row, col)
'E' -> destination = Coordinate(row, col)
else -> {}
}
}
}
val matrix = Matrix(rows, cols) { row, col -> heightsMatrix[row][col] }
return Triple(start, destination, matrix)
}
private fun getMinNumOfSteps(destination: Coordinate, heights: Matrix): Int {
var minNumOfSteps = Int.MAX_VALUE
for (row in 0 until heights.rows) {
for (col in 0 until heights.cols) {
val coordinate = Coordinate(row, col)
if (heights[coordinate] == 0) {
val numOfSteps = getNumOfSteps(
coordinate,
destination,
heights
)
if (numOfSteps > 0) {
minNumOfSteps = min(minNumOfSteps, numOfSteps)
}
}
}
}
return minNumOfSteps
}
private fun solvePartOne() {
val (start, destination, heights) = getHeights("day_12.txt")
println(getNumOfSteps(start, destination, heights))
}
private fun solvePartTwo() {
val (start, destination, heights) = getHeights("day_12.txt")
println(getMinNumOfSteps(destination, heights))
}
fun main() {
//solvePartOne()
solvePartTwo()
} | 0 | Kotlin | 0 | 0 | 78af929252f094a34fe7989984a30724fdb81498 | 5,853 | advent-of-code-2022 | MIT License |
src/Day21.kt | Riaz1 | 577,017,303 | false | {"Kotlin": 15653} |
fun main() {
data class LineItem(
val key1: String,
val operator: String,
val key2: String,
var result: Double?
)
val fileName =
"Day21_input"
// "Day21_sample"
val steps = readInput(fileName).associateBy(
keySelector = {v -> v.substringBefore(":").trim()},
valueTransform = {v ->
if (v.substringAfter(":").trim().toDoubleOrNull() != null) {
LineItem("", "", "", v.substringAfter(":").trim().toDoubleOrNull())
} else {
LineItem(
v.substringAfter(":").trim().split(" ")[0],
v.substringAfter(":").trim().split(" ")[1],
v.substringAfter(":").trim().split(" ")[2],
null
)
}
})
var rootValue : Double? = null
while (rootValue == null) {
run breaking@ {
steps.forEach { (key, item) ->
if (key == "root" && item.result != null) {
rootValue = item.result
return@breaking
}
if (item.result == null &&
steps[item.key1]?.result != null &&
steps[item.key2]?.result != null) {
steps[key]?.result = when (item.operator) {
"+" -> steps[item.key2]?.result?.let {steps[item.key1]?.result?.plus(it) }
"-" -> steps[item.key2]?.result?.let {steps[item.key1]?.result?.minus(it) }
"*" -> steps[item.key2]?.result?.let {steps[item.key1]?.result?.times(it) }
"/" -> steps[item.key2]?.result?.let {steps[item.key1]?.result?.div(it) }
else -> null
}
}
}
}
}
rootValue.println()
"%.2f".format(rootValue).println()
}
| 0 | Kotlin | 0 | 0 | 4d742e404ece13203319e1923ffc8e1f248a8e15 | 1,910 | aoc2022 | Apache License 2.0 |
src/main/kotlin/days/Day7.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.DayInput
class Day7 : Day("7") {
class HandBet(val hand: Hand, val bet: Int)
class Hand(val handString: String)
class HandRulesPart1(val hand: Hand) {
val map = hand.handString.groupingBy { it }.eachCount()
val cardRate = mapOf(
Pair('2', 2),
Pair('3', 3),
Pair('4', 4),
Pair('5', 5),
Pair('6', 6),
Pair('7', 7),
Pair('8', 8),
Pair('9', 9),
Pair('T', 10),
Pair('J', 11),
Pair('Q', 12),
Pair('K', 13),
Pair('A', 14)
)
fun fiveOfKind(): Int? {
if (map.size == 1) {
return 9
}
return null
}
fun fourOfKind(): Int? {
if (map.size == 2 && map.any { it.value == 4 }) {
return 8
}
return null
}
fun fullHouse(): Int? {
if (map.size == 2 && map.any { it.value == 3 }) {
return 7
}
return null
}
fun threeOfKind(): Int? {
if (map.any { it.value == 3 }) {
return 6
}
return null
}
fun twoPairs(): Int? {
if (map.filter { it.value == 2 }.count() == 2) {
return 5
}
return null
}
fun onePair(): Int? {
if (map.filter { it.value == 2 }.count() == 1) {
return 4
}
return null
}
fun highCard(): Int? {
return 1
}
fun rate(): String {
val combination =
listOf(
fiveOfKind(),
fourOfKind(),
fullHouse(),
threeOfKind(),
twoPairs(),
onePair(),
highCard()
).filterNotNull()
.first()
return combination.toString() + hand.handString.map {
Char(('A'.code - 1) + cardRate[it]!!)
}.joinToString("")
}
}
class HandRulesPart2(val hand: Hand) {
val map = hand.handString.groupingBy { it }.eachCount()
val mapWithoutJokers = map.filter { it.key != 'J' }
val jokers = map['J'] ?: 0
val cardRate = mapOf(
Pair('2', 2),
Pair('3', 3),
Pair('4', 4),
Pair('5', 5),
Pair('6', 6),
Pair('7', 7),
Pair('8', 8),
Pair('9', 9),
Pair('T', 10),
Pair('J', 1),
Pair('Q', 12),
Pair('K', 13),
Pair('A', 14)
)
fun fiveOfKind(): Int? {
if (map.size == 1 || mapWithoutJokers.any { it.value == 5 - jokers }) {
return 9
}
return null
}
fun fourOfKind(): Int? {
if (mapWithoutJokers.any { it.value == 4 - jokers }) {
return 8
}
return null
}
fun fullHouse(): Int? {
if (jokers == 0 && map.size == 2 && map.any { it.value == 3 } ||
jokers == 1 && mapWithoutJokers.filter { it.value == 2 }.count() == 2
) {
return 7
}
return null
}
fun threeOfKind(): Int? {
if (map.any { it.value == 3 - jokers }) {
return 6
}
return null
}
fun twoPairs(): Int? {
if (map.filter { it.value == 2 }.count() == 2) {
return 5
}
return null
}
fun onePair(): Int? {
if (map.filter { it.value == 2 - jokers }.count() > 0) {
return 4
}
return null
}
fun highCard(): Int? {
return 1
}
fun rate(): String {
val combination =
listOf(
fiveOfKind(),
fourOfKind(),
fullHouse(),
threeOfKind(),
twoPairs(),
onePair(),
highCard()
).filterNotNull()
.first()
return combination.toString() + hand.handString.map {
Char(('A'.code - 1) + cardRate[it]!!)
}.joinToString("")
}
}
override fun partOne(dayInput: DayInput): Any {
val sortedBy = dayInput.inputList().map {
val split = it.split(" ")
HandBet(Hand(split[0]), split[1].toInt())
}.map {
Pair(it, HandRulesPart1(it.hand).rate())
}.sortedBy { it.second }
return sortedBy.mapIndexed { index, pair ->
(index + 1) * pair.first.bet
}.sum()
}
override fun partTwo(dayInput: DayInput): Any {
val sortedBy = dayInput.inputList().map {
val split = it.split(" ")
HandBet(Hand(split[0]), split[1].toInt())
}.map {
Pair(it, HandRulesPart2(it.hand).rate())
}.sortedBy { it.second }
return sortedBy.mapIndexed { index, pair ->
(index + 1) * pair.first.bet
}.sum()
}
}
fun main() {
Day7().run()
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 5,422 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
Rationals/src/rationals/Rational.kt | Sharkaboi | 258,941,707 | false | null | package rationals
import java.lang.IllegalArgumentException
import java.math.BigInteger
class Rational(private var numerator: BigInteger, private var denominator: BigInteger):Comparable<Rational> {
init {
if (denominator == BigInteger.ZERO)
throw IllegalArgumentException()
else if (denominator < BigInteger.ZERO) {
numerator = -numerator
denominator = -denominator
}
}
operator fun plus(second: Rational): Rational {
val newNumerator = this.numerator * second.denominator + second.numerator * this.denominator
val newDenominator = this.denominator * second.denominator
return Rational(newNumerator, newDenominator)
}
operator fun minus(second: Rational): Rational {
return when {
this.numerator == BigInteger.ZERO -> Rational(-second.numerator, second.denominator)
second.numerator == BigInteger.ZERO -> this
this.denominator == second.denominator -> Rational(this.numerator - second.denominator, this.denominator)
else -> {
val newNumerator = this.numerator * second.denominator - second.numerator * this.denominator
val newDenominator = this.denominator * second.denominator
Rational(newNumerator, newDenominator)
}
}
}
operator fun times(second: Rational): Rational {
return Rational(this.numerator * second.numerator, this.denominator * second.denominator)
}
operator fun div(second: Rational): Rational {
return when {
second.numerator == BigInteger.ZERO || this.denominator == BigInteger.ZERO -> throw IllegalArgumentException()
second.denominator == BigInteger.ZERO || this.numerator == BigInteger.ZERO -> Rational(BigInteger.ZERO, BigInteger.ONE)
else -> {
Rational(this.numerator * second.denominator, this.denominator * second.numerator)
}
}
}
operator fun unaryMinus(): Rational {
return Rational(-this.numerator, this.denominator)
}
override fun toString(): String {
val simplifiedRational=this.simplify()
return when {
simplifiedRational.numerator == BigInteger.ZERO -> "0"
simplifiedRational.denominator == BigInteger.ZERO -> throw IllegalArgumentException()
simplifiedRational.denominator == BigInteger.ONE -> simplifiedRational.numerator.toString()
simplifiedRational.denominator < BigInteger.ZERO -> "${-simplifiedRational.numerator}/${-simplifiedRational.denominator}"
else -> "${simplifiedRational.numerator}/${simplifiedRational.denominator}"
}
}
override operator fun compareTo(second: Rational): Int {
return (this.numerator * second.denominator).compareTo(second.numerator * this.denominator)
}
override fun equals(second: Any?): Boolean {
return when {
this === second -> true
this.numerator == (second as Rational).numerator && this.denominator == second.denominator -> true
else -> {
val newFirst = this.simplify()
val newSecond = second.simplify()
return newFirst.numerator == newSecond.numerator && newFirst.denominator == newSecond.denominator
}
}
}
fun hcf(n1: BigInteger, n2: BigInteger): BigInteger =
if (n2 != 0.toBigInteger()) hcf(n2, n1 % n2) else n1
fun simplify(): Rational {
val hcf = hcf(this.numerator, this.denominator).abs()
return Rational(this.numerator.div(hcf), this.denominator.div(hcf))
}
}
infix fun Int.divBy(second: Int): Rational = Rational(this.toBigInteger(), second.toBigInteger())
infix fun Long.divBy(second: Long): Rational = Rational(this.toBigInteger(), second.toBigInteger())
infix fun BigInteger.divBy(second: BigInteger): Rational = Rational(this, second)
fun main() {
val half = 1 divBy 2
val third = 1 divBy 3
val sum: Rational = half + third
println(5 divBy 6 == sum)
val difference: Rational = half - third
println(1 divBy 6 == difference)
val product: Rational = half * third
println(1 divBy 6 == product)
val quotient: Rational = half / third
println(3 divBy 2 == quotient)
val negation: Rational = -half
println(-1 divBy 2 == negation)
println((2 divBy 1) == "2".toRational())
println((-2 divBy 4) == "-1/2".toRational())
println("117/1098".toRational() == "13/122".toRational())
val twoThirds = 2 divBy 3
println(half < twoThirds)
println(half in third..twoThirds)
println(2000000000L divBy 4000000000L == 1 divBy 2)
println("912016490186296920119201192141970416029".toBigInteger() divBy
"1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2)
}
fun String.toRational(): Rational {
return when {
this.contains('/') -> Rational(this.substringBefore('/').trim().toBigInteger(), this.substringAfter('/').trim().toBigInteger())
else -> Rational(this.trim().toBigInteger(), BigInteger.ONE)
}
}
| 0 | Kotlin | 0 | 0 | 977968b41ecc0ed1b62b50784bfebc3fa9d95a11 | 5,140 | Kotlin-for-java-devs-course | MIT License |
src/day01/Day01.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day01
import readInput
import readTestInput
private fun List<String>.toSnackSumSequence(): Sequence<Int> = sequence {
var sum = 0
for (item in this@toSnackSumSequence) {
if (item.isBlank()) {
this.yield(sum)
sum = 0
} else {
sum += item.toInt()
}
}
this.yield(sum)
}
private fun part1(input: List<String>): Int =
input
.toSnackSumSequence()
.max()
private fun part2(input: List<String>): Int =
input
.toSnackSumSequence()
.sortedDescending()
.take(3)
.sum()
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day01")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 898 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | mnajborowski | 573,619,699 | false | {"Kotlin": 7975} | fun main() {
fun part1(input: List<String>): Int =
input
.map { pairRangesString ->
pairRangesString.split(',', '-')
.let { it[0].toInt()..it[1].toInt() to it[2].toInt()..it[3].toInt() }
}
.count { (firstRange, secondRange) ->
firstRange.all { it in secondRange } || secondRange.all { it in firstRange }
}
fun part2(input: List<String>): Int =
input
.map { pairRangesString ->
pairRangesString.split(',', '-')
.let { it[0].toInt()..it[1].toInt() to it[2].toInt()..it[3].toInt() }
}
.count { (firstRange, secondRange) ->
(firstRange intersect secondRange).isNotEmpty()
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e54c13bc5229c6cb1504db7e3be29fc9b9c4d386 | 884 | advent-of-code-2022 | Apache License 2.0 |
mobile/src/main/java/ch/epfl/sdp/mobile/application/tournaments/PoolResults.kt | epfl-SDP | 462,385,783 | false | {"Kotlin": 1271815, "Shell": 359} | package ch.epfl.sdp.mobile.application.tournaments
import androidx.compose.ui.util.fastSumBy
import ch.epfl.sdp.mobile.application.ChessDocument
import ch.epfl.sdp.mobile.application.ChessMetadata.Companion.BlackWon
import ch.epfl.sdp.mobile.application.ChessMetadata.Companion.Stalemate
import ch.epfl.sdp.mobile.application.ChessMetadata.Companion.WhiteWon
/**
* The [PoolResults] indicate the results of some pools, and provide aggregate statistics to rank
* the players.
*/
interface PoolResults {
/** The identifiers of the players who have some results. */
val players: List<String>
/** Computes the score of [player] against [opponent]. */
fun against(player: String, opponent: String): Int
/** Returns the total score of the player with [playerId]. */
fun score(playerId: String): Int
/** Returns the number of matches played by [playerId]. */
fun played(playerId: String): Int
}
/**
* An implementation of a [PoolResults] which use a list of [ChessDocument].
*
* @property documents the [ChessDocument] which are used to compute the results.
*/
private class ChessDocumentListPoolResults(
private val documents: List<ChessDocument>,
) : PoolResults {
override val players: List<String> =
documents.flatMap { listOf(it.blackId, it.whiteId) }.distinct().filterNotNull()
val scores =
documents
.flatMap {
when (it.metadata?.status) {
WhiteWon -> listOf(it.whiteId to 3)
BlackWon -> listOf(it.blackId to 3)
Stalemate -> listOf(it.whiteId to 1, it.blackId to 1)
else -> emptyList()
}
}
.groupingBy { (id, _) -> id }
.fold(0) { acc, (_, score) -> acc + score }
val played =
documents
.flatMap { listOf(it.whiteId to 1, it.blackId to 1) }
.groupingBy { (id, _) -> id }
.fold(0) { acc, (_, count) -> acc + count }
override fun against(player: String, opponent: String): Int {
return documents.fastSumBy {
val status = it.metadata?.status
when {
status == WhiteWon && it.whiteId == player && it.blackId == opponent -> 3
status == BlackWon && it.blackId == player && it.whiteId == opponent -> 3
status == Stalemate &&
((it.blackId == player && it.whiteId == opponent) ||
(it.whiteId == player && it.blackId == opponent)) -> 1
else -> 0
}
}
}
override fun score(playerId: String): Int = scores[playerId] ?: 0
override fun played(playerId: String): Int = played[playerId] ?: 0
}
/** Returns the [PoolResults] from a [List] off [ChessDocument]. */
fun List<ChessDocument>.toPoolResults(): PoolResults = ChessDocumentListPoolResults(this)
| 15 | Kotlin | 2 | 13 | 71f6e2a5978087205b35f82e89ed4005902d697e | 2,742 | android | MIT License |
src/main/kotlin/g1701_1800/s1775_equal_sum_arrays_with_minimum_number_of_operations/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1701_1800.s1775_equal_sum_arrays_with_minimum_number_of_operations
// #Medium #Array #Hash_Table #Greedy #Counting
// #2023_06_18_Time_529_ms_(100.00%)_Space_52.7_MB_(100.00%)
class Solution {
fun minOperations(nums1: IntArray, nums2: IntArray): Int {
val longer = if (nums1.size > nums2.size) nums1 else nums2
val shorter = if (nums1.size > nums2.size) nums2 else nums1
if (longer.size > shorter.size * 6) {
return -1
}
longer.sort()
shorter.sort()
var i = 0
var j = 0
var diff = 0
while (i < longer.size || j < shorter.size) {
if (i < longer.size) {
diff += longer[i++]
}
if (j < shorter.size) {
diff -= shorter[j++]
}
}
var minOps = 0
i = 0
j = shorter.size - 1
return if (diff < 0) {
while (diff < 0) {
diff += if (i < longer.size && j >= 0) {
if (6 - longer[i] < shorter[j] - 1) {
shorter[j--] - 1
} else {
6 - longer[i++]
}
} else if (i < longer.size) {
6 - longer[i++]
} else {
shorter[j--] - 1
}
minOps++
}
minOps
} else if (diff > 0) {
i = longer.size - 1
j = 0
while (diff > 0) {
diff -= if (i >= 0 && j < shorter.size) {
if (longer[i] - 1 > 6 - shorter[j]) {
longer[i--] - 1
} else {
6 - shorter[j++]
}
} else if (i >= 0) {
longer[i--] - 1
} else {
6 - shorter[j++]
}
minOps++
}
minOps
} else {
minOps
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,038 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/org/softlang/util/Algorithms.kt | lukashaertel | 80,610,151 | false | null | package org.softlang.util
/**
* Mapper of object types to indices, used in algorithms that are index based
*/
data class Mapper<T>(val forward: Map<T, Int>, val backward: Map<Int, T>) {
/**
* Number of mapped objects.
*/
val size get() = forward.size
operator fun get(item: T) = forward.getValue(item)
operator fun get(item: Int) = backward.getValue(item)
}
/**
* A point in a matrix.
*/
data class Point(val column: Int, val row: Int)
/**
* An entry in a matrix.
*/
data class Entry(val column: Int, val row: Int, val value: Int)
/**
* A matrix storing integer values.
*/
data class IntMatrix(val columns: Int, val backing: IntArray) {
/**
* Number of rows in this matrix.
*/
val rows get() = backing.size / columns
/**
* Gets the entry at that position.
*/
operator fun get(column: Int, row: Int) =
backing[column + row * columns]
/**
* Gets the entry at that position.
*/
operator fun get(point: Point) =
backing[point.column + point.row * columns]
/**
* Gets the entry at that position.
*/
operator fun set(column: Int, row: Int, value: Int) {
backing[column + row * columns] = value
}
/**
* Gets the entry at that position.
*/
operator fun set(point: Point, value: Int) {
backing[point.column + point.row * columns] = value
}
/**
* Gets all entries
*/
val entries get() = backing
.withIndex()
.map {
Entry(it.index % columns, it.index / columns, it.value)
}
override fun hashCode() =
columns + 13 * backing.contentHashCode()
override fun equals(other: Any?) =
other is IntMatrix
&& columns == other.columns
&& backing.contentEquals(other.backing)
}
/**
* Creates a symmetric [IntMatrix].
*/
fun intMatrix(dim: Int) =
IntMatrix(dim, IntArray(dim * dim))
/**
* Creates an [IntMatrix] of the given size.
*/
fun intMatrix(columns: Int, rows: Int) =
IntMatrix(columns, IntArray(columns * rows))
/**
* Creates a symmetric [IntMatrix], sets entries using an initializer.
*/
fun intMatrix(dim: Int, initializer: (Point) -> Int) =
IntMatrix(dim, IntArray(dim * dim, { i ->
initializer(Point(i % dim, i / dim))
}))
/**
* Creates an [IntMatrix] of the given size, sets entries using an initializer.
*/
fun intMatrix(columns: Int, rows: Int, initializer: (Point) -> Int) =
IntMatrix(columns, IntArray(columns * rows, { i ->
initializer(Point(i % columns, i / columns))
}))
/**
* Creates a mapper for the given elements.
*/
fun <T> mapper(items: Iterable<T>): Mapper<T> {
// Create map builders
val forward = mutableMapOf<T, Int>()
val backward = mutableMapOf<Int, T>()
// Associate index-wise
items.withIndex().forEach {
forward += it.value to it.index
backward += it.index to it.value
}
// Return mapper on unmodifiable maps
return Mapper(forward.toMap(), backward.toMap())
}
/**
* Floyd-Warshall All-Shortest-Paths
*/
fun <T> fwasp(graph: Map<T, Set<T>>): Map<Pair<T, T>, List<T>> {
// Obtain all nodes
val nodes = graph.values.fold(graph.keys) { a, b ->
a union b
}
// Use mapper to utilize int arrays
return mapper(nodes).let { m ->
// Pseudo-infinity to prevent integer underflows
val INFINITY = m.size * 2
// Initialize distance and next matrix
val dist = intMatrix(m.size) { INFINITY }
val next = intMatrix(m.size) { -1 }
// Copy graph into matrix
for ((n, es) in graph) {
val mn = m[n]
for (e in es) {
val me = m[e]
dist[mn, me] = 1
next[mn, me] = me
}
}
// Perform standard Floyd-Warshall
for (k in 0 until m.size)
for (i in 0 until m.size)
for (j in 0 until m.size) {
// Get previous distance metrics
val ij = dist[i, j]
val ik = dist[i, k]
val kj = dist[k, j]
// Compare and update appropriately
if (ij > ik + kj) {
dist[i, j] = ik + kj
next[i, j] = next[i, k]
}
}
// For all reachable pairs
dist.entries.filter {
it.value != INFINITY
}.associate {
// Extract keys as they are used often
val u = it.column
val v = it.row
// Generate path from u by Floyd-Warshall path reconstruction
(m[u] to m[v]) to generateSequence(u) {
if (it == v) null else next[it, v].toNull()
}.map(m::get).toList()
}
}
}
/**
* Calculates all shortest paths for graphs defined by [I] initial nodes, [E]
* edges and actual node types [N].
*/
fun <I, E, N> fwasp(
initial: Set<I>,
edges: Set<E>,
nodeOf: (I) -> N,
sourceOf: (E) -> N,
targetOf: (E) -> N):
Map<Pair<I, N>, List<E>> {
// Mapping inversion for nodes and edges
val unmapInitial = initial.associateBy { nodeOf(it) }
val unmapEdge = edges.associateBy { sourceOf(it) to targetOf(it) }
val nodes = initial.map(nodeOf) union
edges.map(sourceOf) union
edges.map(targetOf)
// Apply Floyd-Warshall on mapped graph
return fwasp(nodes.associate { n ->
// From node via all edges starting at that node
n to edges
.filter { e -> n == sourceOf(e) }
.map(targetOf)
.toSet()
}).filterKeys {
// Some transitions have no satisfied initial nodes, skip those
unmapInitial.containsKey(it.first)
}.mapKeys {
// Unmap key origin and target
unmapInitial.getValue(it.key.first) to it.key.second
}.mapValues {
// Unmap value transitions
it.value.pairs.map { unmapEdge.getValue(it) }
}
}
fun main(args: Array<String>) {
val graph = mapOf(
"a" to setOf("b", "f", "d"),
"b" to setOf("c"),
"c" to setOf("d"),
"d" to setOf("f")
)
val apsp = fwasp(graph)
print(apsp)
} | 0 | Kotlin | 0 | 0 | ddeb400bcca9ee5547ee09034458f423589312d8 | 6,405 | megal-vm | MIT License |
src/Day02.kt | morris-j | 573,197,835 | false | {"Kotlin": 7085} | fun main() {
fun scorePlay(play: String): Int {
return when(play) {
"A" -> 1
"B" -> 2
"C" -> 3
else -> 0
}
}
fun scoreOutcome(opponent: String, play: String): Int {
return when(opponent) {
// Rock
"A" -> when(play) {
"A" -> 3
"B" -> 6
"C" -> 0
else -> 0
}
// Paper
"B" -> when(play) {
"A" -> 0
"B" -> 3
"C" -> 6
else -> 0
}
// Scissors
"C" -> when(play) {
"A" -> 6
"B" -> 0
"C" -> 3
else -> 0
}
else -> 0
}
}
fun translatePlay(play: String): String {
return when(play) {
"X" -> "A"
"Y" -> "B"
"Z" -> "C"
else -> ""
}
}
fun determinePlay(opponent: String, result: String): String {
return when(opponent) {
// Rock
"A" -> when(result) {
"X" -> "C"
"Y" -> "A"
"Z" -> "B"
else -> ""
}
// Paper
"B" -> when(result) {
"X" -> "A"
"Y" -> "B"
"Z" -> "C"
else -> ""
}
// Scissors
"C" -> when(result) {
"X" -> "B"
"Y" -> "C"
"Z" -> "A"
else -> ""
}
else -> ""
}
}
fun parseInput(input: List<String>): List<Pair<String, String>> {
return input.map {
val split = it.split(" ")
Pair(split[0], split[1])
}
}
fun part1(input: List<String>): Int {
val parsedInput = parseInput(input)
var score = 0
// Loop each round
for(item in parsedInput) {
val play = translatePlay(item.second)
score += scorePlay(play)
score += scoreOutcome(item.first, play)
}
return score
}
fun part2(input: List<String>): Int {
val parsedInput = parseInput(input)
var score = 0
// Loop each round
for(item in parsedInput) {
val play = determinePlay(item.first, item.second)
score += scorePlay(play)
score += scoreOutcome(item.first, play)
}
return score
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e3f2d02dad432dbc1b15c9e0eefa7b35ace0e316 | 2,661 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/sschr15/aocsolutions/util/watched/WatchedIntegerIterables.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | @file:OptIn(ExperimentalTypeInference::class)
package sschr15.aocsolutions.util.watched
import kotlin.experimental.ExperimentalTypeInference
fun Iterable<WatchedInt>.sum() = fold(0.watched()) { acc, i -> acc + i }
fun Iterable<WatchedInt>.product() = fold(1.watched()) { acc, i -> acc * i }
fun Iterable<WatchedInt>.average() = sum() / count()
fun Iterable<WatchedInt>.min() = reduce { acc, i -> if (i < acc) i else acc }
fun Iterable<WatchedInt>.max() = reduce { acc, i -> if (i > acc) i else acc }
fun Iterable<WatchedInt>.minOrNull() = reduceOrNull { acc, i -> if (i < acc) i else acc }
fun Iterable<WatchedInt>.maxOrNull() = reduceOrNull { acc, i -> if (i > acc) i else acc }
@OverloadResolutionByLambdaReturnType // quite possibly the longest annotation name i've ever needed to use
fun <T> Iterable<T>.sumOf(selector: (T) -> WatchedInt) = map(selector).sum()
fun Iterable<WatchedLong>.sum() = fold(0L.watched()) { acc, i -> acc + i }
fun Iterable<WatchedLong>.product() = fold(1L.watched()) { acc, i -> acc * i }
fun Iterable<WatchedLong>.average() = sum() / count()
fun Iterable<WatchedLong>.min() = reduce { acc, i -> if (i < acc) i else acc }
fun Iterable<WatchedLong>.max() = reduce { acc, i -> if (i > acc) i else acc }
fun Iterable<WatchedLong>.minOrNull() = reduceOrNull { acc, i -> if (i < acc) i else acc }
fun Iterable<WatchedLong>.maxOrNull() = reduceOrNull { acc, i -> if (i > acc) i else acc }
@OverloadResolutionByLambdaReturnType
fun <T> Iterable<T>.sumOf(selector: (T) -> WatchedLong) = map(selector).sum()
fun Iterable<Int>.watched() = map(Int::watched)
@JvmName("watchedLong") fun Iterable<Long>.watched() = map(Long::watched)
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 1,658 | advent-of-code | MIT License |
src/Day10.kt | timmiller17 | 577,546,596 | false | {"Kotlin": 44667} | fun main() {
fun part1(input: List<String>): Int {
val instructions = input.map { it.split(' ') }
var cycleCounter = 0
var X = 1
var signalStrengthSum = 0
fun runCycle() {
cycleCounter++
if (listOf(20, 60, 100, 140, 180, 220).contains(cycleCounter)) {
signalStrengthSum += cycleCounter * X
}
// println("end of cycle $cycleCounter, X=$X")
}
for (instruction in instructions) {
if (instruction[0] == "noop") {
runCycle()
} else {
runCycle()
runCycle()
X += instruction[1].toInt()
}
if (cycleCounter > 220) {
break
}
}
return signalStrengthSum
}
fun part2(input: List<String>): Int {
val instructions = input.map { it.split(' ') }
var cycleCounter = 0
var X = 1
var screenBuffer = ""
fun runCycle() {
val position = cycleCounter % 40
screenBuffer += if (position in IntRange(X - 1, X + 1)) {
"#"
} else {
"."
}
cycleCounter++
// println("end of cycle $cycleCounter, position:$position, X=$X, character: ${screenBuffer.last()}")
}
for (instruction in instructions) {
if (instruction[0] == "noop") {
runCycle()
} else {
runCycle()
runCycle()
X += instruction[1].toInt()
}
}
println(screenBuffer.substring(0, 40))
println(screenBuffer.substring(40, 80))
println(screenBuffer.substring(80, 120))
println(screenBuffer.substring(120, 160))
println(screenBuffer.substring(160, 200))
println(screenBuffer.substring(200, 240))
println()
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == 0)
val input = readInput("Day10")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c | 2,248 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/sschr15/aocsolutions/Day11.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.*
import kotlin.math.absoluteValue
/**
* AOC 2023 [Day 11](https://adventofcode.com/2023/day/11)
* Challenge: whoops our spacetime is destroying itself right in front of our eyes
*/
object Day11 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 11) {
// test()
val initialGrid: Grid<Char>
val emptyColumns = mutableListOf<Int>()
val emptyRows = mutableListOf<Int>()
part1 {
initialGrid = inputLines.chars().toGrid()
for (column in 0..<initialGrid.width) {
if (initialGrid.getColumn(column).all { it == '.' }) {
emptyColumns += column
}
}
for (row in 0..<initialGrid.height) {
if (initialGrid.getRow(row).all { it == '.' }) {
emptyRows += row
}
}
val grid = Grid(initialGrid.width + emptyColumns.size, initialGrid.height + emptyRows.size, '.')
var newX = 0
var newY = 0
for (y in 0..<initialGrid.height) {
if (y in emptyRows) {
newY += 2
continue
}
for (x in 0..<initialGrid.width) {
if (x in emptyColumns) {
newX += 2
continue
}
grid[newX, newY] = initialGrid[x, y]
newX++
}
newX = 0
newY++
}
val galaxies = grid.toPointMap().filterValues { it == '#' }.keys.toList().combinations(2)
galaxies.sumOf { (a, b) -> a.manhattanDistance(b) }
}
part2 {
val expansion = 999_999
val galaxies = initialGrid.toPointMap().filterValues { it == '#' }.keys.toList()
.map { (x, y) ->
val emptyRowCount = emptyRows.filter { it < y }.size
val emptyColumnCount = emptyColumns.filter { it < x }.size
val newX = x.toLong() + emptyColumnCount * expansion
val newY = y.toLong() + emptyRowCount * expansion
newX to newY // no points, too large
}
.combinations(2)
galaxies.sumOf { (a, b) -> (a.first - b.first).absoluteValue + (a.second - b.second).absoluteValue }
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 2,593 | advent-of-code | MIT License |
src/Day01.kt | GarrettShorr | 571,769,671 | false | {"Kotlin": 82669} | import java.lang.Exception
fun main() {
fun part1(input: List<String>): Int {
val elves = mutableListOf<Int>()
var totalCalories = 0
for(food in input) {
if (food != "") {
totalCalories += food.toInt()
} else {
elves.add(totalCalories)
totalCalories = 0
}
}
elves.add(totalCalories)
return elves.max()
}
fun part2(input: List<String>): Int {
val elves = mutableListOf<Int>()
var totalCalories = 0
for(food in input) {
if (food != "") {
totalCalories += food.toInt()
} else {
elves.add(totalCalories)
totalCalories = 0
}
}
elves.add(totalCalories)
println(elves)
// for(i in 1..3) {
// totalCalories += elves.max()
// elves.remove(elves.max())
// }
return elves.sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day01")
output(part1(input))
output(part2(input))
}
| 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 1,105 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/g1901_2000/s1964_find_the_longest_valid_obstacle_course_at_each_position/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1901_2000.s1964_find_the_longest_valid_obstacle_course_at_each_position
// #Hard #Array #Binary_Search #Binary_Indexed_Tree
// #2023_06_21_Time_846_ms_(40.00%)_Space_52.5_MB_(99.09%)
@Suppress("NAME_SHADOWING")
class Solution {
fun longestObstacleCourseAtEachPosition(obstacles: IntArray): IntArray {
return longestIncreasingSubsequence(obstacles)
}
private fun longestIncreasingSubsequence(obstacles: IntArray): IntArray {
var len = 1
val length = obstacles.size
val ans = IntArray(length)
val arr = IntArray(length)
arr[0] = obstacles[0]
ans[0] = 1
for (i in 1 until length) {
val `val` = obstacles[i]
if (`val` >= arr[len - 1]) {
arr[len++] = `val`
ans[i] = len
} else {
val idx = binarySearch(arr, 0, len - 1, `val`)
arr[idx] = `val`
ans[i] = idx + 1
}
}
return ans
}
private fun binarySearch(arr: IntArray, lo: Int, hi: Int, `val`: Int): Int {
var lo = lo
var hi = hi
var ans = -1
while (lo <= hi) {
val mid = (lo + hi) / 2
if (`val` >= arr[mid]) {
lo = mid + 1
} else {
ans = mid
hi = mid - 1
}
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,407 | LeetCode-in-Kotlin | MIT License |
src/main/java/challenges/educative_grokking_coding_interview/fast_slow_pointers/_4/CircularArrayLoop.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.fast_slow_pointers._4
import java.util.*
/**
An input array, nums containing non-zero integers, is given, where the value at each index represents the number of places to skip forward (if the value is positive) or backward (if the value is negative). When skipping forward or backward, wrap around if you reach either end of the array. For this reason, we are calling it a circular array. Determine if this circular array has a cycle. A cycle is a sequence of indices in the circular array characterized by the following:
The same set of indices is repeated when the sequence is traversed in accordance with the aforementioned rules.
The length of the sequence is at least two.
The loop must be in a single direction, forward or backward.
It should be noted that a cycle in the array does not have to originate at the beginning. A cycle can begin from any point in the array.
https://www.educative.io/courses/grokking-coding-interview-patterns-java/g2m3z3wzLDD
*/
object CircularArrayLoop {
fun circularArrayLoop(nums: IntArray): Boolean {
val size = nums.size
// Iterate through each index of the array 'nums'.
for (i in 0 until size) {
// Set slow and fast pointer at current index value.
var slow = i
var fast = i
// Set true in 'forward' if element is positive, set false otherwise.
val forward = nums[i] > 0
while (true) {
// Move slow pointer to one step.
slow = nextStep(slow, nums[slow], size)
// If cycle is not possible, break the loop and start from next element.
if (isNotCycle(nums, forward, slow)) break
// First move of fast pointer.
fast = nextStep(fast, nums[fast], size)
// If cycle is not possible, break the loop and start from next element.
if (isNotCycle(nums, forward, fast)) break
// Second move of fast pointer.
fast = nextStep(fast, nums[fast], size)
// If cycle is not possible, break the loop and start from next element.
if (isNotCycle(nums, forward, fast)) break
// At any point, if fast and slow pointers meet each other,
// it indicates that loop has been found, return true.
if (slow == fast) return true
}
}
return false
}
// A function to calculate the next step
fun nextStep(pointer: Int, value: Int, size: Int): Int {
var result = (pointer + value) % size
if (result < 0) result += size
return result
}
// A function to detect a cycle doesn't exist
fun isNotCycle(nums: IntArray, prevDirection: Boolean, pointer: Int): Boolean {
// Set current direction to true if current element is positive, set false otherwise.
val currDirection = nums[pointer] >= 0
// If current direction and previous direction are different or moving a pointer takes back to the same value,
// then the cycle is not possible, we return true, otherwise return false.
return if (prevDirection != currDirection || Math.abs(nums[pointer] % nums.size) == 0) {
true
} else false
}
@JvmStatic
fun main(args: Array<String>) {
val input = arrayOf(
intArrayOf(-2, -3, -9),
intArrayOf(-5, -4, -3, -2, -1),
intArrayOf(-1, -2, -3, -4, -5),
intArrayOf(2, 1, -1, -2),
intArrayOf(-1, -2, -3, -4, -5, 6),
intArrayOf(1, 2, -3, 3, 4, 7, 1),
intArrayOf(2, 2, 2, 7, 2, -1, 2, -1, -1)
)
for (i in input.indices) {
println(
"""
${i + 1}. Circular array = ${Arrays.toString(input[i])}
""".trimIndent()
)
val result = circularArrayLoop(input[i])
println("\tFound Loop = $result")
println(String(CharArray(100)).replace('\u0000', '-'))
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 4,140 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/day14/Day14.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day14
import java.io.File
import kotlin.math.min
import kotlin.math.max
fun main() {
val data = parse("src/main/kotlin/day14/Day14.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 14 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Segment(
val points: List<Pair<Int, Int>>,
)
private fun String.toSegment(): Segment =
split(" -> ")
.map { it.split(",").let { (a, b) -> a.toInt() to b.toInt() } }
.let { points -> Segment(points) }
@Suppress("SameParameterValue")
private fun parse(path: String): Set<Pair<Int, Int>> =
File(path).readLines().map { it.toSegment() }.toObstacles()
private fun List<Segment>.toObstacles(): Set<Pair<Int, Int>> {
val obstacles = mutableSetOf<Pair<Int, Int>>()
for ((points) in this) {
for ((a, b) in points.zipWithNext()) {
val (ax, ay) = a
val (bx, by) = b
if (ax == bx) {
for (dy in min(ay, by)..max(ay, by)) {
obstacles += ax to dy
}
} else {
for (dx in min(ax, bx)..max(ax, bx)) {
obstacles += dx to ay
}
}
}
}
return obstacles
}
private fun part1(data: Set<Pair<Int, Int>>): Int {
val obstacles = data.toMutableSet()
val maxy = obstacles.maxBy { (_, y) -> y }.second
var sandCount = 0
outer@while (true) {
var sx = 500
var sy = 0
inner@while (sx to sy !in obstacles) {
sy += 1
if (sx to sy in obstacles) {
if ((sx - 1) to sy !in obstacles) {
sx -= 1
} else if ((sx + 1) to sy !in obstacles) {
sx += 1
} else {
sy -= 1
break@inner
}
}
if (sy >= maxy) {
break@outer
}
}
obstacles += sx to sy
sandCount += 1
}
return sandCount
}
private fun part2(data: Set<Pair<Int, Int>>): Int {
val obstacles = data.toMutableSet()
val maxy = obstacles.maxBy { (_, y) -> y }.second
var sandCount = 0
outer@while (true) {
var sx = 500
var sy = 0
inner@while (sx to sy !in obstacles) {
sy += 1
if (sx to sy in obstacles) {
if ((sx - 1) to sy !in obstacles) {
sx -= 1
} else if ((sx + 1) to sy !in obstacles) {
sx += 1
} else {
sy -= 1
break@inner
}
}
if (sy == maxy + 2) {
sy -= 1
break@inner
}
}
obstacles += sx to sy
sandCount += 1
if (sx == 500 && sy == 0) {
break@outer
}
}
return sandCount
}
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 3,061 | advent-of-code-2022 | MIT License |
android/src/main/kotlin/com/cloudwebrtc/webrtc/model/VideoConstraints.kt | krida2000 | 510,302,729 | false | null | package com.cloudwebrtc.webrtc.model
import org.webrtc.CameraEnumerator
/**
* Direction in which the camera produces the video.
*
* @property value [Int] representation of this enum which will be expected on the Flutter side.
*/
enum class FacingMode(val value: Int) {
/**
* Indicates that the video source is facing toward the user (this includes, for example, the
* front-facing camera on a smartphone).
*/
USER(0),
/**
* Indicates that the video source is facing away from the user, thereby viewing their
* environment. This is the back camera on a smartphone.
*/
ENVIRONMENT(1);
companion object {
/**
* Tries to create a [FacingMode] based on the provided [Int].
*
* @param value [Int] value to create the [FacingMode] from.
*
* @return [FacingMode] based on the provided [Int].
*/
fun fromInt(value: Int) = values().first { it.value == value }
}
}
/**
* Score of [VideoConstraints].
*
* This score will be determined by a [ConstraintChecker] and basing on it, more suitable video
* device will be selected by `getUserMedia` request.
*/
enum class ConstraintScore {
/**
* Indicates that the constraint is not suitable at all.
*
* So, the device with this score wouldn't used event if there is no other devices.
*/
NO,
/** Indicates that the constraint can be used, but more suitable devices can be found. */
MAYBE,
/** Indicates that the constraint suits ideally. */
YES;
companion object {
/**
* Calculates the total score based on which media devices will be sorted.
*
* @param scores List of [ConstraintScore]s of some device.
*
* @return Total score calculated based on the provided list.
*/
fun totalScore(scores: List<ConstraintScore>): Int? {
var total = 1
for (score in scores) {
when (score) {
NO -> return null
YES -> total++
MAYBE -> {}
}
}
return total
}
}
}
/** Interface for all the video constraints which can check suitability of some device. */
interface ConstraintChecker {
/** Indicates that this constraint is mandatory or not. */
val isMandatory: Boolean
/**
* Calculates a [ConstraintScore] of the device based on the underlying algorithm of the concrete
* constraint.
*
* @param enumerator Object for interaction with Camera API.
* @param deviceId ID of the device which should be checked for this constraint.
*
* @return [ConstraintScore] based on the underlying scoring algorithm.
*/
fun score(enumerator: CameraEnumerator, deviceId: String): ConstraintScore {
val fits = isFits(enumerator, deviceId)
return when {
fits -> {
ConstraintScore.YES
}
isMandatory && !fits -> {
ConstraintScore.NO
}
else -> {
ConstraintScore.MAYBE
}
}
}
/**
* Calculates suitability to the provided device.
*
* @param enumerator Object for an interaction with Camera API.
* @param deviceId ID of device which suitability should be checked.
*
* @return `true` if device is suitable, or `false` otherwise.
*/
fun isFits(enumerator: CameraEnumerator, deviceId: String): Boolean
}
/**
* Constraint searching for a device with some concrete `deviceId`.
*
* @property id Concrete `deviceId` to be searched.
* @property isMandatory Indicates that this constraint is mandatory.
*/
data class DeviceIdConstraint(val id: String, override val isMandatory: Boolean) :
ConstraintChecker {
override fun isFits(enumerator: CameraEnumerator, deviceId: String): Boolean {
return deviceId == id
}
}
/**
* Constraint searching for a device with some [FacingMode].
*
* @property facingMode [FacingMode] which will be searched.
* @property isMandatory Indicates that this constraint is mandatory.
*/
data class FacingModeConstraint(val facingMode: FacingMode, override val isMandatory: Boolean) :
ConstraintChecker {
override fun isFits(enumerator: CameraEnumerator, deviceId: String): Boolean {
return when (facingMode) {
FacingMode.USER -> enumerator.isFrontFacing(deviceId)
FacingMode.ENVIRONMENT -> enumerator.isBackFacing(deviceId)
}
}
}
/**
* List of constraints for video devices.
*
* @property constraints List of the [ConstraintChecker] provided by user.
* @property width Width of the device video.
* @property height Height of the device video.
* @property fps FPS of the device video.
*/
data class VideoConstraints(
val constraints: List<ConstraintChecker>,
val width: Int?,
val height: Int?,
val fps: Int?,
) {
companion object {
/**
* Creates new [VideoConstraints] object based on the method call received from the Flutter
* side.
*
* @return [VideoConstraints] created from the provided [Map].
*/
fun fromMap(map: Map<*, *>): VideoConstraints? {
val constraintCheckers = mutableListOf<ConstraintChecker>()
var width: Int? = null
var height: Int? = null
var fps: Int? = null
val mandatoryArg = map["mandatory"] as Map<*, *>?
val optionalArg = map["optional"] as Map<*, *>?
if (mandatoryArg == null && optionalArg == null) {
return null
} else {
for ((key, value) in mandatoryArg ?: mapOf<Any, Any>()) {
if (value != null) {
when (key as String) {
"deviceId" -> {
constraintCheckers.add(DeviceIdConstraint(value as String, true))
}
"facingMode" -> {
constraintCheckers.add(FacingModeConstraint(FacingMode.fromInt(value as Int), true))
}
"width" -> {
width = value as Int
}
"height" -> {
height = value as Int
}
"fps" -> {
fps = value as Int
}
}
}
}
for ((key, value) in optionalArg ?: mapOf<Any, Any>()) {
if (value != null) {
when (key as String) {
"deviceId" -> {
constraintCheckers.add(DeviceIdConstraint(value as String, false))
}
"facingMode" -> {
constraintCheckers.add(
FacingModeConstraint(FacingMode.fromInt(value as Int), false))
}
"width" -> {
width = value as Int
}
"height" -> {
height = value as Int
}
"fps" -> {
fps = value as Int
}
}
}
}
return VideoConstraints(constraintCheckers, width, height, fps)
}
}
}
/**
* Calculates a score for the device with the provided ID.
*
* @param enumerator Object for interaction with Camera API.
* @param deviceId ID of the device to check suitability with.
* @return total Score calculated based on the provided list.
*/
fun calculateScoreForDeviceId(enumerator: CameraEnumerator, deviceId: String): Int? {
val scores = mutableListOf<ConstraintScore>()
for (constraint in constraints) {
scores.add(constraint.score(enumerator, deviceId))
}
return ConstraintScore.totalScore(scores)
}
}
| 0 | Rust | 0 | 0 | 146467b24dd16a2786c3843f773cd08da68bc83c | 7,320 | webrtc | MIT License |
2023/09/Solution.kt | AdrianMiozga | 588,519,359 | false | {"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732} | import java.io.File
private const val FILENAME = "2023/09/input.txt"
fun main() {
partOne()
partTwo()
}
private fun partOne() {
val file = File(FILENAME).readLines()
.map { it -> it.split(" ").map { it.toInt() } }
var sum = 0
for (line in file) {
val sequence: MutableList<MutableList<Int>> = mutableListOf()
sequence.add(line.toMutableList())
while (true) {
val inner = mutableListOf<Int>()
for (i in 0 until sequence.last().size - 1) {
inner.add(sequence.last()[i + 1] - sequence.last()[i])
}
sequence.add(inner)
if (inner.all { it == 0 }) {
break
}
}
for (i in sequence.size - 2 downTo 0) {
val newValue = sequence[i].last().plus(sequence[i + 1].last())
sequence[i].add(newValue)
}
sum += sequence.first().last()
}
println(sum)
}
private fun partTwo() {
val file = File(FILENAME).readLines()
.map { it -> it.split(" ").map { it.toInt() } }
var sum = 0
for (line in file) {
val sequence: MutableList<MutableList<Int>> = mutableListOf()
sequence.add(line.toMutableList())
while (true) {
val inner = mutableListOf<Int>()
for (i in 0 until sequence.last().size - 1) {
inner.add(sequence.last()[i + 1] - sequence.last()[i])
}
sequence.add(inner)
if (inner.all { it == 0 }) {
break
}
}
for (i in sequence.size - 2 downTo 0) {
val newValue = sequence[i].first().minus(sequence[i + 1].first())
sequence[i].add(0, newValue)
}
sum += sequence.first().first()
}
println(sum)
}
| 0 | Kotlin | 0 | 0 | c9cba875089d8d4fb145932c45c2d487ccc7e8e5 | 1,823 | Advent-of-Code | MIT License |
src/net/sheltem/aoc/y2022/Day07.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2022
const val maxSpace: Long = 70_000_000
const val spaceNeeded: Long = 30_000_000
suspend fun main() {
Day07().run()
}
class Day07 : Day<Long>(95437, 24933642) {
override suspend fun part1(input: List<String>): Long = input.buildTree().getAllFolders().map { it.size }.filter { it <= 100_000 }.sum()
override suspend fun part2(input: List<String>): Long {
val root = input.buildTree()
val deletionTarget = (spaceNeeded - (maxSpace - root.size))
return root.getAllFolders().filter { it.size >= deletionTarget }.minOf { it.size }
}
}
private fun Folder.getAllFolders(): List<Folder> = listOf(this) + content.filterIsInstance<Folder>().flatMap { it.getAllFolders() }
private fun List<String>.buildTree(): Folder = drop(1).iterator().let(Folder()::applyInstructions)
private class Folder(val content: MutableList<FSNode> = mutableListOf()) : FSNode {
override val size: Long
get() = content.sumOf { it.size }
fun applyInstructions(instructions: Iterator<String>): Folder {
while (instructions.hasNext()) {
if (applyInstruction(instructions)) return this
}
return this
}
private fun applyInstruction(instructions: Iterator<String>) = instructions.next().let { instruction ->
when {
instruction == "$ cd .." -> return true
instruction.startsWith("$ cd") -> Folder().applyInstructions(instructions).let { content.add(it) }.also { return false }
instruction[0].isDigit() -> addFile(instruction.split(" ").first()).also { return false }
else -> return false
}
}
private fun addFile(size: String) = content.add(File(size.toLong()))
}
private class File(override val size: Long) : FSNode
interface FSNode {
val size: Long
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 1,827 | aoc | Apache License 2.0 |
src/main/kotlin/g1301_1400/s1367_linked_list_in_binary_tree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1301_1400.s1367_linked_list_in_binary_tree
// #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree #Linked_List
// #Programming_Skills_II_Day_4 #2023_06_06_Time_237_ms_(92.86%)_Space_39.4_MB_(78.57%)
import com_github_leetcode.ListNode
import com_github_leetcode.TreeNode
/*
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
/*
* 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 isSubPath(head: ListNode?, root: TreeNode?): Boolean {
return if (root == null) {
false
} else (
doesRootHaveList(head, root) ||
isSubPath(head, root.left) ||
isSubPath(head, root.right)
)
}
private fun doesRootHaveList(head: ListNode?, root: TreeNode?): Boolean {
if (head == null) {
return true
}
return if (root == null) {
false
} else (
head.`val` == root.`val` &&
(
doesRootHaveList(head.next, root.left) ||
doesRootHaveList(head.next, root.right)
)
)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,430 | LeetCode-in-Kotlin | MIT License |
Lab6/src/main/kotlin/GrahamMethod.kt | knu-3-velychko | 276,473,844 | false | null | //Graham Algorithm for sorted points set
class GrahamMethod(private val points: MutableList<Point>) {
val hull by lazy {
if (points.size <= 3) {
points.toList()
} else {
val start = getLowest()
val ind = points.indexOf(start)
points[ind] = points[0]
points[0] = start
points.map { it.angle = Math.atan2(it.y - start.y, it.x - start.x) * 180 / Math.PI }
points.sortBy { it.angle }
val hull = mutableListOf<Point>()
hull.add(points[0])
hull.add(points[1])
hull.add(points[2])
for (i in 3 until points.size) {
while (hull.size >= 2 && getSide(points[i], hull[hull.size - 2], hull[hull.size - 1]) <= 0) {
hull.remove(hull.last())
}
hull.add(points[i])
}
hull
}
}
private fun getLowest(): Point {
var lowest = points[0]
for (i in points) {
if (i.y < lowest.y || (i.y == lowest.y && i.x < lowest.x)) {
lowest = i
}
}
return lowest
}
private fun getSide(a: Point, b: Point, c: Point): Int {
val rotation = getRotation(a, b, c)
if (rotation > 0)
return 1
if (rotation < 0)
return -1
return 0
}
private fun getRotation(a: Point, b: Point, c: Point) = (c.y - a.y) * (b.x - a.x) - (b.y - a.y) * (c.x - a.x)
} | 0 | Kotlin | 0 | 0 | b16603d78bf44f927f4f6389754a5d015a25f7e2 | 1,524 | ComputerGraphics | MIT License |
src/Day04.kt | Advice-Dog | 436,116,275 | true | {"Kotlin": 25836} | fun main() {
fun part1(input: List<String>): Int {
val board = input.toBoard()
board.numbers.forEach {
println("Calling number: $it")
board.call(it)
val bingo = board.boards.find { it.hasBingo() }
if (bingo != null) {
println("BINGO")
val score = bingo.getScore() * it
println("score: $score")
return score
}
}
return -1
}
fun part2(input: List<String>): Int {
val board = input.toBoard()
val boards = board.boards.toMutableList()
var score = -1
board.numbers.forEach {
println("Calling number: $it")
println("boards: ${boards.size}, score: $score")
board.call(it)
val bingos = boards.filter { it.hasBingo() }
if (bingos.isNotEmpty()) {
for (bingo in bingos) {
println("BINGO\n$bingo")
score = bingo.getScore() * it
boards.remove(bingo)
}
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = getTestData("Day04")
check(part1(testInput) == 4512)
check(part2(testInput) == 1924)
val input = getData("Day04")
println(part1(input))
println(part2(input))
}
fun List<String>.toBoard(): Bingo {
val numbers = this.first().split(",").map { it.toInt() }
println(numbers)
val windowed = this.subList(2, this.size)
.windowed(5, 6)
println(windowed)
val map = windowed.map {
it.map {
val split = it.split(" ")
.filter { it.isNotBlank() }
split.map { it.toInt() }
}
}
println(map)
val list = map.map {
Board(it.map { it.map { BoardPosition(it) } })
}
print(list)
return Bingo(numbers, list)
}
data class Bingo(val numbers: List<Int>, val boards: List<Board>) {
fun call(number: Int) {
boards.forEach { it.call(number) }
}
}
data class Board(val positions: List<List<BoardPosition>>) {
fun call(number: Int) {
positions.forEach { it.forEach { it.call(number) } }
}
fun hasBingo(): Boolean {
val any = positions.any { it.all { it.hasBeenCalled } }
if (any)
return true
for (i in 0..4)
if (positions.all { it.elementAt(i).hasBeenCalled }) {
return true
}
return false
}
fun getScore(): Int {
return positions.flatten()
.filter { !it.hasBeenCalled }
.sumOf { it.value }
}
override fun toString(): String {
return positions.joinToString(separator = "\n") {
it.joinToString(separator = " ") { it.toString() }
}
//return super.toString()
}
}
data class BoardPosition(val value: Int, var hasBeenCalled: Boolean = false) {
fun call(number: Int) {
if (value == number)
hasBeenCalled = true
}
override fun toString(): String {
return if (hasBeenCalled)
"."
else
return value.toString()
}
} | 0 | Kotlin | 0 | 0 | 2a2a4767e7f0976dba548d039be148074dce85ce | 3,257 | advent-of-code-kotlin-template | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LuckyNumbersInMatrix.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
fun interface AbstractLuckyNumbers {
operator fun invoke(matrix: Array<IntArray>): List<Int>
}
class LuckyNumbers : AbstractLuckyNumbers {
override operator fun invoke(matrix: Array<IntArray>): List<Int> {
val m = matrix.size
val n = matrix[0].size
val mi = IntArray(m) { Integer.MAX_VALUE }
val mx = IntArray(n)
for (i in 0 until m) {
for (j in 0 until n) {
mi[i] = matrix[i][j].coerceAtMost(mi[i])
mx[j] = matrix[i][j].coerceAtLeast(mx[j])
}
}
val res: MutableList<Int> = ArrayList()
for (i in 0 until m) {
for (j in 0 until n) {
if (mi[i] == mx[j]) {
res.add(mi[i])
}
}
}
return res
}
}
class LuckyNumbersSet : AbstractLuckyNumbers {
override operator fun invoke(matrix: Array<IntArray>): List<Int> {
val minSet: MutableSet<Int> = HashSet()
val maxSet: MutableSet<Int> = HashSet()
for (row in matrix) {
var mi = row[0]
for (cell in row) {
mi = mi.coerceAtMost(cell)
}
minSet.add(mi)
}
for (j in matrix[0].indices) {
var mx = matrix[0][j]
for (i in matrix.indices) {
mx = matrix[i][j].coerceAtLeast(mx)
}
if (minSet.contains(mx)) {
maxSet.add(mx)
}
}
return maxSet.toList()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,172 | kotlab | Apache License 2.0 |
src/main/kotlin/g2701_2800/s2709_greatest_common_divisor_traversal/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2701_2800.s2709_greatest_common_divisor_traversal
// #Hard #Array #Math #Union_Find #Number_Theory
// #2023_07_31_Time_892_ms_(81.82%)_Space_73.7_MB_(81.82%)
@Suppress("NAME_SHADOWING")
class Solution {
private var map: MutableMap<Int, Int>? = null
private lateinit var set: IntArray
private fun findParent(u: Int): Int {
return if (u == set[u]) u else findParent(set[u]).also { set[u] = it }
}
private fun union(a: Int, b: Int) {
val p1 = findParent(a)
val p2 = findParent(b)
if (p1 != p2) {
set[b] = p1
}
set[p2] = p1
}
private fun solve(n: Int, index: Int) {
var n = n
if (n % 2 == 0) {
val x = map!!.getOrDefault(2, -1)
if (x != -1) {
union(x, index)
}
while (n % 2 == 0) n /= 2
map!!.put(2, index)
}
val sqrt = kotlin.math.sqrt(n.toDouble()).toInt()
for (i in 3..sqrt) {
if (n % i == 0) {
val x = map!!.getOrDefault(i, -1)
if (x != -1) {
union(x, index)
}
while (n % i == 0) n /= i
map!!.put(i, index)
}
}
if (n > 2) {
val x = map!!.getOrDefault(n, -1)
if (x != -1) {
union(x, index)
}
map!!.put(n, index)
}
}
fun canTraverseAllPairs(nums: IntArray): Boolean {
set = IntArray(nums.size)
map = HashMap()
for (i in nums.indices) set[i] = i
for (i in nums.indices) solve(nums[i], i)
val p = findParent(0)
for (i in nums.indices) if (p != findParent(i)) return false
return true
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,783 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem74/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem74
/**
* LeetCode page: [74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/);
*/
class Solution {
/* Complexity:
* Time O(LogM+LogN) and Space O(1) where M and N are the number of rows and columns in matrix;
*/
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
val row = binarySearch(target, 0, matrix.size) { index ->
matrix[index].last()
}.let { if (it < 0) -(it + 1) else it }
return (row in matrix.indices) && (matrix[row].binarySearch(target) >= 0)
}
private fun <T : Comparable<T>> binarySearch(
target: T,
fromIndex: Int,
untilIndex: Int,
readValue: (index: Int) -> T
): Int {
var low = fromIndex
var high = untilIndex - 1
while (low <= high) {
val mid = (low + high).ushr(1)
val midValue = readValue(mid)
when {
midValue < target -> low = mid + 1
midValue > target -> high = mid - 1
else -> return mid // target found and return its index
}
}
return -(low + 1) // target is not found and return the -(insertion point + 1)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,254 | hj-leetcode-kotlin | Apache License 2.0 |
kotlin/graphs/flows/MaxFlowEdmondsKarp.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.flows
import java.util.stream.Stream
// https://en.wikipedia.org/wiki/Edmonds%E2%80%93Karp_algorithm in O(V * E^2)
class MaxFlowEdmondsKarp(nodes: Int) {
var graph: Array<List<Edge>>
inner class Edge(var s: Int, var t: Int, var rev: Int, var cap: Int) {
var f = 0
}
fun addBidiEdge(s: Int, t: Int, cap: Int) {
graph[s].add(Edge(s, t, graph[t].size(), cap))
graph[t].add(Edge(t, s, graph[s].size() - 1, 0))
}
fun maxFlow(s: Int, t: Int): Int {
var flow = 0
val q = IntArray(graph.size)
while (true) {
var qt = 0
q[qt++] = s
val pred = arrayOfNulls<Edge>(graph.size)
var qh = 0
while (qh < qt && pred[t] == null) {
val cur = q[qh]
for (e in graph[cur]) {
if (pred[e.t] == null && e.cap > e.f) {
pred[e.t] = e
q[qt++] = e.t
}
}
qh++
}
if (pred[t] == null) break
var df: Int = Integer.MAX_VALUE
run {
var u = t
while (u != s) {
df = Math.min(df, pred[u]!!.cap - pred[u]!!.f)
u = pred[u]!!.s
}
}
var u = t
while (u != s) {
pred[u]!!.f += df
graph[pred[u]!!.t][pred[u]!!.rev].f -= df
u = pred[u]!!.s
}
flow += df
}
return flow
}
companion object {
// Usage example
fun main(args: Array<String?>?) {
val flow = MaxFlowEdmondsKarp(3)
flow.addBidiEdge(0, 1, 3)
flow.addBidiEdge(0, 2, 2)
flow.addBidiEdge(1, 2, 2)
System.out.println(4 == flow.maxFlow(0, 2))
}
}
init {
graph = Stream.generate { ArrayList() }.limit(nodes).toArray { _Dummy_.__Array__() }
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,026 | codelibrary | The Unlicense |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions27.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
import com.qiaoyuang.algorithm.round1.SingleDirectionNode
import com.qiaoyuang.algorithm.round1.printlnLinkedList
fun test27() {
printlnResult(SingleDirectionNode(element = 8, next = SingleDirectionNode(element = 8)))
printlnResult(SingleDirectionNode(element = 8, next = SingleDirectionNode(element = 9, next = SingleDirectionNode(element = 8))))
printlnResult(SingleDirectionNode(element = 8, next = SingleDirectionNode(element = 8, next = SingleDirectionNode(element = 8))))
printlnResult(complicatedPalindromeLinkedList())
printlnResult(SingleDirectionNode(element = 0, next = complicatedPalindromeLinkedList()))
}
/**
* Questions 27: Palindrome linked list. Time complexity O(n), space complexity O(1).
*/
private fun <T> SingleDirectionNode<T>.isPalindrome(): Boolean {
if (next == null)
return true
var pointer1: SingleDirectionNode<T>? = this
var pointer2: SingleDirectionNode<T>? = next
pointer1?.next = null
while (pointer2 != null) {
when (pointer1?.element) {
pointer2.element -> {
pointer1 = pointer1?.next
pointer2 = pointer2.next
var result = true
while (pointer1 != null || pointer2 != null) {
if (pointer1?.element != pointer2?.element) {
result = false
break
}
pointer1 = pointer1?.next
pointer2 = pointer2?.next
}
if (result)
return true
}
pointer2.next?.element -> {
pointer1 = pointer1?.next
pointer2 = pointer2.next?.next
var result = true
while (pointer1 != null || pointer2 != null) {
if (pointer1?.element != pointer2?.element) {
result = false
break
}
pointer1 = pointer1?.next
pointer2 = pointer2?.next
}
if (result)
return true
}
else -> {
val temp = pointer2.next
pointer2.next = pointer1
pointer1 = pointer2
pointer2 = temp
}
}
}
return false
}
private fun printlnResult(head: SingleDirectionNode<Int>) {
print("The linked list: ")
printlnLinkedList(head)
println("Is it palindrome linked list? ${head.isPalindrome()}")
}
private fun complicatedPalindromeLinkedList(): SingleDirectionNode<Int> =
SingleDirectionNode(element = 1, next =
SingleDirectionNode(element = 2, next =
SingleDirectionNode(element = 1, next =
SingleDirectionNode(element = 3, next =
SingleDirectionNode(element = 4, next =
SingleDirectionNode(element = 5, next =
SingleDirectionNode(element = 4, next =
SingleDirectionNode(element = 3, next =
SingleDirectionNode(element = 1, next =
SingleDirectionNode(element = 2, next =
SingleDirectionNode(element = 1, )))))))))))
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 3,170 | Algorithm | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec12.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.Node
import org.elwaxoro.advent.PuzzleDayTester
/**
* Passage Pathing
*/
class Dec12 : PuzzleDayTester(12, 2021) {
override fun part1(): Any = parse().let { nodes ->
val start = nodes["start"]!!
// reserve the special small cave ahead of time, preventing any small node re-visits (part 2 only)
flail(start, specialSmallCave = start, listOf(start)).size
}
override fun part2(): Any = parse().let { nodes ->
val start = nodes["start"]!!
flail(start, specialSmallCave = null, listOf(start)).size
}
private fun flail(current: Node, specialSmallCave: Node?, path: List<Node>): List<List<Node>> =
if (!current.canLeave) {
listOf(path) // exit found, nowhere else to go!
} else {
current.edges.keys.mapNotNull {
if (!it.canVisit) {
null // start can never be re-visited
} else if (it.canRevisit || !it.canLeave || !path.contains(it)) {
flail(it, specialSmallCave, path.plus(it)) // big caves, the exit, and un-visited small caves
} else if (specialSmallCave == null) {
flail(it, it, path.plus(it)) // already visited small cave, but the special small cave is available for a second visit
} else {
null // small cave that has already been visited (or twice for special small cave)
}
}.flatten().map {
path.plus(it) // create the entire path by adding the existing path to this new section
}
}
private fun parse(): MutableMap<String, Node> = mutableMapOf<String, Node>().also { map ->
load().map { it.split("-") }.map { (a, b) ->
// bidirectional graph
val nodeA = map.getOrDefaultNode(a)
val nodeB = map.getOrDefaultNode(b)
nodeA.addEdge(nodeB)
nodeB.addEdge(nodeA)
map[a] = nodeA
map[b] = nodeB
}
}
private fun Map<String, Node>.getOrDefaultNode(name: String): Node = getOrDefault(name, Node(name, canVisit = name != "start", canLeave = name != "end", canRevisit = name.matches(Regex("[A-Z]+"))))
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,283 | advent-of-code | MIT License |
src/main/kotlin/day5/Day5.kt | mortenberg80 | 574,042,993 | false | {"Kotlin": 50107} | package day5
class Day5 {
fun getOrganizer(filename: String): CrateOrganizer {
val readLines = this::class.java.getResourceAsStream(filename).bufferedReader().readLines()
return CrateOrganizer(readLines)
}
}
/*
[N] [C] [Z]
[Q] [G] [V] [S] [V]
[L] [C] [M] [T] [W] [L]
[S] [H] [L] [C] [D] [H] [S]
[C] [V] [F] [D] [D] [B] [Q] [F]
[Z] [T] [Z] [T] [C] [J] [G] [S] [Q]
[P] [P] [C] [W] [W] [F] [W] [J] [C]
[T] [L] [D] [G] [P] [P] [V] [N] [R]
1 2 3 4 5 6 7 8 9
stackNumber
1 => 0-2
2 => 4-6
3 => 8-10
4 => 12-14
5 => 16-18
6 => 20-22
7 => 24-26
8 => 28-30
9 => 32-34
*/
data class CrateOrganizer(val input: List<String>) {
val stackSize: Int
val stacks: Map<Int, Stack>
val commands: List<Command>
init {
println(input.first { it.startsWith(" 1 ") }.trim().replace("\\s{2,}".toRegex(), " ").split(" "))
// 1 2 3 4 5 6 7 8 9 ==> 1 2 3 4 5 6 7 8 9 ==> 9
stackSize = input.first { it.startsWith(" 1 ") }.trim().replace("\\s{2,}".toRegex(), " ").split(" ").size
val cratesInput = input.takeWhile { !it.startsWith( " 1 ") }
println(cratesInput)
stacks = (1..stackSize)
.map { stackNumber -> cratesInput.map { it.substring((stackNumber-1)*4, (stackNumber-1)*4 + 2) } }
.map { crateInput -> crateInput.mapNotNull { Crate.fromString(it) }}
.map { Stack(it) }
.withIndex().associateBy({it.index + 1}, {it.value})
commands = input.takeLastWhile { it.startsWith("move") }.map { Command.fromString(it) }
}
fun organizeWithCrateMover9000(): Stacks {
return Stacks(commands.fold(stacks) { acc, command -> performCommand9000(acc, command) })
}
fun organizeWithCrateMover9001(): Stacks {
return Stacks(commands.fold(stacks) { acc, command -> performCommand9001(acc, command) })
}
private fun performCommand9000(stacks: Map<Int, Stack>, command: Command): Map<Int, Stack> {
if (command.repetitions == 0) return stacks
//println("Moving ${command.repetitions} from ${command.from} to ${command.to}")
val fromStack = stacks[command.from]!!
val toStack = stacks[command.to]!!
val movedCrates = fromStack.crates.take(1)
val outputStack = stacks.toMutableMap()
outputStack[command.from] = Stack(fromStack.crates.drop(1))
outputStack[command.to] = Stack(movedCrates + toStack.crates)
//println("Operation resulted in $outputStack")
return performCommand9000(outputStack, Command(repetitions = command.repetitions -1, from = command.from, to = command.to))
}
private fun performCommand9001(stacks: Map<Int, Stack>, command: Command): Map<Int, Stack> {
//println("Moving ${command.repetitions} from ${command.from} to ${command.to}")
val fromStack = stacks[command.from]!!
val toStack = stacks[command.to]!!
val movedCrates = fromStack.crates.take(command.repetitions)
val outputStack = stacks.toMutableMap()
outputStack[command.from] = Stack(fromStack.crates.drop(command.repetitions))
outputStack[command.to] = Stack(movedCrates + toStack.crates)
//println("Operation resulted in $outputStack")
return outputStack
}
}
data class Stacks(val input: Map<Int, Stack>) {
val topCrates = input.entries.sortedBy { it.key }.map { it.value }.map {it.topCrate()}.map { it.value }.joinToString("")
}
data class Stack(val crates: List<Crate>) {
fun topCrate(): Crate = crates[0]
override fun toString(): String {
return crates.toString()
}
}
data class Crate(val value: Char) {
override fun toString(): String {
return "[$value]"
}
companion object {
fun fromString(input: String): Crate? {
if (input.isNullOrBlank()) return null
return Crate(input[1])
}
}
}
data class Command(val repetitions: Int, val from: Int, val to: Int) {
override fun toString(): String {
return "[repetitions=$repetitions][from=$from][to=$to]"
}
companion object {
fun fromString(input: String): Command {
val parts = input.split(" ")
val repetitions = parts[1].toInt()
val from = parts[3].toInt()
val to = parts[5].toInt()
return Command(repetitions, from, to)
}
}
}
fun main() {
val testOrganizer = Day5().getOrganizer("/day5_test.txt")
val inputOrganizer = Day5().getOrganizer("/day5_input.txt")
println("Test stacks: ${testOrganizer.stackSize}")
println("Test stacks: ${testOrganizer.stacks}")
println("Test stacks: ${testOrganizer.commands}")
val resultingStacks = testOrganizer.organizeWithCrateMover9000()
println("Test stacks top crates: ${resultingStacks.topCrates}")
val inputResultingStacks = inputOrganizer.organizeWithCrateMover9000()
println("Input stacks top crates: ${inputResultingStacks.topCrates}")
val resultingStacks9001 = testOrganizer.organizeWithCrateMover9001()
println("Test stacks top crates: ${resultingStacks9001.topCrates}")
val inputResultingStacks9001 = inputOrganizer.organizeWithCrateMover9001()
println("Input stacks top crates: ${inputResultingStacks9001.topCrates}")
}
| 0 | Kotlin | 0 | 0 | b21978e145dae120621e54403b14b81663f93cd8 | 5,395 | adventofcode2022 | Apache License 2.0 |
src/Day06.kt | zirman | 572,627,598 | false | {"Kotlin": 89030} | fun main() {
fun part(input: List<String>, startOfPacketSize: Int): Int {
return input[0].windowed(startOfPacketSize, 1)
.indexOfFirst { it.toSet().size == startOfPacketSize } + startOfPacketSize
}
fun part1(input: List<String>): Int {
return part(input, 4)
}
fun part2(input: List<String>): Int {
return part(input, 14)
}
// test if implementation meets criteria from the description, like:
check(part1(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz")) == 5)
check(part1(listOf("nppdvjthqldpwncqszvftbrmjlhg")) == 6)
check(part1(listOf("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg")) == 10)
check(part1(listOf("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw")) == 11)
val input = readInput("Day06")
println(part1(input))
check(part2(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz")) == 23)
check(part2(listOf("nppdvjthqldpwncqszvftbrmjlhg")) == 23)
check(part2(listOf("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg")) == 29)
check(part2(listOf("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw")) == 26)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 2ec1c664f6d6c6e3da2641ff5769faa368fafa0f | 1,068 | aoc2022 | Apache License 2.0 |
src/Day24.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
import java.lang.Exception
import java.util.*
import kotlin.math.abs
import kotlin.system.measureTimeMillis
// Advent of Code 2022, Day 24: <NAME>
class Day24(input: String) {
private val startCol: Int
private val endCol: Int
private val startPos: Pt
private val endPos: Pt
private val dirs: List<List<List<Char>>>
data class Pt(val r: Int, val c: Int) // row and column
// Manhattan distance
private fun Pt.distance(other: Pt) = abs(this.r - other.r) + abs(this.c - other.c)
data class State(val pt: Pt, val time: Int)
companion object {
val DIR_LIST = listOf('>', '<', '^', 'v')
}
init {
// start pos, for the end pos we just need the next to last position & then we can add 1
val lines = input.split("\n").filter { it.isNotEmpty() }
startCol = lines[0].indexOf('.') - 1 // don't count left border
endCol = lines[lines.lastIndex].indexOf('.') -1 // don't count left border
dirs = DIR_LIST.map {dir ->
lines.drop(1).dropLast(1).map {
it.drop(1).dropLast(1).map { c ->
if (c == dir) dir else '.'
}
}
}
startPos = Pt(-1, startCol)
endPos = Pt(dirs[0].lastIndex + 1, endCol)
}
// A* search
// https://www.redblobgames.com/pathfinding/a-star/implementation.html
private fun aStarSearch(start: Pt, goal: Pt) : Int {
// store Point, time, priority
val openSet = PriorityQueue {t1: Triple<Pt, Int, Int>, t2 : Triple<Pt, Int, Int> -> (t1.third - t2.third) }
openSet.add(Triple(start, 0, 0))
val cameFrom = mutableMapOf<Pair<Pt, Int>, Pair<Pt, Int>?>()
val costSoFar = mutableMapOf<Pair<Pt, Int>, Int>()
cameFrom[start to 0] = null
costSoFar[start to 0] = 0
var cost = 0
while (openSet.isNotEmpty()) {
val current = openSet.remove()
if (current.first == goal) {
cost = costSoFar[current.first to current.second]!!
break
}
val newTime = current.second + 1
val neighbors = current.first.getMoves(newTime)
for (next in neighbors) {
val newCost = costSoFar[current.first to current.second]!! + 1
if ((next to newCost) !in costSoFar || newCost < costSoFar[next to newCost]!!) {
costSoFar[next to newCost] = newCost
val priority = newCost + next.distance(goal)
openSet.add(Triple(next, newTime, priority))
cameFrom[next to newTime] = current.first to current.second
}
}
}
return cost
}
// Return '.', blizzard direction, or '2', '3', '4' for number of blizzards at this location & time
private fun getPos(row: Int, col: Int, time: Int) : Char {
val chars = DIR_LIST.mapIndexed { idx, c ->
val width = dirs[idx][row].size
val height = dirs[idx].size
val pos = when (c) {
DIR_LIST[0] -> { // right
var offset = (col - time) % width
if (offset < 0) offset += width
dirs[idx][row][offset]
}
DIR_LIST[1] -> dirs[idx][row][(col + time) % width] // left
DIR_LIST[2] -> dirs[idx][(row + time) % height][col] // up
DIR_LIST[3] -> { // down
var offset = (row - time) % height
if (offset < 0) offset += height
dirs[idx][offset][col]
}
else -> throw Exception("bad direction")
}
pos
}
val blizzards = chars.filter { it != '.' }
return when (blizzards.size) {
0 -> '.'
1 -> blizzards.first()
else -> blizzards.size.toString().first() // we know size is 2, 3 or 4
}
}
// print top or bottom of map
private fun printBorder(len: Int, emptySpace: Int) {
for (j in 0..len + 1) {
val c = if (j - 1 == emptySpace) '.' else '#'
print(c)
}
println()
}
// print the map
private fun printMap(time: Int, path: List<Pt> = emptyList()) {
val width = dirs[0][0].size
val height = dirs[0].size
val pathDisplay = ('a'..'z').toList() + ('A'..'Z').toList()
printBorder(width, startCol)
for (row in 0 until height) {
print('#')
for (col in 0 until width) {
val idx = path.indexOf(Pt(row, col))
val c = if (idx >= 0) {
pathDisplay[idx % pathDisplay.size]
} else {
getPos(row, col, time)
}
print(c)
}
println("#")
}
printBorder(width, endCol)
}
// get possible moves from this point
private fun Pt.getMoves(time: Int): List<Pt> {
// include current position
val possibleMoves = listOf(Pt(r, c), Pt(r - 1, c), Pt(r + 1, c), Pt(r, c - 1), Pt(r, c + 1))
val width = dirs[0][0].size
val height = dirs[0].size
return possibleMoves.filter {
(it == startPos) || (it == endPos) ||
((it.r in 0 until height) &&
(it.c in 0 until width) &&
('.' == getPos(it.r, it.c, time)))
}
}
fun part1_astar() : Int {
return aStarSearch(startPos, endPos)
}
fun part1(): Int {
return BFS(startPos, endPos, 0)
}
fun part2(): Int {
val time1 = BFS(startPos, endPos, 0)
val time2 = BFS(endPos, startPos, time1)
return BFS(startPos, endPos, time2)
}
private fun BFS(start: Pt, end: Pt, startTime: Int): Int {
val queue = mutableListOf<State>()
val startMoves = start.getMoves(startTime + 1)
queue.addAll(startMoves.map { State(it, startTime + 1) })
val cache = hashSetOf<State>()
while (queue.isNotEmpty()) {
val state = queue.removeFirst()
if (state.pt == end) {
return state.time
}
if (state in cache) continue
cache.add(state)
val newTime = state.time + 1
val newMoves = state.pt.getMoves(newTime)
queue.addAll(newMoves.map { State(it, newTime) })
}
return 0 // we failed
}
}
fun main() {
fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText()
val testSolver = Day24(readInputAsOneLine("Day24_test"))
check(testSolver.part1() == 18)
check(testSolver.part2() == 54)
val solver = Day24(readInputAsOneLine("Day24"))
var result : Int
var timeInMillis = measureTimeMillis {
result = solver.part1()
}
println("part 1 $result, time is $timeInMillis ms")
timeInMillis = measureTimeMillis {
result = solver.part2()
}
println("part 2 $result, time is $timeInMillis ms")
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 7,117 | AdventOfCode2022 | Apache License 2.0 |
src/day13/Day13.kt | pnavais | 574,712,395 | false | {"Kotlin": 54079} | package day13
import readInput
import java.util.Stack
typealias PacketPair = Pair<Packet, Packet>
interface Value {
fun getData(): Any
}
class IntValue(private val data: Int) : Value {
override fun getData(): Int {
return this.data
}
companion object {
fun from(s: String): IntValue {
return IntValue(s.toInt())
}
}
override fun toString(): String {
return getData().toString()
}
}
class ListValue : Value {
private var listValue = mutableListOf<Value>()
override fun getData(): MutableList<Value> {
return listValue
}
fun add(v: Value) {
listValue.add(v)
}
companion object {
fun from(value: IntValue): ListValue {
val l = ListValue()
l.add(value)
return l
}
}
override fun toString(): String {
val builder = StringBuilder()
builder.append("[")
var prefix = ""
for (item in listValue) {
builder.append(prefix)
builder.append(item.toString())
prefix = ","
}
builder.append("]")
return builder.toString()
}
}
data class Packet(val list: ListValue)
class PacketList {
val packetPairs = mutableListOf<PacketPair>()
fun processSum(): Int {
var sum = 0
for ((i, pair) in packetPairs.withIndex()) {
val result = processPair(pair)
if ((result == null) || (result)) {
sum+=(i+1)
}
}
return sum
}
fun processDecoderKey(): Int {
var key = 1
val packetComparator = Comparator { firstPacket: Packet, secondPacket: Packet ->
val res = processPair(firstPacket to secondPacket)
if (res == null) {
0
} else if (res) {
-1
} else {
1
}
}
val packets = mutableListOf<Packet>()
packetPairs.forEach {
packets.add(it.first)
packets.add(it.second)
}
// Add divider packets
val startPacket = Packet(ListValue.from(IntValue(2)))
val endPacket = Packet(ListValue.from(IntValue(6)))
packets.add(startPacket)
packets.add(endPacket)
val sortedPackets = packets.sortedWith(packetComparator)
for ((i,sortedPacket) in sortedPackets.withIndex()) {
if (sortedPacket === startPacket) {
key*=(i+1)
} else if (sortedPacket === endPacket) {
key*=(i+1)
break
}
}
return key
}
private fun processPair(pair: PacketPair): Boolean? {
return compareListValues(pair.first.list, pair.second.list)
}
private fun compareListValues(firstList: ListValue, secondList: ListValue): Boolean? {
var result: Boolean? = null
for ((i, item) in firstList.getData().withIndex()) {
result = if (secondList.getData().size > i) {
compareValues(item, secondList.getData()[i])
} else {
false
}
if (result != null) {
break
}
}
if ((result == null) && (firstList.getData().size < secondList.getData().size)) {
result = true
}
return result
}
private fun compareValues(first: Value, second: Value): Boolean? {
var res: Boolean? = null
var firstValue: Value = first
var compareLists = true
if (first is IntValue) {
if (second is IntValue) {
if ((first.getData() != second.getData())) {
res = (first.getData() < second.getData())
}
compareLists = false
} else {
firstValue = ListValue.from(first)
}
}
if (compareLists) {
val secondValue: ListValue = if (second is ListValue) { second } else {
ListValue.from(second as IntValue)
}
res = compareListValues(firstValue as ListValue, secondValue)
}
return res
}
}
fun readSpec(input: List<String>): PacketList {
val packetList = PacketList()
var firstPacket: Packet? = null
for (line in input) {
if (line.isNotEmpty()) {
val newPacket = Packet(processList(line))
firstPacket = if (firstPacket == null) {
newPacket
} else {
packetList.packetPairs.add(firstPacket to newPacket)
null
}
}
}
return packetList
}
private fun processList(line: String): ListValue {
val listStack: Stack<ListValue> = Stack()
var currentList: ListValue? = null
val digitBuilder = StringBuilder()
for (c in line.toCharArray()) {
if (c == '[') {
if (currentList != null) {
listStack.push(currentList)
}
currentList = ListValue()
} else if (c.isDigit()) {
digitBuilder.append(c)
} else if ((c == ',') && (digitBuilder.isNotEmpty())) {
currentList?.add(IntValue.from(digitBuilder.toString()))
digitBuilder.clear()
} else if (c == ']') {
if (digitBuilder.isNotEmpty()) {
currentList?.add(IntValue.from(digitBuilder.toString()))
digitBuilder.clear()
}
if (listStack.isNotEmpty()) {
val parentList = listStack.pop()
if (parentList !== currentList) {
parentList.add(currentList!!)
}
currentList = parentList
}
}
}
return currentList!!
}
fun part1(input: List<String>): Int {
val packetList = readSpec(input)
return packetList.processSum()
}
fun part2(input: List<String>): Int {
val packetList = readSpec(input)
return packetList.processDecoderKey()
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13/Day13_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | ed5f521ef2124f84327d3f6c64fdfa0d35872095 | 6,527 | advent-of-code-2k2 | Apache License 2.0 |
codeforces/eduround68/YetAnotherCrossesProblem.kt | grine4ka | 183,575,046 | false | {"Kotlin": 98723, "Java": 28857, "C++": 4529} | package codeforces.eduround68
import java.io.PrintWriter
import kotlin.math.min
// https://codeforces.com/contest/1194/problem/B
// this is mine
//fun eduround68.eduround68.eduround68.round567.round567.round573.codeforces.codeforces.codeforces.eduround69.kotlinheroes.kotlinheroes.main(args: Array<String>) {
// val q = eduround68.readInt()
// val matrices = mutableListOf<Matrix>()
// for (i in 0 until q) {
// val (n, m) = eduround68.readInts()
// val matrix = Matrix(n, m)
// for (j in 0 until n) {
// matrix.fillRow(j, readLine()!!)
// }
// matrices.add(matrix)
// }
// matrices.forEach {
// println("${it.findMinMinutesForCrosses()}")
// }
//}
//
//class Matrix(val n: Int, val m: Int) {
//
// private val body = Array(n) {
// IntArray(m)
// }
//
// private val tbody = Array(m) {
// IntArray(n)
// }
//
// fun fillRow(row: Int, symbols: String) {
// val r = body[row]
// symbols.forEachIndexed { index, c ->
// r[index] = if (c == '*') 1 else 0
// tbody[index][row] = if (c == '*') 1 else 0
// }
// }
//
// fun findMinMinutesForCrosses(): Int {
// var minSum = Int.MAX_VALUE
// for (i in 0 until n) {
// val rowSum = m - body[i].sum()
// for (j in 0 until m) {
// val colSum = n - tbody[j].sum()
// val sub = 1 - body[i][j]
// val sum = rowSum + colSum - sub
// if (sum < minSum) {
// minSum = sum
// }
// }
// }
// return minSum
// }
//}
// this is elizarov's
fun main() {
val q = readInt()
bufferOut {
repeat(q) { solveQuery() }
}
}
private fun PrintWriter.solveQuery() {
val (n, m) = readInts()
val a = Array(n) { readLine()!!.map { it == '*' }.toBooleanArray() }
val rowSums = IntArray(n)
val colSums = IntArray(m)
for (i in 0 until n) {
for(j in 0 until m) {
if (a[i][j]) {
rowSums[i]++
colSums[j]++
}
}
}
if (rowSums.any { it == m } && colSums.any { it == n }) {
println(0)
return
}
var ans = Int.MAX_VALUE
for (i in 0 until n) {
for(j in 0 until m) {
var d = n + m - rowSums[i] - colSums[j]
if (!a[i][j]) d--
ans = min(ans, d)
}
}
println(ans)
}
private fun readInt() = readLine()!!.toInt()
private fun readInts() = readLine()!!.split(" ").map(String::toInt)
// for the future
private fun bufferOut(block: PrintWriter.() -> Unit) = PrintWriter(System.out).use { block(it) } | 0 | Kotlin | 0 | 0 | c967e89058772ee2322cb05fb0d892bd39047f47 | 2,708 | samokatas | MIT License |
src/main/kotlin/days/aoc2023/Day15.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
class Day15 : Day(2023, 15) {
override fun partOne(): Any {
return calculatePartOne(inputString)
}
override fun partTwo(): Any {
return calculatePartTwo(inputString)
}
fun calculatePartOne(input: String): Int {
return input.split(",").sumOf { hashValueOf(it) }
}
private fun hashValueOf(string: String): Int {
var hash = 0
string.forEach { c ->
hash = ((hash + c.code) * 17) % 256
}
return hash
}
fun calculatePartTwo(input: String): Int {
val boxes = mutableMapOf<Int,MutableList<Pair<String,Int>>>()
input.split(",").forEach { step ->
Regex("(\\w+)([-=])(\\d*)").matchEntire(step)?.destructured?.let { (label, operation, focalLength) ->
val boxNumber = hashValueOf(label)
val lensList = boxes.getOrPut(boxNumber) { mutableListOf() }
when (operation) {
"=" -> {
val newLens = Pair(label, focalLength.toInt())
if (lensList.any { lens -> lens.first == label } ) {
lensList[lensList.indexOfFirst { lens -> lens.first == label }] = newLens
} else {
lensList.add(newLens)
}
}
"-" -> {
lensList.removeIf { lens -> lens.first == label }
}
else -> throw IllegalArgumentException("that shouldn't have been in there")
}
}
}
return boxes.entries.sumOf { box ->
box.value.withIndex().sumOf { (lensIndex, lens) ->
(box.key + 1) * (lensIndex + 1) * lens.second
}
}
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 1,851 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/softaai/dsa_kotlin/radixsort/RadixSort.kt | amoljp19 | 537,774,597 | false | {"Kotlin": 139041} | package com.softaai.dsa_kotlin.radixsort
/**
* Created by amoljp19 on 11/22/2022.
* softAai Apps.
*/
fun MutableList<Int>.radixSort(){
val base = 10
var done = false
var digits = 1
while (!done){
done = true
val buckets = arrayListOf<MutableList<Int>>().apply {
for (i in 0..9){
this.add(arrayListOf())
}
}
this.forEach { number ->
val remaining = number / digits
if (remaining > 0 ){
done = false
}
val digit = remaining % base
buckets[digit].add(number)
}
digits *= base
this.clear()
this.addAll(buckets.flatten())
}
}
/*
Challenge 1 - Most Significant Sort
The implementation discussed in the chapter used a least significant digit radix sort.
Your task is to implement a most significant digit (MSD) radix sort.
This sorting behavior is called lexicographical sorting and is also used for String
sorting.
For example:
var list = arrayListOf(500, 1345, 13, 459, 44, 999)
list.lexicographicalSort()
println(list) // outputs [13, 1345, 44, 459, 500, 999]
*/
fun Int.digits() : Int{
var count = 0
var num = this
while (num != 0){
count +=1
num/=10
}
return count
}
fun Int.digit(atPosition : Int) : Int?{
if (atPosition > this.digits()) return null
var num = this
val correctedPosition = (atPosition + 1).toDouble()
while((num /Math.pow(10.0, correctedPosition)).toInt() != 0){
num/=10
}
return num % 10
}
/*fun MutableList<Int>.maxDigits() : Int{
return this.max().digits()
}*/
private fun List<Int>.maxDigits(): Int {
val result = this.maxOrNull()?.digits() ?: 0
//return this.maxOrNull()?.digits() ?: 0
return result
}
fun MutableList<Int>.lexicographicalSort() : MutableList<Int>{
val newList = msdRadixSorted(this, 0)
this.clear()
this.addAll(newList)
//this.addAll(msdRadixSorted(this, 0))
return this
}
private fun msdRadixSorted(list : MutableList<Int>, position : Int) : MutableList<Int>{
if(position >= list.maxDigits()) return list
val buckets = arrayListOf<MutableList<Int>>().apply {
for (i in 0..9){
this.add(arrayListOf())
}
}
val priorityBucket = arrayListOf<Int>()
list.forEach { number ->
val digit = number.digit(position)
if (digit == null){
priorityBucket.add(number)
return@forEach
}
buckets[digit].add(number)
}
priorityBucket.addAll(
buckets.reduce { result, bucket ->
if (bucket.isEmpty()) return@reduce result
result.addAll(msdRadixSorted(bucket, position+1))
result
}
)
return priorityBucket
}
| 0 | Kotlin | 0 | 1 | 3dabfbb1e506bec741aed3aa13607a585b26ac4c | 2,834 | DSA_KOTLIN | Apache License 2.0 |
src/Day03.kt | frango9000 | 573,098,370 | false | {"Kotlin": 73317} | fun main() {
val input = readInput("Day03")
println(Day03.part1(input))
println(Day03.part2(input))
}
class Day03 {
companion object {
fun part1(input: List<String>): Int {
return input.map { it.chunked(it.length / 2) }
.map { it[0].filter { x -> it[1].contains(x) }.toCharArray().first() }
.sumOf { it.code - if (it.isUpperCase()) 38 else 96 }
}
fun part2(input: List<String>): Int {
return input.chunked(3).map {
it[0].filter { x -> it[1].contains(x) && it[2].contains(x) }.toCharArray().first()
}.sumOf { it.code - if (it.isUpperCase()) 38 else 96 }
}
}
}
| 0 | Kotlin | 0 | 0 | 62e91dd429554853564484d93575b607a2d137a3 | 697 | advent-of-code-22 | Apache License 2.0 |
jvm/src/main/kotlin/boj/ChickenDelivery.kt | imdudu1 | 196,377,985 | false | {"Java": 47989, "Kotlin": 39952, "Python": 38168, "Go": 15491, "Rust": 2583, "JavaScript": 1023} | package boj
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*
import kotlin.math.abs
class ChickenDelivery constructor(private val map: Array<Array<Int>>) {
private val stores: List<Point> by lazy { getObjects(2) }
private val houses: List<Point> by lazy { getObjects(1) }
fun solution(m: Int): Int {
val openStores = BooleanArray(stores.size)
var result = Int.MAX_VALUE
combination(0, m, 0, openStores) {
val t = houses.asSequence().map { house ->
stores.asSequence().filterIndexed { index, _ -> openStores[index] }
.map { it.distance(house) }.minOf { it }
}.sum()
result = result.coerceAtMost(t)
}
return result
}
private fun combination(s: Int, m: Int, c: Int, visited: BooleanArray, action: () -> Unit) {
if (c == m) {
action()
return
}
for (i in s until stores.size) {
if (visited[i]) continue
visited[i] = true
combination(i, m, c + 1, visited, action)
visited[i] = false
}
}
data class Point constructor(val x: Int, val y: Int) {
fun distance(other: Point) = abs(x - other.x) + abs(y - other.y)
}
private fun getObjects(type: Int): List<Point> {
val result = LinkedList<Point>()
for (i in map.indices) {
for (j in map[0].indices) {
if (map[i][j] == type) {
result.add(Point(j, i))
}
}
}
return result
}
}
fun chickenDelivery(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val (n, m) = br.readLine().trim().split(" ").map { it.toInt() }
val map = Array(n) { br.readLine().trim().split(" ").map { it.toInt() }.toTypedArray() }
val solution = ChickenDelivery(map)
print(solution.solution(m))
}
| 0 | Java | 0 | 0 | ee7df895761b095d02a08f762c682af5b93add4b | 1,965 | algorithm-diary | MIT License |
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day21/StepCounter.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2023.day21
import de.havox_design.aoc.utils.kotlin.model.directions.UDLRDirection
import de.havox_design.aoc.utils.kotlin.model.positions.Position2d
import kotlin.math.pow
class StepCounter(private var filename: String) {
private val ICON_ROCK = '#'
private val ICON_START = 'S'
fun solvePart1(steps: Int = 64): Long {
val rocks = HashSet<Position2d<Int>>()
var start = Position2d(0, 0)
for ((row, inputRow) in getResourceAsText(filename).withIndex()) {
inputRow.forEachIndexed { col, ch ->
when (ch) {
ICON_START -> start = Position2d(col, row)
ICON_ROCK -> rocks.add(Position2d(col, row))
}
}
}
var reachablePlots = HashSet<Position2d<Int>>()
reachablePlots.add(start)
for (i in 1..steps) {
val next = HashSet<Position2d<Int>>()
for (position in reachablePlots) {
move(position, UDLRDirection.UP, rocks)
?.let { next.add(it) }
move(position, UDLRDirection.RIGHT, rocks)
?.let { next.add(it) }
move(position, UDLRDirection.DOWN, rocks)
?.let { next.add(it) }
move(position, UDLRDirection.LEFT, rocks)
?.let { next.add(it) }
}
reachablePlots = next
}
return reachablePlots
.size
.toLong()
}
fun solvePart2(steps: Long = 26501365L): Long {
val rocks = HashSet<Position2d<Int>>()
var start = Position2d(0, 0)
var rows = 0
for (inputRows in getResourceAsText(filename)) {
inputRows.forEachIndexed { col, ch ->
val row = rows
when (ch) {
ICON_START -> start = Position2d(col, row)
ICON_ROCK -> rocks.add(Position2d(col, row))
}
}
rows++
}
val grids = steps / rows - 1
val oddGrids = (grids / 2 * 2 + 1)
.toDouble()
.pow(2)
.toLong()
val evenGrids = ((grids + 1) / 2 * 2)
.toDouble()
.pow(2)
.toLong()
return sumUpReachablePlots(oddGrids, start, rows, rocks, evenGrids, grids)
}
private fun sumUpReachablePlots(
oddGrids: Long,
start: Position2d<Int>,
rows: Int,
rocks: HashSet<Position2d<Int>>,
evenGrids: Long,
grids: Long
) = oddGrids * reachable(start, rows * 2 + 1, rocks, rows) +
evenGrids * reachable(start, rows * 2, rocks, rows) +
reachable(Position2d(start.x, rows - 1), rows - 1, rocks, rows) +
reachable(Position2d(0, start.y), rows - 1, rocks, rows) +
reachable(Position2d(start.x, 0), rows - 1, rocks, rows) +
reachable(Position2d(rows - 1, start.y), rows - 1, rocks, rows) +
(
(grids + 1) * (reachable(Position2d(0, rows - 1), rows / 2 - 1, rocks, rows) +
reachable(Position2d(rows - 1, rows - 1), rows / 2 - 1, rocks, rows) +
reachable(Position2d(0, 0), rows / 2 - 1, rocks, rows) +
reachable(Position2d(rows - 1, 0), rows / 2 - 1, rocks, rows))
) +
(
grids * (reachable(Position2d(0, rows - 1), rows * 3 / 2 - 1, rocks, rows) +
reachable(Position2d(rows - 1, rows - 1), rows * 3 / 2 - 1, rocks, rows) +
reachable(Position2d(0, 0), rows * 3 / 2 - 1, rocks, rows) +
reachable(Position2d(rows - 1, 0), rows * 3 / 2 - 1, rocks, rows))
)
private fun move(
position: Position2d<Int>,
direction: UDLRDirection,
rocks: HashSet<Position2d<Int>>
): Position2d<Int>? =
when {
!rocks.contains(
Position2d(
position.x + direction.direction.x,
position.y + direction.direction.y
)
) -> {
Position2d(
position.x + direction.direction.x,
position.y + direction.direction.y
)
}
else -> {
null
}
}
private fun reachable(from: Position2d<Int>, steps: Int, rocks: HashSet<Position2d<Int>>, rows: Int): Int {
var reachablePlots = HashSet<Position2d<Int>>()
reachablePlots.add(from)
for (i in 1..steps) {
val next = HashSet<Position2d<Int>>()
fun move(p: Position2d<Int>, dir: Position2d<Int>) {
if (!rocks.contains(Position2d(p.x + dir.x, p.y + dir.y))) {
next.add(Position2d(p.x + dir.x, p.y + dir.y))
}
}
for (position in reachablePlots) {
move(position, UDLRDirection.UP, rocks)
?.let { next.add(it) }
move(position, UDLRDirection.RIGHT, rocks)
?.let { next.add(it) }
move(position, UDLRDirection.DOWN, rocks)
?.let { next.add(it) }
move(position, UDLRDirection.LEFT, rocks)
?.let { next.add(it) }
}
reachablePlots = next
}
return reachablePlots.count { it.x >= 0 && it.y >= 0 && it.x < rows && it.y < rows }
}
private fun getResourceAsText(path: String): List<String> =
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
}
| 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 5,757 | advent-of-code | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/ValidSudoku.kt | faniabdullah | 382,893,751 | false | null | //Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be
//validated according to the following rules:
//
//
// Each row must contain the digits 1-9 without repetition.
// Each column must contain the digits 1-9 without repetition.
// Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9
//without repetition.
//
//
// Note:
//
//
// A Sudoku board (partially filled) could be valid but is not necessarily
//solvable.
// Only the filled cells need to be validated according to the mentioned rules.
//
//
//
//
// Example 1:
//
//
//Input: board =
//[["5","3",".",".","7",".",".",".","."]
//,["6",".",".","1","9","5",".",".","."]
//,[".","9","8",".",".",".",".","6","."]
//,["8",".",".",".","6",".",".",".","3"]
//,["4",".",".","8",".","3",".",".","1"]
//,["7",".",".",".","2",".",".",".","6"]
//,[".","6",".",".",".",".","2","8","."]
//,[".",".",".","4","1","9",".",".","5"]
//,[".",".",".",".","8",".",".","7","9"]]
//Output: true
//
//
// Example 2:
//
//
//Input: board =
//[["8","3",".",".","7",".",".",".","."]
//,["6",".",".","1","9","5",".",".","."]
//,[".","9","8",".",".",".",".","6","."]
//,["8",".",".",".","6",".",".",".","3"]
//,["4",".",".","8",".","3",".",".","1"]
//,["7",".",".",".","2",".",".",".","6"]
//,[".","6",".",".",".",".","2","8","."]
//,[".",".",".","4","1","9",".",".","5"]
//,[".",".",".",".","8",".",".","7","9"]]
//Output: false
//Explanation: Same as Example 1, except with the 5 in the top left corner
//being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is
//invalid.
//
//
//
// Constraints:
//
//
// board.length == 9
// board[i].length == 9
// board[i][j] is a digit 1-9 or '.'.
//
// Related Topics Array Hash Table Matrix 👍 3644 👎 625
package leetcodeProblem.leetcode.editor.en
class ValidSudoku {
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 isValidSudoku(board: Array<CharArray>): Boolean {
// 9 x 9 .
// detect HashMap row detect HashMap Coloumn
// detect HashMap Board .
// detect HashMap Row and Board .
val seen: HashSet<String> = hashSetOf()
for (i in board.indices) {
for (j in board[i].indices) {
board[i][j].run {
if (this != '.') {
if (!seen.add("$this in row $i") ||
!seen.add("$this in column $j") ||
!seen.add("$this in box ${i / 3} - ${j / 3}")
) return false
}
}
}
}
return true
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,952 | dsa-kotlin | MIT License |
src/nativeMain/kotlin/Day7.kt | rubengees | 576,436,006 | false | {"Kotlin": 67428} | class Day7 : Day {
private data class File(val name: String, val size: Int)
private data class Dir(
val name: String,
val parent: Dir? = null
) {
private val dirs = mutableListOf<Dir>()
private val files = mutableListOf<File>()
val size: Int
get() {
return this.dirs.sumOf { it.size } + files.sumOf { it.size }
}
fun addFile(file: File) {
this.files.add(file)
}
fun addDir(name: String) {
this.dirs.add(Dir(name, this))
}
fun subDir(name: String): Dir {
return this.dirs.find { it.name == name } ?: error("Unknown dir $name")
}
fun sequence(): Sequence<Dir> = sequence {
yield(this@Dir)
for (dir in dirs) {
yieldAll(dir.sequence())
}
}
}
private val fileRegex = Regex("^(\\d+) (.*)$")
private fun parse(input: String): Dir {
val root = Dir("/")
var current = root
for (line in input.lines()) {
if (line == "$ cd /") {
current = root
} else if (line == "$ ls") {
continue
} else if (line == "$ cd ..") {
current = current.parent ?: error("Dir ${current.name} has no parent")
} else if (line.startsWith("$ cd ")) {
current = current.subDir(line.substring(5))
} else if (line.startsWith("dir")) {
current.addDir(line.substring(4))
} else if (line.matches(fileRegex)) {
val match = fileRegex.matchEntire(line) ?: error("Line did not match regex")
val size = match.groupValues[1].toInt()
val name = match.groupValues[2]
current.addFile(File(name, size))
} else {
error("Unknown command $line")
}
}
return root
}
override suspend fun part1(input: String): String {
return parse(input).sequence().filter { it.size <= 100_000 }.sumOf { it.size }.toString()
}
override suspend fun part2(input: String): String {
val fileSystem = parse(input)
val usedSpace = fileSystem.size
val unusedSpace = 70_000_000 - usedSpace
val requiredSpace = 30_000_000 - unusedSpace
return fileSystem.sequence().filter { it.size >= requiredSpace }.minOf { it.size }.toString()
}
}
| 0 | Kotlin | 0 | 0 | 21f03a1c70d4273739d001dd5434f68e2cc2e6e6 | 2,485 | advent-of-code-2022 | MIT License |
2017/src/main/kotlin/Day10.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import utils.splitCommas
import utils.toIntList
import java.util.*
object Day10 {
fun part1(input: String, size: Int = 256): Int {
val list = (0 until size).toMutableList()
val lengths = input.splitCommas().toIntList()
hash(list, lengths)
return list[0] * list[1]
}
fun part2(input: String): String {
val list = (0 until 256).toMutableList()
val lengths = input.map { it.toInt() } + listOf(17, 31, 73, 47, 23)
var hashState = HashState(0, 0)
for (a in 0 until 64) {
hashState = hash(list, lengths, hashState)
}
return list.chunked(16)
.map { it.reduce { acc, i -> acc.xor(i) } }
.joinToString("") { "%02x".format(it) }
}
data class HashState(val position: Int, val skipSize: Int)
private fun hash(list: MutableList<Int>,
lengths: List<Int>,
hashState: HashState = HashState(0, 0)): HashState {
val size = list.size
var position = hashState.position
var skipSize = hashState.skipSize
for (length in lengths) {
reverse(list, position, position + length)
position = (position + length + skipSize) % size
skipSize++
}
return HashState(position, skipSize)
}
private fun reverse(list: MutableList<Int>, fromInclusive: Int, toExclusive: Int) {
val mid = (fromInclusive + toExclusive) / 2
val length = (toExclusive - fromInclusive)
for (a in (0 until length)) {
val reversePosition = fromInclusive + a
if (reversePosition >= mid) {
return
}
val i = reversePosition % list.size
val j = (toExclusive - a - 1) % list.size
Collections.swap(list, i, j)
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,678 | advent-of-code | MIT License |
src/main/aoc2015/Day6.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2015
import Pos
import kotlin.math.max
class Day6(input: List<String>) {
sealed class Instruction(val x: IntRange, val y: IntRange) {
class Toggle(x: IntRange, y: IntRange) : Instruction(x, y) {
override fun op(v: Int, part1: Boolean) = if (part1) (v + 1) % 2 else v + 2
}
class TurnOn(x: IntRange, y: IntRange) : Instruction(x, y) {
override fun op(v: Int, part1: Boolean) = if (part1) 1 else v + 1
}
class TurnOff(x: IntRange, y: IntRange) : Instruction(x, y) {
override fun op(v: Int, part1: Boolean) = if (part1) 0 else max(0, v - 1)
}
abstract fun op(v: Int, part1: Boolean): Int
}
private val lights = input.map { line ->
val x1 = line.substringBefore(",").substringAfterLast(" ").toInt()
val y1 = line.substringAfter(",").substringBefore(" ").toInt()
val x2 = line.substringBeforeLast(",").substringAfterLast(" ").toInt()
val y2 = line.substringAfterLast(",").substringBefore(" ").toInt()
when {
(line.startsWith("turn on")) -> Instruction.TurnOn(x1..x2, y1..y2)
(line.startsWith("turn off")) -> Instruction.TurnOff(x1..x2, y1..y2)
(line.startsWith("toggle")) -> Instruction.Toggle(x1..x2, y1..y2)
else -> throw RuntimeException("Unknown instruction type: $line")
}
}
private fun runInstructions(part1: Boolean): Int {
val grid = mutableMapOf<Pos, Int>()
lights.forEach { instruction ->
for (y in instruction.y) {
for (x in instruction.x) {
val pos = Pos(x, y)
grid[pos] = instruction.op(grid.getOrDefault(pos, 0), part1)
}
}
}
return grid.values.sum()
}
fun solvePart1(): Int {
return runInstructions(part1 = true)
}
fun solvePart2(): Int {
return runInstructions(part1 = false)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,984 | aoc | MIT License |
src/Day04.kt | tristanrothman | 572,898,348 | false | null | fun main() {
fun String.toIntRange() = this.substringBefore("-").toInt()..this.substringAfter("-").toInt()
fun String.toIntRanges() = this.substringBefore(",").toIntRange() to this.substringAfter(",").toIntRange()
infix fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last
infix fun IntRange.intersect(other: IntRange) = first <= other.last && other.first <= last
fun part1(input: List<String>): Int {
return input.map { it.toIntRanges() }.count {
it.first contains it.second || it.second contains it.first
}
}
fun part2(input: List<String>): Int {
return input.map { it.toIntRanges() }.count {
it.first intersect it.second
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e794ab7e0d50f22d250c65b20e13d9b5aeba23e2 | 952 | advent-of-code-2022 | Apache License 2.0 |
kotlin/0074-search-a-2d-matrix.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | // binary search on rows to find row, then binary search on actual row O(log(m*n))
class Solution {
// TC: O(log m + log n)
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
var row = matrix.size
var col = matrix.first().size
var top = 0
var bot = row - 1
while ( top <= bot ){
row = (top + bot ) / 2
if(target > matrix[row][col - 1]){
top = row + 1
} else if(target < matrix[row][0]) {
bot = row - 1
} else {
break
}
}
if((top > bot)) return false
row = (top + bot) / 2
var l = 0
var r = col - 1
while(l <= r){
var m = (l + r) / 2
if(target > matrix[row][m]){
l = m + 1
} else if(target < matrix[row][m]){
r = m - 1
} else {
return true
}
}
return false
}
}
//binary search on whole matrix (search the matrix as an sorted array) O(log(m*n))
class Solution {
fun searchMatrix(mt: Array<IntArray>, t: Int): Boolean {
val rows = mt.size
val cols = mt[0].size
var l = 0
var r = rows * cols - 1
while (l != r) {
val m = (l + r) / 2
if (mt[m / cols][m % cols] < t)
l = m + 1
else
r = m
}
return mt[r / cols][r % cols] == t
}
}
//treat the matrix as an BST, root at mt[0][-1] O(m + n)
class Solution {
fun searchMatrix(mt: Array<IntArray>, t: Int): Boolean {
val rows = mt.size
val cols = mt[0].size
var row = 0
var col = cols - 1
while (row < rows && col >= 0) {
val cur = mt[row][col]
if (cur > t)
col--
else if (cur < t)
row++
else
return true
}
return false
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 2,010 | leetcode | MIT License |
Möbius_function/Kotlin/src/MobiusFunction.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | import kotlin.math.sqrt
fun main() {
println("First 199 terms of the möbius function are as follows:")
print(" ")
for (n in 1..199) {
print("%2d ".format(mobiusFunction(n)))
if ((n + 1) % 20 == 0) {
println()
}
}
}
private const val MU_MAX = 1000000
private var MU: IntArray? = null
// Compute mobius function via sieve
private fun mobiusFunction(n: Int): Int {
if (MU != null) {
return MU!![n]
}
// Populate array
MU = IntArray(MU_MAX + 1)
val sqrt = sqrt(MU_MAX.toDouble()).toInt()
for (i in 0 until MU_MAX) {
MU!![i] = 1
}
for (i in 2..sqrt) {
if (MU!![i] == 1) {
// for each factor found, swap + and -
for (j in i..MU_MAX step i) {
MU!![j] *= -i
}
// square factor = 0
for (j in i * i..MU_MAX step i * i) {
MU!![j] = 0
}
}
}
for (i in 2..MU_MAX) {
when {
MU!![i] == i -> {
MU!![i] = 1
}
MU!![i] == -i -> {
MU!![i] = -1
}
MU!![i] < 0 -> {
MU!![i] = 1
}
MU!![i] > 0 -> {
MU!![i] = -1
}
}
}
return MU!![n]
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 1,334 | rosetta | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/StrangePrinter.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.min
/**
* 664. Strange Printer
* @see <a href="https://leetcode.com/problems/strange-printer/">Source</a>
*/
fun interface StrangePrinter {
operator fun invoke(s: String): Int
}
/**
* Approach 1: Bottom-Up Dynamic Programming
*/
class StrangePrinterBottomUp : StrangePrinter {
override operator fun invoke(s: String): Int {
val n: Int = s.length
val dp = Array(n) { IntArray(n) }
for (length in 1..n) {
for (left in 0..n - length) {
val right = left + length - 1
var j = -1
dp[left][right] = n
for (i in left until right) {
if (s[i] != s[right] && j == -1) {
j = i
}
if (j != -1) {
dp[left][right] =
min(dp[left][right].toDouble(), (1 + dp[j][i] + dp[i + 1][right]).toDouble())
.toInt()
}
}
if (j == -1) {
dp[left][right] = 0
}
}
}
return dp[0][n - 1] + 1
}
}
/**
* Approach 2: Top-Down Dynamic Programming (Memoization)
*/
class StrangePrinterTopDown : StrangePrinter {
private lateinit var dp: Array<IntArray>
override operator fun invoke(s: String): Int {
val n: Int = s.length
dp = Array(n) { IntArray(n) }
for (left in 0 until n) {
for (right in 0 until n) {
dp[left][right] = -1
}
}
return solve(s, n, 0, n - 1) + 1
}
private fun solve(s: String, n: Int, left: Int, right: Int): Int {
if (dp[left][right] != -1) {
return dp[left][right]
}
dp[left][right] = n
var j = -1
for (i in left until right) {
if (s[i] != s[right] && j == -1) {
j = i
}
if (j != -1) {
dp[left][right] =
min(dp[left][right].toDouble(), (1 + solve(s, n, j, i) + solve(s, n, i + 1, right)).toDouble())
.toInt()
}
}
if (j == -1) {
dp[left][right] = 0
}
return dp[left][right]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,946 | kotlab | Apache License 2.0 |
algorithm/src/test/kotlin/com/seanshubin/condorcet/algorithm/CondorcetAlgorithmTest.kt | SeanShubin | 190,099,313 | false | null | package com.seanshubin.condorcet.algorithm
import kotlin.test.Test
import kotlin.test.assertEquals
class CondorcetAlgorithmTest {
@Test
fun typical() {
// given
val election = "typical election"
val candidates = setOf("frank", "grace", "eve")
val eligibleVoters = setOf("bob", "dave", "alice", "carol")
val aliceBallot = Ballot("alice", "code-4", mapOf(Pair("grace", 1), Pair("eve", 2), Pair("frank", 3)))
val carolBallot = Ballot("carol", "code-3", mapOf(Pair("grace", 2), Pair("eve", 1), Pair("frank", 3)))
val daveBallot = Ballot("dave", "code-5", mapOf(Pair("grace", 3), Pair("eve", 2), Pair("frank", 1)))
val ballots = listOf(aliceBallot, carolBallot, daveBallot)
val request = TallyElectionRequest(election, candidates, eligibleVoters, ballots)
// when
val response = CondorcetAlgorithm.tally(request)
// then
assertEquals("typical election", response.election)
assertEquals(listOf("eve", "frank", "grace"), response.candidates)
assertEquals(listOf("alice", "carol", "dave"), response.voted)
assertEquals(listOf("bob"), response.didNotVote)
assertEquals(
listOf(Placing(1, listOf("eve")),
Placing(2, listOf("grace")),
Placing(3, listOf("frank"))),
response.placings)
assertEquals(listOf(carolBallot, aliceBallot, daveBallot), response.ballots)
assertEquals(listOf(listOf(0, 2, 2), listOf(1, 0, 1), listOf(1, 2, 0)), response.preferenceMatrix)
assertEquals(listOf(listOf(0, 2, 2), listOf(1, 0, 1), listOf(1, 2, 0)), response.strongestPathMatrix)
}
// input validation (philosophy: fail if anything looks like it might have been a mistake)
// candidates must be unique
// eligible voters must be unique
// ballot voters must be unique
// every ballot voter must match a voter
// ballot confirmations must be unique
// every ballot ranking must match a candidate
// rankings must already be normalized
// output validation (philosophy: accurate, predictable ordering)
// candidates must be sorted
// voted must be sorted
// not voted must be sorted
// rankings must be ascending by rank
// candidates with same rank must be sorted
// ballots must be sorted by confirmation
// preference matrix must match candidate order
// strongest path matrix must match candidate order
} | 2 | Kotlin | 0 | 0 | 61219ae238b47792a5d347625f4963a1b2841d2d | 2,503 | condorcet5 | The Unlicense |
src/main/kotlin/g0401_0500/s0494_target_sum/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0401_0500.s0494_target_sum
// #Medium #Top_100_Liked_Questions #Array #Dynamic_Programming #Backtracking
// #Big_O_Time_O(n*(sum+s))_Space_O(n*(sum+s))
// #2022_09_16_Time_308_ms_(89.61%)_Space_37.2_MB_(61.04%)
@Suppress("NAME_SHADOWING")
class Solution {
fun findTargetSumWays(nums: IntArray, target: Int): Int {
var target = target
var sum = 0
target = Math.abs(target)
for (num in nums) {
sum += num
}
// Invalid target, just return 0
if (target > sum || (sum + target) % 2 != 0) {
return 0
}
val dp = Array((sum + target) / 2 + 1) { IntArray(nums.size + 1) }
dp[0][0] = 1
// empty knapsack must be processed specially
for (i in nums.indices) {
if (nums[i] == 0) {
dp[0][i + 1] = dp[0][i] * 2
} else {
dp[0][i + 1] = dp[0][i]
}
}
for (i in 1 until dp.size) {
for (j in nums.indices) {
dp[i][j + 1] += dp[i][j]
if (nums[j] <= i) {
dp[i][j + 1] += dp[i - nums[j]][j]
}
}
}
return dp[(sum + target) / 2][nums.size]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,250 | LeetCode-in-Kotlin | MIT License |
aoc-common/src/main/kotlin/nl/jstege/adventofcode/aoccommon/utils/extensions/Collections.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoccommon.utils.extensions
/**
* Extra utilities for lists.
* @author <NAME>
*/
/**
* Transposes a list of lists in 2 dimensional space. This function does not check whether all
* rows have an equal amount of elements. Rather, it assumes all rows have an equal amount of
* elements to the first row. Giving a 2D-list of varying row sizes results in undefined behaviour.
*
* @receiver The list to transpose.
* @return The transposed list of lists.
* @throws IllegalArgumentException if the list is empty, or the columns are empty.
*/
fun <E> List<List<E>>.transpose(): List<List<E>> {
tailrec fun <E> List<List<E>>.transpose(accumulator: List<List<E>>): List<List<E>> =
if (this.isEmpty() || this.first().isEmpty()) accumulator
else this.map { it.tail }.transpose(accumulator + listOf(this.map { it.head }))
return if (this.isEmpty() || this.head.isEmpty()) {
throw IllegalArgumentException("Empty columns or rows found. Can not transpose.")
} else {
this.transpose(mutableListOf())
}
}
/**
* Calculates all permutations of the given collection.
*
* @receiver The collection to calculate permutations of.
* @return A sequence of all permutations.
*/
fun <E> Collection<E>.permutations(): Sequence<List<E>> = sequence {
val a = this@permutations.toMutableList()
val c = IntArray(this@permutations.size) { 0 }
yield(a.toList())
var i = 0
while (i < a.size) {
if (c[i] < i) {
a.swap(if (i.isEven) 0 else c[i], i)
yield(a.toList())
c[i] += 1
i = 0
} else {
c[i] = 0
i += 1
}
}
}
/**
* Calculates and returns all combinations of a given size of the given collection.
*
* @receiver The collection to calculate combinations of.
* @param n The size of the combinations.
* @return A sequence of all combinations.
*/
fun <E> Collection<E>.combinations(n: Int): Sequence<Set<E>> {
fun IntArray.valid(@Suppress("NAME_SHADOWING") n: Int, k: Int): Boolean {
if (this.size != k) {
return false
}
(0 until k).forEach { i ->
if (this[i] < 0L || this[i] > n - 1) {
return false
}
if ((i + 1 until k).filter { this[i] >= this[it] }.any()) {
return false
}
}
return true
}
return sequence {
val dataSet = this@combinations.toList()
val indices = IntArray(n) { it }
while (indices.valid(dataSet.size, n)) {
yield(indices.map { dataSet[it] }.toSet())
var i = n - 1
while (i > 0 && indices[i] == dataSet.size - n + i) {
i--
}
indices[i]++
while (i < n - 1) {
indices[i + 1] = indices[i] + 1
i++
}
}
}
}
fun <E> List<E>.cycle(): Sequence<E> =
generateSequence(0) { (it + 1) % this.size }.map { this[it] }
fun <E> List<E>.copy(vararg replacement: Pair<Int, E>): List<E> =
this.toMutableList().apply { replacement.forEach { (i, r) -> this[i] = r } }
/**
* Swaps two elements in the given MutableList
*
* @receiver The MutableList to mutate.
* @param i The index of the first element.
* @param j The index of the second element.
*/
fun <E> MutableList<E>.swap(i: Int, j: Int) {
val t = this[i]
this[i] = this[j]
this[j] = t
}
fun <E> List<E>.reverse(start: Int, length: Int): List<E> =
(start until start + length)
.zipWithReverse()
.asSequence()
.take(length / 2)
.fold(this.toMutableList()) { list, (f, s) ->
list.apply { swap(f % this.size, s % this.size) }
}
/**
* Returns a list of each element and their tails in the given list.
* E.g. ["a", "b", "c"] -> [["a", "b", "c"], ["b", "c"], ["c"]]
* @receiver List<E>
* @return List<List<E>> all elements and their tails.
*/
fun <E> List<E>.tails(): List<List<E>> {
tailrec fun tails(current: List<E>, acc: List<List<E>>): List<List<E>> =
if (current.isEmpty()) acc
else tails(current.drop(1), acc + listOf(current))
return tails(this, listOf())
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 4,233 | AdventOfCode | MIT License |
src/Day05.kt | luiscobo | 574,302,765 | false | {"Kotlin": 19047} | import java.util.*
fun main() {
val stacks = mutableListOf<Stack<Char>>()
fun crearPilas(n: Int) {
for (i in 0 until n) {
stacks.add(Stack())
}
}
fun procesarLinea(linea: String): Boolean {
if (linea.isNotEmpty()) {
for (i in 1 until linea.length step 4) {
if (linea[i].isUpperCase()) {
val n = (i - 1) / 4
stacks[n].push(linea[i])
}
}
return true
}
return false
}
fun procesarPilas(input: List<String>): Int {
var n = 0
while (!input[n][1].isDigit()) {
n++
}
val aux = input[n].split(" ")
var x = aux.size - 1
var tam = 0
while (x >= 0) {
if (aux[x].isNotEmpty()) {
tam = aux[x].toInt()
break
}
x--
}
crearPilas(tam)
for (i in n - 1 downTo 0) {
val linea = input[i]
procesarLinea(linea)
}
return n
}
fun obtenerDatosLinea(linea: String): Triple<Int, Int, Int> {
val lista = linea.split(" ")
return Triple(lista[1].toInt(), lista[3].toInt() - 1, lista[5].toInt() - 1)
}
fun ejecutarMovimiento(cuantos: Int, desde: Int, hasta: Int) {
repeat (cuantos) {
val elem = stacks[desde].pop()
stacks[hasta].push(elem)
}
}
// -------------------------------------------------------
fun part1(input: List<String>): String {
val numPilas = procesarPilas(input)
for (i in numPilas + 2 until input.size) {
val linea = input[i]
val (cuantos, desde, hasta) = obtenerDatosLinea(linea)
ejecutarMovimiento(cuantos, desde, hasta)
}
var resp = ""
for (stack in stacks) {
resp += stack.peek()
}
println(stacks[0])
return resp
}
// -------------------------------------------------------------
fun ejercutarMovimiento9001(cuantos: Int, desde: Int, hasta: Int) {
val posInicial = stacks[desde].size - cuantos
repeat (cuantos) {
val elem = stacks[desde].get(posInicial)
stacks[hasta].push(elem)
stacks[desde].removeAt(posInicial)
}
}
fun part2(input: List<String>): String {
stacks.clear()
val numPilas = procesarPilas(input)
for (i in numPilas + 2 until input.size) {
val linea = input[i]
val (cuantos, desde, hasta) = obtenerDatosLinea(linea)
ejercutarMovimiento9001(cuantos, desde, hasta)
}
var resp = ""
for (stack in stacks) {
resp += stack.peek()
}
return resp
}
// -------------------------------------------------------------
val input = readInput("day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c764e5abca0ea40bca0b434bdf1ee2ded6458087 | 2,993 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day04.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 java.lang.RuntimeException
open class Part4A : PartSolution() {
lateinit var pairs: List<String>
override fun parseInput(text: String) {
pairs = text.trim().split("\n")
}
override fun compute(): Int {
return pairs.map(::Sections).count(Sections::isSubset)
}
override fun getExampleAnswer(): Int {
return 2
}
internal data class Sections(val section1: Set<Int>, val section2: Set<Int>) {
/**
* Get if [section1] is a subset of [section2] or [section2] is a subset of [section1]
*/
fun isSubset(): Boolean {
return section1.containsAll(section2) || section2.containsAll(section1)
}
/**
* Get if the sections do overlap
*/
fun doOverlap(): Boolean {
return section1.intersect(section2).isNotEmpty()
}
}
internal fun Sections(pair: String): Sections {
val result = Regex("^(\\d+)-(\\d+),(\\d+)-(\\d+)").find(pair) ?: throw RuntimeException()
val startS1 = result.groupValues[1].toInt()
val startS2 = result.groupValues[3].toInt()
val endS1 = result.groupValues[2].toInt()
val endS2 = result.groupValues[4].toInt()
val section1 = (startS1..endS1).toSet()
val section2 = (startS2..endS2).toSet()
return Sections(section1, section2)
}
}
class Part4B : Part4A() {
override fun compute(): Int {
return pairs.map(::Sections).count(Sections::doOverlap)
}
override fun getExampleAnswer(): Int {
return 4
}
}
fun main() {
Day(2022, 4, Part4A(), Part4B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 1,753 | advent-of-code-kotlin | MIT License |
src/Day05.kt | Inn0 | 573,532,249 | false | {"Kotlin": 16938} | data class Move(
val amount: Int,
val from: Int,
val to: Int
)
fun main() {
fun getCargo(input: List<String>): MutableList<MutableList<Char>> {
val inputCargo = input.subList(0, input.indexOf(""))
val cleanedInputCargo = mutableListOf<String>()
var inputSize = 0
inputCargo.forEach {
if(it.contains("[")){
var cargoString = it.replace(" ", "x")
cargoString = cargoString.replace(" ", "")
cargoString = cargoString.replace("[", "")
cargoString = cargoString.replace("]", "")
if(inputSize < cargoString.length){
inputSize = cargoString.length
}
cleanedInputCargo.add(cargoString)
}
}
val outputCargo = mutableListOf<String>()
cleanedInputCargo.forEach {
var newString = it
if(it.length < inputSize){
newString += "x".repeat(inputSize - it.length)
}
outputCargo.add(newString)
}
val cargoLists: MutableList<MutableList<Char>> = mutableListOf()
outputCargo.forEach {
cargoLists.add(it.toList().toMutableList())
}
val returnCargoList: MutableList<MutableList<Char>> = MutableList(inputSize) { mutableListOf() }
cargoLists.forEach {
for(i in 0 until inputSize) {
returnCargoList[i].add(it[i])
}
}
repeat(inputSize) {
returnCargoList.forEach {
it.remove('x')
}
}
return returnCargoList
}
fun getMoves(input: List<String>): MutableList<Move> {
val inputMoves = input.subList(input.indexOf("") + 1, input.size)
val cleanedMoves = mutableListOf<Move>()
inputMoves.forEach {
var str = it.replace("move ", "")
str = str.replace("from ", "")
str = str.replace("to ", "")
val arr = str.split(" ")
cleanedMoves.add(Move(arr[0].toInt(), arr[1].toInt(), arr[2].toInt()))
}
return cleanedMoves
}
fun part1(input: List<String>): String {
val cargo = getCargo(input)
val moves = getMoves(input)
for(move in moves){
repeat(move.amount){
val c = cargo[move.from - 1][0]
cargo[move.from - 1].removeAt(0)
cargo[move.to - 1].add(0, c)
}
}
var returnStr = ""
cargo.forEach {
returnStr += it[0]
}
return returnStr
}
fun part2(input: List<String>): String {
val cargo = getCargo(input)
val moves = getMoves(input)
for(move in moves){
val listToAppend = cargo[move.from - 1].take(move.amount).toMutableList()
cargo[move.to - 1].addAll(0, listToAppend)
repeat(listToAppend.size){
cargo[move.from - 1].removeAt(0)
}
}
println(cargo)
var returnStr = ""
cargo.forEach {
if(it.isNotEmpty()) {
returnStr += it[0]
}
}
return returnStr
}
// 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("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | f35b9caba5f0c76e6e32bc30196a2b462a70dbbe | 3,538 | aoc-2022 | Apache License 2.0 |
src/poyea/aoc/mmxxii/day03/Day03.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day03
import poyea.aoc.utils.readInput
fun part1(input: String): Int {
return input.split("\n").sumOf {
val char = it.substring(0, it.length / 2).toSet().intersect(it.substring(it.length / 2).toSet()).first()
if (char.isLowerCase()) char - 'a' + 1 else char - 'A' + 27
}
}
fun part2(input: String): Int {
return input.split("\n").chunked(3).sumOf {
val char = it[0].toSet().intersect(it[1].toSet().intersect(it[2].toSet())).first()
if (char.isLowerCase()) char - 'a' + 1 else char - 'A' + 27
}
}
fun main() {
println(part1(readInput("Day03")))
println(part2(readInput("Day03")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 666 | aoc-mmxxii | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[54]螺旋矩阵.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
//
//
//
// 示例 1:
//
//
//输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
//输出:[1,2,3,6,9,8,7,4,5]
//
//
// 示例 2:
//
//
//输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
//输出:[1,2,3,4,8,12,11,10,9,5,6,7]
//
//
//
//
// 提示:
//
//
// m == matrix.length
// n == matrix[i].length
// 1 <= m, n <= 10
// -100 <= matrix[i][j] <= 100
//
// Related Topics 数组 矩阵 模拟
// 👍 812 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
//获取上下左右边界 然后遍历获取就行
var res = ArrayList<Int>()
if(matrix.isEmpty()) return res
var left = 0
var top = 0
var right = matrix[0].size -1
var bottom = matrix.size -1
while (true){
//左到右
for (i in left ..right){
res.add(matrix[top][i])
}
if(++top> bottom){
//如果上边界到达底部
break
}
//上到下
for (i in top ..bottom){
res.add(matrix[i][right])
}
//如果右边界到左边界
if (left>--right) break
//右到左
for (i in right downTo left){
res.add(matrix[bottom][i])
}
//如果到达上边界
if (top>--bottom) break
//下到上
for (i in bottom downTo top){
res.add(matrix[i][left])
}
//如果左边界到右边界
if (++left>right) break
}
return res
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,891 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/com/github/davio/aoc/y2022/Day2.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2022
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.call
import com.github.davio.aoc.general.getInputAsSequence
import com.github.davio.aoc.y2022.Day2.Outcome.*
import com.github.davio.aoc.y2022.Day2.RockPaperScissors.*
import kotlin.system.measureTimeMillis
fun main() {
Day2.getResultPart1()
measureTimeMillis {
Day2.getResultPart2()
}.call { println("Took $it ms") }
}
/**
* See [Advent of Code 2022 Day 2](https://adventofcode.com/2022/day/2#part2])
*/
object Day2 : Day() {
enum class Outcome(val points: Int) {
WIN(6),
DRAW(3),
LOSE(0)
}
enum class RockPaperScissors(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3),
}
private val opponentCodeMap = mapOf(
'A' to ROCK,
'B' to PAPER,
'C' to SCISSORS
)
private val rspStructure = arrayOf(SCISSORS, ROCK, PAPER)
private fun RockPaperScissors.getOutcomeAgainstOpponent(opponentChoice: RockPaperScissors): Outcome {
if (this == opponentChoice) {
return DRAW
}
val choiceToWin = rspStructure[(rspStructure.indexOf(opponentChoice) + 1) % rspStructure.size]
return if (this == choiceToWin) {
WIN
} else {
LOSE
}
}
fun getResultPart1() {
val yourCodeMap = mapOf(
'X' to ROCK,
'Y' to PAPER,
'Z' to SCISSORS
)
getInputAsSequence().map {
val opponentChoice = opponentCodeMap[(it.first())]!!
val yourChoice = yourCodeMap[it[2]]!!
yourChoice.points + yourChoice.getOutcomeAgainstOpponent(opponentChoice).points
}.sum()
.call { println(it) }
}
fun getResultPart2() {
val desiredOutcomeMap = mapOf(
'X' to LOSE,
'Y' to DRAW,
'Z' to WIN
)
getInputAsSequence().map {
val opponentChoice = opponentCodeMap[(it.first())]!!
val desiredOutcome = desiredOutcomeMap[it[2]]!!
desiredOutcome.points + when (desiredOutcome) {
DRAW -> opponentChoice.points
WIN -> rspStructure[(rspStructure.indexOf(opponentChoice) + 1) % rspStructure.size].points
LOSE -> {
val losingIndex = (rspStructure.indexOf(opponentChoice) - 1).let { index ->
if (index < 0) index + rspStructure.size else index
}
rspStructure[losingIndex].points
}
}
}.sum()
.call { println(it) }
}
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 2,682 | advent-of-code | MIT License |
kotlin/pig-latin/src/main/kotlin/PigLatin.kt | colintheshots | 117,450,747 | false | null | import java.util.*
object PigLatin {
private val vowels = setOf('a','e','i','o','u')
fun translate(input: String) : String {
require(input.all { it.isLowerCase() || it.isWhitespace() })
return input.replace("\\b\\w+\\b".toRegex()) { result : MatchResult ->
val word = result.value
when {
word[0] in vowels -> word + "ay"
word.startsWith("qu") -> word.substring(2) + "quay"
word.startsWith("squ") -> word.substring(3) + "squay"
word == "xray" -> word + "ay"
else -> {
val firstY = word.indexOfFirst { it == 'y' }
val firstVowel = word.indexOfFirst { it in vowels }
val beforeVowel = firstVowel == -1 || firstY < firstVowel
val yIsVowel = firstY != -1 && (word.length == firstY + 1
|| word.length > firstY + 1
&& word[firstY + 1] !in vowels)
if (beforeVowel && yIsVowel) {
val beforeY = word.substring(0, firstY)
val afterY = word.substring(firstY)
afterY + beforeY + "ay"
} else {
val beginning = if (firstVowel != -1) word.substring(firstVowel) else word
val remainder = if (firstVowel != -1) word.substring(0, firstVowel) else ""
beginning + remainder + "ay"
}
}
}
}
}
}
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val numTestCases = scanner.nextInt()
require(numTestCases in 1..20)
(0 until numTestCases).map {
val numThieves = scanner.nextInt()
require(numThieves in 1..100)
val duration = scanner.nextInt()
require(duration in 0..1000000)
val thiefSlots = mutableListOf(0, 0)
val entries = (0 until numThieves).map { scanner.nextInt() }
entries.forEach{ require(it in 0..100)}
entries.forEach{
thiefSlots.addToSmallest(it)
}
if (thiefSlots.max()!! > duration) {
"NO"
} else {
"YES"
}
}.forEach(::println)
}
fun MutableList<Int>.addToSmallest(duration : Int) : MutableList<Int> {
val indexOfSmallest = indexOfFirst { it == min() }
this[indexOfSmallest] += duration
return this
} | 0 | Kotlin | 0 | 0 | f284aecd7f017c3fd972c1dcf9d1c4b25866d614 | 2,482 | ExercismKotlin | Apache License 2.0 |
src/Day05.kt | baghaii | 573,918,961 | false | {"Kotlin": 11922} | import java.util.*
import kotlin.collections.ArrayDeque
fun main() {
fun part1(input: List<String>, stacks: List<Stack<Char>>): String {
input.forEach {
val tokens = it.split(' ')
val howMany = tokens[1].toInt()
val fromStack = tokens[3].toInt() - 1
val toStack = tokens[5].toInt() - 1
for (i in 0 until howMany) {
val char = stacks[fromStack].pop()
stacks[toStack].push(char)
}
}
val word = String(stacks.map{ it.pop() }.toCharArray())
return word
}
fun part2(input: List<String>, stacks: List<Stack<Char>>): String {
input.forEach {
val tokens = it.split(' ')
val howMany = tokens[1].toInt()
val fromStack = tokens[3].toInt() - 1
val toStack = tokens[5].toInt() - 1
val tempStack = Stack<Char>()
for (i in 0 until howMany) {
val char = stacks[fromStack].pop()
tempStack.push(char)
}
while (tempStack.isNotEmpty()) {
val charToMove = tempStack.pop()
stacks[toStack].push(charToMove)
}
}
val word = String(stacks.map{ it.pop() }.toCharArray())
return word
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput, buildTestStack()) == "CMZ")
check(part2(testInput, buildTestStack()) == "MCD")
val input = readInput("Day05")
println(part1(input, buildStack()))
println(part2(input, buildStack()))
}
fun buildTestStack(): List<Stack<Char>> {
val stack1 = Stack<Char>()
stack1.push('Z')
stack1.push('N')
val stack2 = Stack<Char>()
stack2.push('M')
stack2.push('C')
stack2.push('D')
val stack3 = Stack<Char>()
stack3.push('P')
return listOf(stack1, stack2, stack3)
}
fun buildStack(): List<Stack<Char>> {
val stack1 = Stack<Char>()
stack1.push('L')
stack1.push('N')
stack1.push('W')
stack1.push('T')
stack1.push('D')
val stack2 = Stack<Char>()
stack2.push('C')
stack2.push('P')
stack2.push('H')
val stack3 = Stack<Char>()
stack3.push('W')
stack3.push('P')
stack3.push('H')
stack3.push('N')
stack3.push('D')
stack3.push('G')
stack3.push('M')
stack3.push('J')
val stack4 = Stack<Char>()
stack4.push('C')
stack4.push('W')
stack4.push('S')
stack4.push('N')
stack4.push('T')
stack4.push('Q')
stack4.push('L')
val stack5 = Stack<Char>()
stack5.push('P')
stack5.push('H')
stack5.push('C')
stack5.push('N')
val stack6 = Stack<Char>()
stack6.push('T')
stack6.push('H')
stack6.push('N')
stack6.push('D')
stack6.push('M')
stack6.push('W')
stack6.push('Q')
stack6.push('B')
val stack7 = Stack<Char>()
stack7.push('M')
stack7.push('B')
stack7.push('R')
stack7.push('J')
stack7.push('G')
stack7.push('S')
stack7.push('L')
val stack8 = Stack<Char>()
stack8.push('Z')
stack8.push('N')
stack8.push('W')
stack8.push('G')
stack8.push('V')
stack8.push('B')
stack8.push('R')
stack8.push('T')
val stack9 = Stack<Char>()
stack9.push('W')
stack9.push('G')
stack9.push('D')
stack9.push('N')
stack9.push('P')
stack9.push('L')
return(listOf(stack1, stack2, stack3, stack4, stack5, stack6, stack7, stack8, stack9))
}
| 0 | Kotlin | 0 | 0 | 8c66dae6569f4b269d1cad9bf901e0a686437469 | 3,569 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/ikueb/advent18/Day17.kt | h-j-k | 159,901,179 | false | null | package com.ikueb.advent18
import com.ikueb.advent18.model.*
import java.util.*
object Day17 {
private const val DEFINITION = "(.)=(\\d+), .=(\\d+)..(\\d+)"
private val source = Point(500, 0)
fun getWaterReach(input: List<String>): Int {
val state = process(input)
val yMin = state.getTokens().minBy { it.y() }!!.y()
return state.flatMap { it.additions }
.distinctBy { it.point }
.count { it.y() >= yMin }
}
fun getWaterRetained(input: List<String>) = process(input)
.flatMap { it.additions }
.count { it is StillWater }
private fun process(input: List<String>): Ground {
val veins = input.parseWith(DEFINITION) { (axis, a, b1, b2) ->
when (axis) {
"x" -> (b1.toInt()..b2.toInt()).map { b -> Clay(Point(a.toInt(), b)) }
else -> (b1.toInt()..b2.toInt()).map { b -> Clay(Point(b, a.toInt())) }
}
}.flatten()
val boundary: Boundary = getBoundary(setOf(source).union(veins.map { it.point }))
.let { (topLeft, bottomRight) -> topLeft.w() to bottomRight.e() }
val base = ".".repeat(boundary.getWidth())
return (1..boundary.getHeight()).map { y ->
Layer(veins.filter { it.atRow(y - 1) }.toSet(), base)
}.also { it.flow(boundary, source) }
}
}
private typealias Layer = MutableInputLine<Clay, Water>
private fun Layer.nothingAt(point: Point) =
tokens().none { it.point == point } && additions.none { it.point == point }
private typealias Ground = List<Layer>
private fun Ground.flow(boundary: Boundary, start: Point) {
val toProcess = ArrayDeque<Point>().apply { add(start) }
while (toProcess.isNotEmpty()) {
val now = toProcess.removeFirst()
val south = now.s()
if (!boundary.contains(south)
|| isFlowing(boundary, toProcess, south) { it }) continue
val veins = this[south.y].tokens().map { it.point }
val stillWater = this[south.y].additions
.filter { it is StillWater }
.map { it.point }
if (veins.any { it == south } || stillWater.any { it == south }) {
val flowEast = isFlowing(boundary, toProcess, now.e()) { it }
val flowWest = isFlowing(boundary, toProcess, now.w()) { it }
if (flowEast || flowWest) continue
}
if (hasSideWalls(boundary, now)) {
fillHorizontal(now)
}
}
}
private fun Ground.isFlowing(boundary: Boundary,
toProcess: Deque<Point>,
point: Point,
toPrevious: (Point) -> Point): Boolean {
return if (boundary.contains(point) && this[point.y].nothingAt(point)) {
this[point.y].additions.add(FlowingWater(point))
toProcess.addFirst(toPrevious(point))
toProcess.addFirst(point)
true
} else false
}
private fun Ground.hasSideWalls(boundary: Boundary, point: Point): Boolean =
hasSideWall(boundary, point) { it.e() }
&& hasSideWall(boundary, point) { it.w() }
private fun Ground.hasSideWall(boundary: Boundary,
point: Point,
toNext: (Point) -> Point): Boolean {
var now = point
while (boundary.contains(now)) {
with(this[now.y]) {
when (now) {
in tokens().map { it.point } -> return true
in additions.map { it.point } -> now = toNext(now)
else -> return false
}
}
}
return false
}
private fun Ground.fillHorizontal(point: Point) {
fill(point) { it.e() }
fill(point) { it.w() }
}
private fun Ground.fill(point: Point, toNext: (Point) -> Point) {
var now = point
with(this[now.y]) {
while (tokens().none { it.point == now }) {
additions.add(StillWater(now))
now = toNext(now)
}
}
}
private data class Clay(override var point: Point) : InputToken(point) {
override fun isActive() = true
override fun toString() = "#"
}
private typealias Water = InputToken
private data class StillWater(override var point: Point) : Water(point) {
override fun isActive() = true
override fun toString() = "~"
}
private data class FlowingWater(override var point: Point) : Water(point) {
override fun isActive() = true
override fun toString() = "|"
} | 0 | Kotlin | 0 | 0 | f1d5c58777968e37e81e61a8ed972dc24b30ac76 | 4,483 | advent18 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day04.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
fun main() {
val testInput = """2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8""".split("\n")
fun String.toIntRange(): IntRange {
val (start, end) = split('-')
return start.toInt()..end.toInt()
}
infix fun IntRange.covers(second: IntRange) = first <= second.first && last >= second.last
infix fun IntRange.intersects(second: IntRange) =
second.first in this || second.last in this || this.first in second
fun parseToRanges(input: List<String>) = input
.map { it.split(',').map { it.toIntRange() } }
fun part1(input: List<String>): Int = parseToRanges(input)
.count {
val (first, second) = it
(first covers second) || (second.covers(first))
}
fun part2(input: List<String>) = parseToRanges(input)
.count {
val (first, second) = it
first intersects second
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 2)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 4)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 1,263 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/Day10.kt | SimonMarquis | 724,825,757 | false | {"Kotlin": 30983} | import Day10.Pipe.`▉`
class Day10(input: List<String>) {
private val map = input.map { it.map(Char::toChar).map(Pipe.Companion::from).toTypedArray() }.toTypedArray()
private val start: Coordinate = map.withIndex().firstNotNullOf { (y, pipes) ->
pipes.withIndex().firstNotNullOfOrNull { (x, pipe) ->
if (pipe == `▉`) Coordinate(x, y) else null
}
}
@Suppress("EnumEntryName", "NonAsciiCharacters")
private enum class Pipe(val replacement: Char, val bold: Char, val top: Boolean, val right: Boolean, val bottom: Boolean, val left: Boolean) {
`│`('|', '║', top = true, right = false, bottom = true, left = false),
`─`('-', '═', top = false, right = true, bottom = false, left = true),
`└`('L', '╚', top = true, right = true, bottom = false, left = false),
`┘`('J', '╝', top = true, right = false, bottom = false, left = true),
`┐`('7', '╗', top = false, right = false, bottom = true, left = true),
`┌`('F', '╔', top = false, right = true, bottom = true, left = false),
` `('.', ' ', top = false, right = false, bottom = false, left = false),
`▉`('S', '▉', top = true, right = true, bottom = true, left = true),
;
companion object {
fun from(char: Char) = Pipe.entries.first { char == it.replacement }
}
}
data class Coordinate(val x: Int, val y: Int)
private fun Coordinate.filter(predicate: (Pipe) -> Boolean) = takeIf { map.getOrNull(y)?.getOrNull(x)?.let(predicate) ?: false }
private fun Coordinate.filter(
path: Set<Coordinate>,
from: (Pipe) -> Boolean,
to: (Pipe) -> Boolean,
transform: (Coordinate) -> Coordinate,
) = filter(from)?.let(transform)?.takeIf { it !in path }?.filter(to)
private fun Coordinate.next(path: Set<Coordinate>): Coordinate? {
filter(path, from = Pipe::top, to = Pipe::bottom) { copy(y = y - 1) }?.let { return it }
filter(path, from = Pipe::right, to = Pipe::left) { copy(x = x + 1) }?.let { return it }
filter(path, from = Pipe::bottom, to = Pipe::top) { copy(y = y + 1) }?.let { return it }
filter(path, from = Pipe::left, to = Pipe::right) { copy(x = x - 1) }?.let { return it }
return null
}
fun part1() = buildSet<Coordinate> {
add(start)
do {
this += last().next(this) ?: break
} while (first() != last())
}.also(::printMap).size / 2
fun part2(): Int = TODO()
private fun printMap(path: Set<Coordinate> = emptySet()) = map.withIndex().forEach { (y, pipes) ->
pipes.withIndex().joinToString("") { (x, pipe) ->
if (Coordinate(x, y) in path) pipe.bold.toString() else pipe.name
}.let(::println)
}
}
| 0 | Kotlin | 0 | 1 | 043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e | 2,804 | advent-of-code-2023 | MIT License |
src/main/kotlin/uk/co/baconi/playground/countdown/calculateSolution.kt | beercan1989 | 482,206,407 | false | {"Kotlin": 8623} | package uk.co.baconi.playground.countdown
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import org.slf4j.LoggerFactory
import kotlin.math.abs
enum class Operation(val perform: (Int, Int) -> Int, private val description: String) {
Add(Int::plus, "+"),
Minus(Int::minus, "-"),
Times(Int::times, "*"),
Divide(Int::div, "/");
override fun toString() = description
}
data class Method(val result: Lazy<Int>, val numbers: List<Int>, private val description: String) {
constructor(number: Int) : this(lazyOf(number), listOf(number), "$number")
constructor(left: Method, operation: Operation, right: Int) : this(
lazy { operation.perform(left.result.value, right) },
left.numbers + right,
"($left $operation $right)"
)
override fun toString() = description
}
data class Solution(val distance: Int, val method: Method)
fun Method.hasNoOverUseOf(available: List<Int>): Boolean {
return available.groupBy { n ->
n
}.map { (key, value) ->
numbers.count { number -> key == number } <= value.size
}.reduce { left, right ->
if (!right) { false } else { left }
}
}
suspend fun CoroutineScope.calculateSolution(picked: List<Int>, target: Int, solution: Channel<Solution?>, isPlayerAnAss: Boolean) {
var bestSolution: Solution? = null
val operations = Operation.values().asSequence()
val numbers = picked.asSequence()
// TODO - Protect against negative results
// TODO - Protect against fractional results
val numberCombinations: Sequence<Method> = sequence {
// 6^2
for (first in numbers.map(::Method)) {
yield(first)
// 6^2
for (operation1 in operations) {
for (second in numbers.map { Method(first, operation1, it) }.filter { m -> m.hasNoOverUseOf(picked) }) {
yield(second)
// 6^3
for (operation2 in operations) {
for (third in numbers.map { Method(second, operation2, it) }.filter { m -> m.hasNoOverUseOf(picked) }) {
yield(third)
// 6^4
for (operation3 in operations) {
for (fourth in numbers.map { Method(third, operation3, it) }.filter { m -> m.hasNoOverUseOf(picked) }) {
yield(fourth)
// 6^5
for (operation4 in operations) {
for (fifth in numbers.map { Method(fourth, operation4, it) }.filter { m -> m.hasNoOverUseOf(picked) }) {
yield(fifth)
// 6^6
for (operation5 in operations) {
for (sixth in numbers.map { Method(fifth, operation5, it) }.filter { m -> m.hasNoOverUseOf(picked) }) {
yield(sixth)
}
}
}
}
}
}
}
}
}
}
}
}
// Perform solution calculations
for (attempt: Method in numberCombinations) {
when {
!isActive -> break
bestSolution?.distance == 0 -> break
bestSolution == null -> {
val distance = abs(target - attempt.result.value)
if (distance <= 10) {
bestSolution = Solution(distance, attempt)
}
}
else -> {
val distance = abs(target - attempt.result.value)
if (distance < bestSolution.distance) {
bestSolution = Solution(distance, attempt)
}
}
}
}
if(isPlayerAnAss) {
val logger = LoggerFactory.getLogger("Countdown")
if (isActive && bestSolution == null) {
logger.info("I GIVE UP!!!!!")
} else {
logger.info("Eureka!")
}
}
solution.send(bestSolution)
}
fun checkNotNegative(value: Int): Int {
if (value < 0) throw IllegalStateException("Required value to be not negative.")
return value
}
fun checkNoRemainder(left: Int, right: Int): Int {
if (left % right != 0) throw IllegalStateException("Required remainder to be zero.")
return left / right
} | 0 | Kotlin | 0 | 0 | 5e8feb7e2b39e40a2f7ea3ff0861f7557831d7b8 | 4,704 | playground-countdown-calculator | Apache License 2.0 |
src/Day01.kt | jpereyrol | 573,074,843 | false | {"Kotlin": 9016} | fun List<String>.getCaloriesPerElfAsList(): List<Int> {
var currentSum = 0
val caloriesPerElf: MutableList<Int> = mutableListOf()
for (line in this) {
if (line == "") {
caloriesPerElf.add(currentSum)
currentSum = 0
} else {
currentSum += line.toInt()
}
}
caloriesPerElf.add(currentSum)
return caloriesPerElf.toList()
}
fun main() {
fun part1(input: List<String>): Int {
val caloriesPerElf = input.getCaloriesPerElfAsList()
return caloriesPerElf.max()
}
fun part2(input: List<String>): Int {
val caloriesPerElf = input.getCaloriesPerElfAsList()
return caloriesPerElf
.asSequence()
.sortedDescending()
.take(3)
.sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e17165afe973392a0cbbac227eb31d215bc8e07c | 894 | advent-of-code | Apache License 2.0 |
src/main/kotlin/_2020/Day11.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2020
import aocRun
fun main() {
aocRun(puzzleInput) { input ->
return@aocRun runSeatModel(
parseSeatLayout(input),
{ seating, x, y -> hasNoAdjacentOccupiedSeats(seating, x, y) },
{ seating, x, y -> has4OrMoreAdjacentOccupiedSeats(seating, x, y) }
)
}
aocRun(puzzleInput) { input ->
return@aocRun runSeatModel(
parseSeatLayout(input),
{ seating, x, y -> hasNoOccupiedSeatInSight(seating, x, y) },
{ seating, x, y -> has5OrMoreOccupiedSeatsInSight(seating, x, y) }
)
}
}
private fun parseSeatLayout(input: String): List<List<Seat>> =
input.split("\n").map { row -> row.toCharArray().map { Seat.getForChar(it) } }
private fun printSeatLayout(seating: List<List<Seat>>) = seating.forEach { row ->
row.forEach { print(it.character) }
println()
}
private fun runSeatModel(
initialSeating: List<List<Seat>>,
shouldEmptyBeOccupied: (seating: List<List<Seat>>, x: Int, y: Int) -> Boolean,
shouldOccupiedBeEmpty: (seating: List<List<Seat>>, x: Int, y: Int) -> Boolean
): Int {
// printSeatLayout(initialSeating)
var seating = initialSeating
var lastSeating: List<List<Seat>>
var round = 0
do {
lastSeating = seating
seating = runSeatModelRound(seating, shouldEmptyBeOccupied, shouldOccupiedBeEmpty)
round++
// println("----- Round $round -----")
// printSeatLayout(seating)
} while (seating != lastSeating)
return seating.sumBy { row -> row.sumBy { if (it == Seat.OCCUPIED) 1 else 0 } }
}
private fun runSeatModelRound(
seating: List<List<Seat>>,
shouldEmptyBeOccupied: (seating: List<List<Seat>>, x: Int, y: Int) -> Boolean,
shouldOccupiedBeEmpty: (seating: List<List<Seat>>, x: Int, y: Int) -> Boolean
): List<List<Seat>> {
// Create deep copy of the seating
val newSeating = mutableListOf<MutableList<Seat>>().apply { seating.forEach { add(it.toMutableList()) } }
// Run the seat model once for every position
seating.forEachIndexed { y, row ->
row.forEachIndexed { x, seat ->
when (seat) {
Seat.FLOOR -> Unit
Seat.EMPTY -> if (shouldEmptyBeOccupied(seating, x, y))
newSeating[y][x] = Seat.OCCUPIED
else
Unit
Seat.OCCUPIED -> if (shouldOccupiedBeEmpty(seating, x, y))
newSeating[y][x] = Seat.EMPTY
else
Unit
}
}
}
return newSeating
}
private inline fun <T> List<List<T>>.forEachAround(
x: Int,
y: Int,
consumer: (value: T, vecX: Int, vecY: Int) -> Unit
) {
for (vecY in -1..1) {
val checkY = y + vecY
if (checkY < 0 || checkY > this.size - 1)
continue
val row = this[checkY]
for (vecX in -1..1) {
val checkX = x + vecX
if (checkX < 0 || checkX > row.size - 1)
continue
if (checkY != y || checkX != x)
consumer(row[checkX], vecX, vecY)
}
}
}
private inline fun <T> List<List<T>>.forEachInLineUntil(
xStart: Int,
yStart: Int,
vecX: Int,
vecY: Int,
function: (value: T) -> Unit
) {
val maxX = this[0].size - 1
val maxY = this.size - 1
var x = xStart
var y = yStart
while (true) {
x += vecX
y += vecY
if (x < 0 || x > maxX || y < 0 || y > maxY)
return
function(this[y][x])
}
}
private fun hasNoAdjacentOccupiedSeats(seating: List<List<Seat>>, x: Int, y: Int): Boolean {
// println("hasNoAdjacentOccupiedSeats -> x: $x, y: $y")
seating.forEachAround(x, y) { seat, _, _ ->
if (seat == Seat.OCCUPIED)
return false
}
return true
}
private fun hasNoOccupiedSeatInSight(seating: List<List<Seat>>, x: Int, y: Int): Boolean {
seating.forEachAround(x, y) { _, vecX: Int, vecY: Int ->
seating.forEachInLineUntil(x, y, vecX, vecY) { seat ->
when (seat) {
Seat.FLOOR -> Unit
Seat.EMPTY -> return@forEachAround
Seat.OCCUPIED -> return false
}
}
}
return true
}
private fun has4OrMoreAdjacentOccupiedSeats(seating: List<List<Seat>>, x: Int, y: Int): Boolean {
// println("has4OrMoreAdjacentOccupiedSeats -> x: $x, y: $y")
var count = 0
seating.forEachAround(x, y) { seat, vecX, vecY ->
if (seat == Seat.OCCUPIED)
count++
if (count >= 4)
return true
}
return false
}
private fun has5OrMoreOccupiedSeatsInSight(seating: List<List<Seat>>, x: Int, y: Int): Boolean {
var count = 0
seating.forEachAround(x, y) { _, vecX, vecY ->
seating.forEachInLineUntil(x, y, vecX, vecY) { seat ->
when (seat) {
Seat.FLOOR -> Unit
Seat.EMPTY -> return@forEachAround
Seat.OCCUPIED -> {
count++
if (count >= 5)
return true
return@forEachAround
}
}
}
}
return false
}
private enum class Seat(val character: Char) {
FLOOR('.'),
EMPTY('L'),
OCCUPIED('#');
companion object {
private val map = mutableMapOf<Char, Seat>().apply {
values().forEach { put(it.character, it) }
}.toMap()
fun getForChar(char: Char): Seat = map[char]!!
}
}
private val testInput = """
L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
""".trimIndent()
private val puzzleInput = """
LLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLLLLLLLLLLLLLL.LLLLL.LLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLLLLL
LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLL.LLLL.LLLLLL
LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
L.L...L...LL.LL.......LL...LL.L...LL..LL..L.......LLLLL.....LL..LLLL.L....L..L...L.LL....LL...L
LLLLL.LLLLL.LLLLLLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLL.LL.LLLLLLLLL.LLLL.LLLL.LLLLLLLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LL.LLLLLLLLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLL.LLLLLL
LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLL.LLL.LL.LLLLLLLLL.LLLL.LLLL.LLLL.L.LLLL
LLLLL.LLLL.LLLL.LLL.LLLLLLLLLLLLLLLLLLLL.LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLL.LLLL.LLLL.LLLLLLLLLLL
LLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLL.LLLL.LLL.LL.LLLLLLLLLLLLLLLLLLL.LLLL.LLLLLL
.L.....L.LL..LLL.L..L...L.LLL.L...L.L.L.L.....L..L.......L.LLL...L.......L.LLLL......L.L.L...LL
LLLLLLLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLL..LLLLLL.LLLL.LLLL.L.LL.LLLLLLLLL.LLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLL
LLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LL.LLLLLLLLLLLLL.LLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLLL.LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
.L..LLL.L...LL.....LL......LL...L...LL...L.L..L....L.L.L.LL.L........L....LL......L..LL..LL....
LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLL
LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL
LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLL.LLLLL.LLL..LLLL.LLLLLL.LLLLLLLLLLL.LL.LLLL.LLLLLLLLLLL
LLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL..L.LLL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLLLLL.LLLLLLLLLL.LLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLLLLLLL.LLLL.LLLLLLLLLLL
L.LLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLLLLL
LLLL....L.......L..LLL...........L..L...LL..L.L.LLL...L.....LL..LL..L....L....L..LL..LL.L....L.
LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.L.LLLLLLLLLLLL.LLLLLL
LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLL
LLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLLL.LLLLLLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLL..LLL.LLLL.LLLL.LLLL.LLLLLLLLLLL
LLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLL.L.LLLL.LL.L.LL.LLLLLLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
.LL........L.....L.L.L.......LL.L.L.......LLL.........L....LL........L.L..L......L.LL......L..L
LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLLLLLLL.L.LLLLLLLLLLLLLL
LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLL.LLLLLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLLLLL
LLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.L.LLLL.LLLLLL.LLLLLLLLL.LLLL.LLLLLLLLL.LLLLLL
LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLL..LLLLLL.LLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLL.LL.L.LLLLLLLLLLLLLLLL.LLLL.LLLLLLLLL.LLLLLL
.L..L...L........L.......L.L.LL.LLLL...LLL.L.L..L.L....L.................L.L.L.L....L...L...L..
LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL.LLLL
LLLLL.LL.LLLLLLL.LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLLLLLLL.LLLLLL
LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLL...LLL.......LL..L.L.L.L...L........LL..............L.L......L.......L..LL....L....LL...LL.
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLL.LLLLLL.L.LLLLLLL.LLLLLLLLL.LLLLLLLLLLL
LLLLL.LLLL.LLLL.LLLLLL..LLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.L.LLLL.LLLLLL
LLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLLL.LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLLL.LLLLL.LLLL.L.LL.LLLLLL.LLLLLLLLLLL.LL.LLLLLLLLL.LLL.LL
LLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LL.LL.LLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL
LLLL.L...LL.......LL..L.....L.LL..L....L.L..L.......L..L......LLLLL..L.L..L......L...L.L...L.L.
LLLLL.LLL..LLLL.LLLLLL.LLLLL.LLL.LLLLL.L.LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLLLLL.LLLLLLLL..LLLLLL
LLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLL
LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLL.LLLL.LLLLLLLLLLLL.LLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
L.L...............L..L.LLLL...L..L...LLL.......LLL.LL........L..LL..L..L...L.L.L.LL..LLLL.L.LL.
LLLLLLLL.L.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLLLLLLL.LLLLLL
LLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLL.LLLLLLLLLLL
LLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLL.LLLL.LLLLLLLLLLL
LLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLLL
LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLLL
L.LLL.LLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLL.LLLLLLL.LLLL.LLLL.LLLLLL
.L..LL.L.L..L...L....L......LLL......L.LL..L....L.LLLL.LL.....L.L.LL.L.....L......L.LL.........
LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLL.LLLL..LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLL.LLLLLLLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLL
LLLLL.LLL..LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLL..LLL.LLLLLLLLLLLLLLLL
.LLL......L.L.L......L.....LL......L.LLL.LLL..LL...L.L.......L..L.......L....L.....L.......LL..
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLLLLLLL.LLLLLL
LLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLLL.LLLLLL
LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LL...L...........L...L..L......LL...........L...L.LL..LL....L....LLL.LLLL....LLL...LL..L..L...L
LLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLL.LLLL.LLLL.LLLLLLLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLL.LLLLLLLLLLLLL.LLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLLLLLLL
.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLL
LLLLL.LL.LLLLLLLLLLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLL.LLLLLLLLLLL.LLLLLLLL..LLLL.LLL..LLLLLLLLLLL
.......L...LL.L.....L.L.....LLL.L.......L.....LL.......L..LLL.....L.LL.L..........LL...........
LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLLLL.LL.LL.LLL.LLLLLLLLLLLLLL.LLLL.LLLLLLLLLLL
LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLLL.LLLLLLLLLL.LLLL.LLLLLL.LLLLLLLL..LLLLLLLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLL.LLLL.LLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLL.LLLL.LLLL.LLLL.LLLLLL
LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL
""".trimIndent()
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 14,299 | AdventOfCode | Creative Commons Zero v1.0 Universal |
AtCoder/abc204/C.kt | thedevelopersanjeev | 112,687,950 | false | null | private fun readLn() = readLine()!!
private fun readLns() = readLn().split(" ")
private fun readInt() = readLn().toInt()
private fun readInts() = readLns().map { it.toInt() }
fun main() {
val (n, m) = readInts()
val adj = ArrayList<ArrayList<Int>>()
for (i in 0 until n) adj.add(ArrayList())
for (i in 0 until m) {
val (u, v) = readInts()
adj[u - 1].add(v - 1)
}
var ans = 0
for (u in 0 until n) {
val visited = BooleanArray(n)
ans += dfs(adj, visited, u)
}
print(ans)
}
private fun dfs(adj: ArrayList<ArrayList<Int>>, visited: BooleanArray, u: Int): Int {
if (visited[u]) return 0
visited[u] = true
var ans = 1
for (v in adj[u]) {
ans += dfs(adj, visited, v)
}
return ans
}
| 0 | C++ | 58 | 146 | 610520cc396fb13a03c606b5fb6739cfd68cc444 | 807 | Competitive-Programming | MIT License |
src/main/java/com/ncorti/aoc2021/Exercise02.kt | cortinico | 433,486,684 | false | {"Kotlin": 36975} | package com.ncorti.aoc2021
object Exercise02 {
fun part1(): Int =
getInputAsTest("02") { split("\n") }
.map { it.split(" ") }
.map { it[0] to it[1].toInt() }
.fold(0 to 0) { (depth, horizontal), (move, unit) ->
when (move) {
"forward" -> depth to horizontal + unit
"up" -> depth - unit to horizontal
else -> depth + unit to horizontal
}
}
.let { (depth, horizontal) -> depth * horizontal }
fun part2(): Int =
getInputAsTest("02") { split("\n") }
.map { it.split(" ") }
.map { it[0] to it[1].toInt() }
.fold(Triple(0, 0, 0)) { (depth, horizontal, aim), (move, unit) ->
when (move) {
"forward" -> Triple(depth + (aim * unit), horizontal + unit, aim)
"up" -> Triple(depth, horizontal, aim - unit)
else -> Triple(depth, horizontal, aim + unit)
}
}
.let { (depth, horizontal) -> depth * horizontal }
}
fun main() {
println(Exercise02.part1())
println(Exercise02.part2())
}
| 0 | Kotlin | 0 | 4 | af3df72d31b74857201c85f923a96f563c450996 | 1,208 | adventofcode-2021 | MIT License |
src/main/kotlin/leetcode/Problem1482.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
import kotlin.math.max
import kotlin.math.min
/**
* https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/
*/
class Problem1482 {
fun minDays(bloomDay: IntArray, m: Int, k: Int): Int {
if (bloomDay.size < m * k) {
return -1
}
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
for (day in bloomDay) {
min = min(min, day)
max = max(max, day)
}
while (min <= max) {
val mid = min + ((max - min) / 2)
if (isValid(bloomDay, m, k, mid)) {
max = mid - 1
} else {
min = mid + 1
}
}
return min
}
private fun isValid(bloomDay: IntArray, m: Int, k: Int, day: Int): Boolean {
var bouquets = 0
var flowers = 0
for (d in bloomDay) {
if (d > day) {
flowers = 0
} else {
flowers++
}
if (flowers == k) {
flowers = 0
bouquets++
}
if (bouquets == m) {
return true
}
}
return false
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 1,212 | leetcode | MIT License |
generator/src/main/kotlin/com/kylemayes/generator/generate/file/Bitmasks.kt | KyleMayes | 305,287,877 | false | {"Rust": 6654307, "Kotlin": 153555, "GLSL": 3759, "Python": 2709, "Shell": 1142, "Makefile": 800, "PowerShell": 721} | // SPDX-License-Identifier: Apache-2.0
package com.kylemayes.generator.generate.file
import com.kylemayes.generator.generate.support.generateAliases
import com.kylemayes.generator.generate.support.generateManualUrl
import com.kylemayes.generator.registry.Bitflag
import com.kylemayes.generator.registry.Bitmask
import com.kylemayes.generator.registry.Registry
import java.math.BigInteger
/** Generates Rust `bitflags!` structs for Vulkan bitmasks. */
fun Registry.generateBitmasks() =
"""
use bitflags::bitflags;
use crate::{Flags, Flags64};
${bitmasks.values
.sortedBy { it.name }
.joinToString("\n") { generateBitmask(it) }}
${generateAliases(bitmasks.keys)}
"""
/** Generates a Rust `bitflags!` struct for a Vulkan bitmask. */
private fun Registry.generateBitmask(bitmask: Bitmask): String {
val long = bitmask.bitflags.any { it.value.bitLength() > 32 }
val repr = "Flags" + (if (long) { "64" } else { "" })
val values = bitmask.bitflags.associateBy { it.value }
val flags = generateBitflags(values, bitmask.bitflags).joinToString("\n ")
val block = if (flags.isNotBlank()) {
"{\n $flags\n }"
} else {
"{ }"
}
return """
bitflags! {
/// <${generateManualUrl(bitmask)}>
#[repr(transparent)]
#[derive(Default)]
pub struct ${bitmask.name}: $repr $block
}
"""
}
/** Generates Rust `bitflags!` bitflags for a list of Vulkan bitflags. */
private fun generateBitflags(values: Map<BigInteger, Bitflag>, bitflags: List<Bitflag>) =
if (bitflags.isNotEmpty()) {
bitflags
.sortedBy { it.value }
.map { "const ${it.name} = ${generateExpr(values, it.value)};" }
} else {
emptyList()
}
/** Generates a Rust expression for a Vulkan bitflag value. */
private fun generateExpr(values: Map<BigInteger, Bitflag>, value: BigInteger): String {
val bits = (0..value.bitLength())
.map { it to value.testBit(it) }
.filter { it.second }
.map { it.first }
return if (bits.isEmpty()) {
"0"
} else if (bits.size == 1) {
val bit = bits[0]
if (bit == 0) { "1" } else { "1 << $bit" }
} else if (bits.size == 31) {
return "i32::MAX as u32"
} else {
return bits
.map { values[BigInteger.valueOf(1L.shl(it))]!!.name }
.joinToString(" | ") { "Self::$it.bits" }
}
}
| 12 | Rust | 29 | 216 | c120c156dc5a6ebcfd8870d8688001f4accfb373 | 2,417 | vulkanalia | Apache License 2.0 |
src/main/kotlin/day18/Day18.kt | Jessevanbekkum | 112,612,571 | false | null | package day18
import util.readLines
class Day18 {
val snd = Regex("snd (\\w)")
val set = Regex("set (\\w) ([\\w-]*)")
val add = Regex("add (\\w) ([\\w-]*)")
val mul = Regex("mul (\\w) ([\\w-]*)")
val mod = Regex("mod (\\w) ([\\w-]*)")
val rcv = Regex("rcv (\\w)")
val jgz = Regex("jgz (\\w) ([\\w-]*)")
val reg = mutableMapOf<String, Long>()
val regex = listOf<Regex>(snd, set, add, mul, mod, rcv, jgz)
init {
"abcdefghijklmnopqrstuvwxyz".forEach { it -> reg.put(it.toString(), 0) }
}
fun day18_1(input: String): Long {
val code = readLines(input)
var lf :Long= 0
var pos = 0;
while (pos in (0..code.size)) {
val s = code[pos]
val caps = regex.map { r -> r.matchEntire(s) }.filterNotNull().first().groupValues
when (caps[0].subSequence(0, 3)) {
"snd" -> lf = read(caps[1])
"set" -> reg[caps[1]] = read(caps[2])
"rcv" -> if (lf != 0L) return lf;
"mul" -> reg[caps[1]] = reg[caps[1]]!! * read(caps[2])
"mod" -> reg[caps[1]] = reg[caps[1]]!! % read(caps[2])
"add" -> reg[caps[1]] = reg[caps[1]]!! + read(caps[2])
"jgz" -> if (reg[caps[1]]!! > 0) pos += read(caps[2]).toInt() - 1 else {}
}
pos++
}
return -666
}
fun read(s: String): Long {
return s.toLongOrNull() ?: reg[s]!!
}
}
| 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 1,481 | aoc-2017 | Apache License 2.0 |
src/main/kotlin/g2001_2100/s2065_maximum_path_quality_of_a_graph/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2065_maximum_path_quality_of_a_graph
// #Hard #Array #Graph #Backtracking #2023_06_26_Time_429_ms_(100.00%)_Space_46.7_MB_(100.00%)
class Solution {
private var maxQuality = 0
internal class Node(var i: Int, var time: Int)
fun maximalPathQuality(values: IntArray, edges: Array<IntArray>, maxTime: Int): Int {
val graph: MutableList<MutableList<Node>> = ArrayList()
for (i in values.indices) {
graph.add(ArrayList())
}
for (edge in edges) {
val u = edge[0]
val v = edge[1]
val time = edge[2]
val node1 = Node(u, time)
val node2 = Node(v, time)
graph[u].add(node2)
graph[v].add(node1)
}
maxQuality = 0
dfs(graph, 0, 0, maxTime, values[0], values)
return maxQuality
}
private fun dfs(
graph: List<MutableList<Node>>,
start: Int,
curTime: Int,
maxTime: Int,
curValue: Int,
values: IntArray
) {
if (curTime > maxTime) {
return
}
if (curTime == maxTime && start != 0) {
return
}
if (start == 0) {
maxQuality = maxQuality.coerceAtLeast(curValue)
}
val tmp = values[start]
if (tmp != 0) {
values[start] = 0
}
for (node in graph[start]) {
val v = node.i
val time = node.time
val value = values[v]
if (value != 0) {
values[v] = 0
}
dfs(graph, v, curTime + time, maxTime, curValue + value, values)
if (value != 0) {
values[v] = value
}
}
if (tmp != 0) {
values[start] = tmp
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,822 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/leetcode/kotlin/array/easy/122. Best Time to Buy and Sell Stock II.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.array.easy
fun main() {
println(maxProfit(intArrayOf(7, 1, 5, 3, 6, 4)))
println(maxProfit(intArrayOf(1, 2, 3, 4, 5)))
println(maxProfit(intArrayOf(7, 6, 4, 3, 1)))
println(maxProfit2(intArrayOf(7, 1, 5, 3, 6, 4)))
println(maxProfit2(intArrayOf(1, 2, 3, 4, 5)))
println(maxProfit2(intArrayOf(7, 6, 4, 3, 1)))
println(maxProfit3(intArrayOf(7, 1, 5, 3, 6, 4)))
println(maxProfit3(intArrayOf(1, 2, 3, 4, 5)))
println(maxProfit3(intArrayOf(7, 6, 4, 3, 1)))
}
private fun maxProfit(prices: IntArray): Int {
var buyprice = -1
var profit = 0
for (i in 0 until prices.size) {
// buy condition
if (buyprice == -1 && i != prices.lastIndex && prices[i + 1] > prices[i]) {
buyprice = prices[i]
}
// sell condition
if (buyprice != -1 && i != prices.lastIndex && prices[i + 1] < prices[i]) {
profit += prices[i] - buyprice
buyprice = -1
}
}
if (buyprice != -1) {
profit += prices[prices.lastIndex] - buyprice
}
return profit
}
/**
* Consider each greater element compared to previous as new peak compared previous
* and keep accumulating delta profit.
*/
private fun maxProfit2(prices: IntArray): Int {
var ans = 0
for (i in 1 until prices.size) {
if (prices[i] > prices[i - 1]) {
ans += prices[i] - prices[i - 1]
}
}
return ans
}
/**
* Traverse from left to right, find every peak followed by valley, and
* book profit. Keep accumulating the profit and return it.
*/
private fun maxProfit3(prices: IntArray): Int {
var valley = 0
var peak = 0
var profit = 0
var i = 0
while (i < prices.size - 1) {
// going down till we find a valley
while (i < prices.size - 1 && prices[i + 1] <= prices[i]) i++
valley = prices[i]
// going up till we find a peak
while (i < prices.size - 1 && prices[i + 1] >= prices[i]) i++
peak = prices[i]
// time to book profit
profit += peak - valley
}
return profit
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 2,108 | kotlinmaster | Apache License 2.0 |
src/2022/Day22.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
import splitBy
fun main() {
fun part1(input: List<String>): Int {
val (map, directionsLines) = input.splitBy { it.isEmpty() }
val directions = "\\d+|R|L".toRegex().findAll(directionsLines.first()).map { it.value }.toList()
var positionColumn = map.first().indexOfFirst { it == '.' }
var positionRow = 0
var degree = 0
directions.forEach {
when(it) {
"R" -> degree = if (degree + 90 > 180) degree - 270 else degree + 90
"L" -> degree = if (degree - 90 <= -180) degree + 270 else degree - 90
else -> {
val steps = it.toInt()
when(degree) {
0 -> {
repeat(steps) {
val row = map[positionRow]
var nextPosition = positionColumn + 1
if (nextPosition >= row.length || row[nextPosition] == ' ') {
nextPosition = row.indexOfFirst { char -> char != ' ' }
}
if (row[nextPosition] == '#') return@repeat
positionColumn = nextPosition
}
}
90 -> {
repeat(steps) {
var nextPosition = positionRow + 1
if (nextPosition >= map.size || positionColumn >= map[nextPosition].length || map[nextPosition][positionColumn] == ' ') {
nextPosition = map.indexOfFirst { row -> positionColumn < row.length && row[positionColumn] != ' ' }
}
if (map[nextPosition][positionColumn] == '#') return@repeat
positionRow = nextPosition
}
}
-90 -> {
repeat(steps) {
var nextPosition = positionRow - 1
if (nextPosition < 0 || positionColumn >= map[nextPosition].length || map[nextPosition][positionColumn] == ' ') {
nextPosition = map.indexOfLast { row -> positionColumn < row.length && row[positionColumn] != ' ' }
}
if (map[nextPosition][positionColumn] == '#') return@repeat
positionRow = nextPosition
}
}
180 -> {
repeat(steps) {
val row = map[positionRow]
var nextPosition = positionColumn - 1
if (nextPosition < 0 || row[nextPosition] == ' ') {
nextPosition = row.indexOfLast { char -> char != ' ' }
}
if (row[nextPosition] == '#') return@repeat
positionColumn = nextPosition
}
}
else -> error("illegal state")
}
}
}
}
val facing = when(degree) {
0 -> 0
90 -> 1
180 -> 2
-90 -> 3
else -> error("illegal")
}
return (positionRow + 1) * 1000 + 4 * (positionColumn + 1) + facing
}
fun nextPosition(map: List<String>, positionRow: Int, positionColumn: Int, degree: Int): Triple<Int, Int, Int> {
return when (degree) {
0 -> {
var nextPositionRow = positionRow
var nextPositionColumn = positionColumn + 1
var nextDegree = degree
if (nextPositionColumn >= map[nextPositionRow].length || map[nextPositionRow][nextPositionColumn] == ' ') {
if (positionRow in 0 until 50) {
nextDegree = 180
nextPositionColumn = 99
nextPositionRow = 150 - positionRow
}
if (positionRow in 50 until 100) {
nextDegree = -90
nextPositionColumn = positionRow + 50
nextPositionRow = 49
}
if (positionRow in 100 until 150) {
nextDegree = 180
nextPositionColumn = 149
nextPositionRow = 150 - positionRow
}
if (positionRow in 150 until 200) {
check(nextPositionColumn == 50)
nextDegree = -90
nextPositionColumn = positionRow - 100
nextPositionRow = 149
}
}
if (map[nextPositionRow][nextPositionColumn] == '#') {
Triple(positionRow, positionColumn, degree)
} else {
Triple(nextPositionRow, nextPositionColumn, nextDegree)
}
}
90 -> {
var nextPositionRow = positionRow + 1
var nextPositionColumn = positionColumn
var nextDegree = degree
if (nextPositionRow >= map.size || positionColumn >= map[nextPositionRow].length || map[nextPositionRow][nextPositionColumn] == ' ') {
if (positionColumn in 0 until 50) {
check(nextPositionRow == 200)
nextDegree = 90
nextPositionColumn = positionColumn + 100
nextPositionRow = 0
}
if (positionColumn in 50 until 100) {
check(nextPositionRow == 150)
nextDegree = 180
nextPositionColumn = 49
nextPositionRow = positionColumn + 100
}
if (positionColumn in 100 until 150) {
check(nextPositionRow == 50)
nextDegree = 180
nextPositionColumn = 99
nextPositionRow = positionColumn - 50
}
}
if (map[nextPositionRow][nextPositionColumn] == '#') {
Triple(positionRow, positionColumn, degree)
} else {
Triple(nextPositionRow, nextPositionColumn, nextDegree)
}
}
-90 -> {
var nextPositionRow = positionRow - 1
var nextPositionColumn = positionColumn
var nextDegree = degree
if (nextPositionRow < 0 || map[nextPositionRow][nextPositionColumn] == ' ') {
if (positionColumn in 0 until 50) {
check(positionRow == 100)
nextDegree = 0
nextPositionColumn = 50
nextPositionRow = positionColumn + 50
}
if (positionColumn in 50 until 100) {
check(positionRow == 0)
nextDegree = 0
nextPositionColumn = 0
nextPositionRow = positionColumn + 99
}
if (positionColumn in 100 until 150) {
check(positionRow == 0)
nextDegree = -90
nextPositionColumn = positionColumn - 100
nextPositionRow = 199
}
}
if (map[nextPositionRow][nextPositionColumn] == '#') {
Triple(positionRow, positionColumn, degree)
} else {
Triple(nextPositionRow, nextPositionColumn, nextDegree)
}
}
180 -> {
var nextPositionRow = positionRow
var nextPositionColumn = positionColumn - 1
var nextDegree = degree
if (nextPositionColumn < 0 || map[nextPositionRow][nextPositionColumn] == ' ') {
if (positionRow in 0 until 50) {
nextDegree = 0
nextPositionColumn = 0
nextPositionRow = 150 - positionRow
}
if (positionRow in 50 until 100) {
nextDegree = 90
nextPositionColumn = nextPositionRow - 50
nextPositionRow = 100
}
if (positionRow in 100 until 150) {
nextDegree = 0
nextPositionColumn = 50
nextPositionRow = 150 - positionRow
}
if (positionRow in 150 until 200) {
nextDegree = 90
nextPositionColumn = nextPositionRow - 100
nextPositionRow = 0
}
}
if (map[nextPositionRow][nextPositionColumn] == '#') {
Triple(positionRow, positionColumn, degree)
} else {
Triple(nextPositionRow, nextPositionColumn, nextDegree)
}
}
else -> error("illegal state")
}
}
fun part2(input: List<String>): Int {
val (map, directionsLines) = input.splitBy { it.isEmpty() }
val directions = "\\d+|R|L".toRegex().findAll(directionsLines.first()).map { it.value }.toList()
var positionRow = 0
var positionColumn = map.first().indexOfFirst { it == '.' }
var degree = 0
directions.forEach {
when(it) {
"R" -> degree = if (degree + 90 > 180) degree - 270 else degree + 90
"L" -> degree = if (degree - 90 <= -180) degree + 270 else degree - 90
else -> {
val steps = it.toInt()
repeat(steps) {
val (nextPositionRow, nextPositionColumn, nextDegree) = nextPosition(map, positionRow, positionColumn, degree)
positionRow = nextPositionRow
positionColumn = nextPositionColumn
degree = nextDegree
}
}
}
}
val facing = when(degree) {
0 -> 0
90 -> 1
180 -> 2
-90 -> 3
else -> error("illegal")
}
return (positionRow + 1) * 1000 + 4 * (positionColumn + 1) + facing
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day22_test")
println(part1(testInput))
//println(part2(testInput))
check(part1(testInput) == 6032)
//check(part2(testInput) == 5031)
val input = readInput("Day22")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 11,329 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Day11.kt | andrewrlee | 434,584,657 | false | {"Kotlin": 29493, "Clojure": 14117, "Shell": 398} | import java.io.File
import java.nio.charset.Charset.defaultCharset
import kotlin.streams.toList
typealias OctopusGrid = Map<Pair<Int, Int>, Day11.Octopus>
object Day11 {
private fun toCoordinates(row: Int, line: String) = line.chars()
.map(Character::getNumericValue)
.toList()
.mapIndexed { col, value -> (row to col) to Octopus((row to col), value) }
val octopusGrid = {
File("day11/input-Day11.kt.txt")
.readLines(defaultCharset())
.mapIndexed(::toCoordinates)
.flatten()
.associate { it }
}
data class Octopus(var coord: Pair<Int, Int>, var score: Int, var hasFlashed: Boolean = false) {
fun increment() = score++
private fun needsToFlash() = score > 9 && !hasFlashed
private fun flash() {
hasFlashed = true
}
fun reset() = if (hasFlashed) {
hasFlashed = false; score = 0; 1
} else 0
private fun getNeighbours(
validCells: OctopusGrid,
deltas: List<Pair<Int, Int>> = listOf(
-1 to 0, 0 to -1,
1 to 0, 0 to 1,
-1 to -1, 1 to 1,
-1 to 1, 1 to -1
)
) = deltas.asSequence()
.map { (x2, y2) -> coord.first + x2 to coord.second + y2 }
.mapNotNull { validCells[it] }
fun check(grid: OctopusGrid) {
if (this.needsToFlash()) {
this.flash()
this.getNeighbours(grid).forEach { it.increment(); it.check(grid) }
}
}
}
private fun OctopusGrid.step(): Int {
this.values.forEach { it.increment() }
this.values.forEach { oct -> oct.check(this) }
return this.values.sumOf { it.reset() }
}
object Part1 {
fun run() {
val grid = octopusGrid()
val count = (0..99).map { grid.step() }.sum()
println(count)
}
}
object Part2 {
private fun OctopusGrid.isNotComplete(): Boolean {
val flashCount = this.step()
return flashCount != this.size
}
fun run() {
val grid = octopusGrid()
var count = 0
do {
count++
} while (grid.isNotComplete())
println(count)
}
}
}
fun main() {
Day11.Part1.run()
Day11.Part2.run()
} | 0 | Kotlin | 0 | 0 | aace0fccf9bb739d57f781b0b79f2f3a5d9d038e | 2,424 | adventOfCode2021 | MIT License |
src/Day05.kt | cagriyildirimR | 572,811,424 | false | {"Kotlin": 34697} | import java.util.Stack
val input5 = readInput("Day05")
val crates = input5.take(8).reversed()
val instructions =input5.drop(10).map { i -> i.split("move", "from", "to", " ").filter { it != "" }.map { it.toInt() } }
fun day05Part2(){
val conveyor = Stack<String>()
val listOfPiles = List(9) { Stack<String>() }
// initialize piles
for (c in crates){
for (i in c.indices step 4) {
val o = c.slice(i..i+2)
if (o != " ")listOfPiles[i/4].push(o)
}
}
// move 4 from 9 to 1
for (i in instructions){
repeat(i[0]){
conveyor.push(listOfPiles[i[1]-1].pop())
}
repeat(i[0]){
listOfPiles[i[2]-1].push(conveyor.pop())
}
}
listOfPiles.forEach { it.peek().print() }
}
fun day05Part1(){
val listOfPiles = List(9) { Stack<String>() }
// initialize piles
for (c in crates){
for (i in c.indices step 4) {
val o = c.slice(i..i+2)
if (o != " ")listOfPiles[i/4].push(o)
}
}
// move 4 from 9 to 1
for (i in instructions){
repeat(i[0]){
listOfPiles[i[2]-1].push(listOfPiles[i[1]-1].pop())
}
}
listOfPiles.forEach { it.peek().print() }
}
| 0 | Kotlin | 0 | 0 | 343efa0fb8ee76b7b2530269bd986e6171d8bb68 | 1,261 | AoC | Apache License 2.0 |
src/Day23.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | fun main() {
var move = Array(4) { listOf<Pair<Int, Int>>() }
move[0] = listOf( Pair(-1, -1), Pair(-1, 0), Pair(-1, 1)) // up
move[1] = listOf( Pair(1, 1), Pair(1, 0), Pair(1, -1) ) // down
move[2] = listOf( Pair(1, -1), Pair(0, -1), Pair(-1, -1) ) // left
move[3] = listOf( Pair(-1, 1), Pair(0, 1), Pair(1, 1) ) // right
var dR = listOf<Int>(-1, -1, -1, 0, 0, 1, 1, 1)
var dC = listOf<Int>(-1, 0, 1, -1, 1, -1, 0, 1)
fun part1(input: List<String>): Int {
var elves = mutableSetOf<Pair<Int, Int>>()
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == '#') {
elves.add(Pair(i, j))
}
}
}
var moveChoice = 0
for (rounds in 1 .. 10) {
var newElves = mutableSetOf<Pair<Int, Int>>()
var positionCount = mutableMapOf<Pair<Int, Int>, Int>()
// get moves
for (elf in elves) {
var cantMove = true
for (k in 0 until 8) {
var next = Pair(elf.first + dR[k], elf.second + dC[k])
if (elves.contains(next)) {
cantMove = false
break
}
}
if (cantMove) continue
for (moveIdx in 0 until 4) {
val i = (moveChoice + moveIdx) % 4
var count = 0
for (j in 0 until 3) {
var pos = Pair(elf.first + move[i][j].first, elf.second + move[i][j].second)
if (elves.contains(pos)) {
count++
}
}
if (count > 0) continue
positionCount[Pair(elf.first + move[i][1].first, elf.second + move[i][1].second)] = positionCount.getOrDefault(Pair(elf.first + move[i][1].first, elf.second + move[i][1].second), 0) + 1
break
}
}
// apply moves
for (elf in elves) {
var moved = false
var cantMove = true
for (k in 0 until 8) {
var next = Pair(elf.first + dR[k], elf.second + dC[k])
if (elves.contains(next)) {
cantMove = false
break
}
}
if (!cantMove) {
for (moveIdx in 0 until 4) {
val i = (moveChoice + moveIdx) % 4
var count = 0
for (j in 0 until 3) {
var pos = Pair(elf.first + move[i][j].first, elf.second + move[i][j].second)
if (elves.contains(pos)) {
count++
}
}
if (count > 0) continue
if (positionCount.getOrDefault(Pair(elf.first + move[i][1].first, elf.second + move[i][1].second), 0) == 1) {
newElves.add(Pair(elf.first + move[i][1].first, elf.second + move[i][1].second))
moved = true
}
break
}
}
if (!moved) {
newElves.add(elf)
}
}
elves = newElves
moveChoice = (moveChoice + 1) % 4
}
var minRow = elves.minBy { it.first }!!.first
var maxRow = elves.maxBy { it.first }!!.first
var minCol = elves.minBy { it.second }!!.second
var maxCol = elves.maxBy { it.second }!!.second
return (maxRow - minRow + 1) * (maxCol - minCol + 1) - elves.size
}
fun part2(input: List<String>): Int {
var elves = mutableSetOf<Pair<Int, Int>>()
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == '#') {
elves.add(Pair(i, j))
}
}
}
var moveChoice = 0
var round = 0
var moved = true
while (moved) {
round++
moved = false
var newElves = mutableSetOf<Pair<Int, Int>>()
var positionCount = mutableMapOf<Pair<Int, Int>, Int>()
// get moves
for (elf in elves) {
var cantMove = true
for (k in 0 until 8) {
var next = Pair(elf.first + dR[k], elf.second + dC[k])
if (elves.contains(next)) {
cantMove = false
break
}
}
if (cantMove) continue
else moved = true
for (moveIdx in 0 until 4) {
val i = (moveChoice + moveIdx) % 4
var count = 0
for (j in 0 until 3) {
var pos = Pair(elf.first + move[i][j].first, elf.second + move[i][j].second)
if (elves.contains(pos)) {
count++
}
}
if (count > 0) continue
positionCount[Pair(elf.first + move[i][1].first, elf.second + move[i][1].second)] = positionCount.getOrDefault(Pair(elf.first + move[i][1].first, elf.second + move[i][1].second), 0) + 1
break
}
}
// apply moves
for (elf in elves) {
var moved = false
var cantMove = true
for (k in 0 until 8) {
var next = Pair(elf.first + dR[k], elf.second + dC[k])
if (elves.contains(next)) {
cantMove = false
break
}
}
if (!cantMove) {
for (moveIdx in 0 until 4) {
val i = (moveChoice + moveIdx) % 4
var count = 0
for (j in 0 until 3) {
var pos = Pair(elf.first + move[i][j].first, elf.second + move[i][j].second)
if (elves.contains(pos)) {
count++
}
}
if (count > 0) continue
if (positionCount.getOrDefault(Pair(elf.first + move[i][1].first, elf.second + move[i][1].second), 0) == 1) {
newElves.add(Pair(elf.first + move[i][1].first, elf.second + move[i][1].second))
moved = true
}
break
}
}
if (!moved) {
newElves.add(elf)
}
}
elves = newElves
moveChoice = (moveChoice + 1) % 4
}
return round
}
val input = readInput("Day23")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 7,202 | advent-of-code-2022-kotlin | Apache License 2.0 |
year2023/day03/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day03/part2/Year2023Day03Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
The engineer finds the missing part and installs it in the engine! As the engine springs to life,
you jump in the closest gondola, finally ready to ascend to the water source.
You don't seem to be going very fast, though. Maybe something is still wrong? Fortunately, the
gondola has a phone labeled "help", so you pick it up and the engineer answers.
Before you can explain the situation, she suggests that you look out the window. There stands the
engineer, holding a phone in one hand and waving with the other. You're going so slowly that you
haven't even left the station. You exit the gondola.
The missing part wasn't the only issue - one of the gears in the engine is wrong. A gear is any `*`
symbol that is adjacent to exactly two part numbers. Its gear ratio is the result of multiplying
those two numbers together.
This time, you need to find the gear ratio of every gear and add them all up so that the engineer
can figure out which gear needs to be replaced.
Consider the same engine schematic again:
```
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..
```
In this schematic, there are two gears. The first is in the top left; it has part numbers 467 and
35, so its gear ratio is 16345. The second gear is in the lower right; its gear ratio is 451490.
(The `*` adjacent to 617 is not a gear because it is only adjacent to one part number.) Adding up
all of the gear ratios produces 467835.
What is the sum of all of the gear ratios in your engine schematic?
*/
package com.curtislb.adventofcode.year2023.day03.part2
import com.curtislb.adventofcode.year2023.day03.engine.EngineSchematic
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2023, day 03, part 2.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
val schematic = EngineSchematic.fromFile(inputPath.toFile())
return schematic.sumGearRatios()
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,099 | AdventOfCode | MIT License |
src/main/kotlin/co/csadev/advent2021/Day02.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2021, Day 2
* Problem Description: http://adventofcode.com/2021/day/2
*/
package co.csadev.advent2021
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Resources.resourceAsList
class Day02(data: List<String> = resourceAsList("22day02.txt")) :
BaseDay<List<Day02.Directions>, Int, Int> {
class Directions(var x: Int = 0, var y: Int = 0, var aim: Int = 0) {
fun addAndAim(d: Directions): Directions {
x += d.x
y += if (d.x > 0) aim * d.x else 0
aim += d.y
return this
}
}
override val input: List<Directions> = data.map {
it.split(" ").run { this[0] to this[1].toInt() }
}.map {
when (it.first) {
"forward" -> Directions(it.second)
"down" -> Directions(y = it.second)
"up" -> Directions(y = it.second * -1)
else -> Directions()
}
}
override fun solvePart1() = input.sumOf { it.x } * input.sumOf { it.y }
override fun solvePart2() = input.reduce { acc, d -> acc.addAndAim(d) }.run { x * y }
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 1,148 | advent-of-kotlin | Apache License 2.0 |
src/main/kotlin/g2901_3000/s2916_subarrays_distinct_element_sum_of_squares_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2916_subarrays_distinct_element_sum_of_squares_ii
// #Hard #Array #Dynamic_Programming #Segment_Tree #Binary_Indexed_Tree
// #2023_12_31_Time_467_ms_(100.00%)_Space_58_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
private var n = 0
private lateinit var tree1: LongArray
private lateinit var tree2: LongArray
fun sumCounts(nums: IntArray): Int {
n = nums.size
tree1 = LongArray(n + 1)
tree2 = LongArray(n + 1)
var max = 0
for (x in nums) {
if (x > max) {
max = x
}
}
val last = IntArray(max + 1)
var ans: Long = 0
var cur: Long = 0
for (i in 1..n) {
val x = nums[i - 1]
val j = last[x]
cur += 2 * (query(i) - query(j)) + (i - j)
ans += cur
update(j + 1, 1)
update(i + 1, -1)
last[x] = i
}
return (ans % MOD).toInt()
}
private fun lowbit(index: Int): Int {
return index and (-index)
}
private fun update(index: Int, x: Int) {
var index = index
val v = index * x
while (index <= n) {
tree1[index] += x.toLong()
tree2[index] += v.toLong()
index += lowbit(index)
}
}
private fun query(index: Int): Long {
var index = index
var res: Long = 0
val p = index + 1
while (index > 0) {
res += p * tree1[index] - tree2[index]
index -= lowbit(index)
}
return res
}
companion object {
private const val MOD = 1e9.toInt() + 7
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,681 | LeetCode-in-Kotlin | MIT License |
y2017/src/main/kotlin/adventofcode/y2017/Day18.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
fun main()
{
Day18.solve()
}
object Day18 : AdventSolution(2017, 18, "Duet") {
override fun solvePartOne(input: String): String {
val instructions = parseInstructions(input)
val context = ExecutionContext()
var ip = 0
var mostRecentSound = "nothing"
while (ip in instructions.indices) {
val (operator, x, y) = instructions[ip]
when (operator) {
"set" -> context[x] = context[y]
"add" -> context[x] += context[y]
"mul" -> context[x] *= context[y]
"mod" -> context[x] %= context[y]
"snd" -> mostRecentSound = context[x].toString()
"rcv" -> if (context[x] != 0L) return mostRecentSound
"jgz" -> if (context[x] > 0L) ip += context[y].toInt() - 1
}
ip++
}
return mostRecentSound
}
override fun solvePartTwo(input: String): String {
val instructions = parseInstructions(input)
val q1 = mutableListOf<Long>()
val q2 = mutableListOf<Long>()
val ec0 = ProgramTwo(0, q1, q2)
val ec1 = ProgramTwo(1, q2, q1)
while (ec0.canExecute(instructions) || ec1.canExecute(instructions)) {
ec0.run(instructions)
ec1.run(instructions)
}
return ec1.sendCount.toString()
}
private fun parseInstructions(input: String) = input.lines()
.map { row -> row.split(" ") + "" }
}
private class ProgramTwo(id: Long,
private val sendQueue: MutableList<Long>,
private val receiveQueue: MutableList<Long>) {
private val context = ExecutionContext().apply { this["p"] = id }
private var ip = 0
var sendCount = 0
private set
fun canExecute(instructions: List<List<String>>) = ip in instructions.indices
&& (instructions[ip][0] != "rcv" || receiveQueue.isNotEmpty())
fun run(instructions: List<List<String>>) {
while (canExecute(instructions)) {
executeNext(instructions[ip])
}
}
private fun executeNext(instruction: List<String>) {
val (operator, x, y) = instruction
when (operator) {
"snd" -> {
sendQueue += context[x]
sendCount++
}
"rcv" -> context[x] = receiveQueue.removeAt(0)
"set" -> context[x] = context[y]
"add" -> context[x] += context[y]
"mul" -> context[x] *= context[y]
"mod" -> context[x] %= context[y]
"jgz" -> if (context[x] > 0L) ip += context[y].toInt() - 1
}
ip++
}
}
class ExecutionContext {
private val registers: MutableMap<String, Long> = mutableMapOf()
operator fun get(value: String) = value.toLongOrNull() ?: registers[value] ?: 0
operator fun set(name: String, value: Long) = registers.put(name, value)
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,539 | advent-of-code | MIT License |
omnia/src/commonMain/omnia/algorithm/SetAlgorithms.kt | StrangePan | 224,343,744 | false | {"Kotlin": 490047} | package omnia.algorithm
import omnia.data.structure.Set
import omnia.data.structure.immutable.ImmutableSet
import omnia.data.structure.immutable.ImmutableSet.Companion.toImmutableSet
object SetAlgorithms {
/**
* Computes the mathematical union of two sets. Returns a new set containing all of the items
* present in set [a] and all of the items present in set [b].
*
*
* This operation is commutative; the order of parameters will not affect the result.
*
* @return a new set representing the union of sets [a] and [b]
*/
fun <T : Any> unionOf(a: Set<out T>, b: Set<out T>): ImmutableSet<T> {
return ImmutableSet.builder<T>().addAll(a).addAll(b).build()
}
/**
* Computes the mathematical intersection of two sets. Returns a new set containing all of the
* items present in set [a] and all of the items present in set [b] *except* for
* items present in *both* sets.
*
*
* This operation is commutative; the order of parameters will not affect the result.
*
* @return a new set representing the intersection of sets [a] and [b]
*/
fun <T : Any> intersectionOf(a: Set<out T>, b: Set<out T>): ImmutableSet<T> {
val smaller = if (a.count < b.count) a else b
val larger = if (smaller !== a) a else b
return smaller.filter(larger::containsUnknownTyped).toImmutableSet()
}
/**
* Returns a new set that contains all of the items present in set [a] except for the items
* *also* present in set [b]. The result is guaranteed to never contain any item from
* set [b].
*
*
* This operation **is not commutative**; the order of parameters **will** affect the
* result.
*
* @param a the set of items to possibly include in the final result
* @param b the items not to be included in the final result
* @param T the type of items in set [a]
* @return a new set containing the items from set [a] except for the items contained in
* set [b]
*/
fun <T : Any> differenceBetween(a: Set<out T>, b: Set<*>): ImmutableSet<T> {
return a.filterNot(b::containsUnknownTyped).toImmutableSet()
}
/**
* Computes whether or not two sets are mathematically disjoint. Two sets are disjoint if they
* share no common items. In other words, In other words, this function returns false if any
* item in set [a] is also present in set [b]. Empty sets are considered disjoint,
* despite also being considered equal.
*
*
* This operation is commutative; the order of parameters will not affect the result.
*
* @return true if the sets are disjoint, false if any item is present in both.
*/
fun areDisjoint(a: Set<*>, b: Set<*>): Boolean {
val smaller = if (a.count < b.count) a else b
val larger = if (smaller !== a) a else b
return smaller.any(larger::containsUnknownTyped)
}
} | 0 | Kotlin | 0 | 1 | c6328c20a4f4712f94b2b721219eed5361846292 | 2,824 | omnia | The Unlicense |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day09/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day09
import com.bloidonia.aoc2023.lines
private const val example = """0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45"""
private fun parse(input: String) = input.split(Regex("\\s+")).map { it.toLong() }
// Generate the difference lists, and reverse them
private fun differences(input: String) = generateSequence(parse(input)) { list ->
list.windowed(2, 1).map { it[1] - it[0] }
}
.takeWhile { diffs -> diffs.any { it != 0L } }
.toList()
.reversed()
// Walk the differences adding the last value to the current
private fun part1(input: String) = differences(input)
.fold(0L) { acc, n -> acc + n.last() }
// Walk the differences, taking the current away from the first
private fun part2(input: String) = differences(input)
.fold(0L) { acc, n -> n.first() - acc }
fun main() {
println(example.lines().map(::part1).sum())
println("Part 1: ${lines("/day09.input").map(::part1).sum()}")
println(example.lines().map(::part2))
println("Part 2: ${lines("/day09.input").map(::part2).sum()}")
} | 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 1,061 | aoc-2023 | MIT License |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p01/Leet118.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p01
/**
* Optimizations
* Runtime 158ms Beats 86.92%
* Memory 35.4MB Beats 75.39%
*/
class Leet118 {
class Solution {
fun generate(numRows: Int): List<List<Int>> {
val result = ArrayList<List<Int>>(numRows)
var rowIndex = 0
while (rowIndex < numRows) {
// println("rowIndex: $rowIndex")
val row = ArrayList<Int>(rowIndex + 1)
var elementIndex = 0
while (elementIndex <= rowIndex) {
val rowNumber = rowIndex + 1
if (elementIndex == 0 || elementIndex == rowIndex) {
// println("$elementIndex: const")
row.add(1)
} else if (elementIndex >= rowNumber - (rowNumber / 2)) {
// println("$elementIndex: copy")
row.add(row[rowIndex - elementIndex])
} else {
// println("$elementIndex: calc")
row.add(result[rowIndex - 1][elementIndex - 1] + result[rowIndex - 1][elementIndex])
}
elementIndex++
}
result.add(row)
rowIndex++
}
return result
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
val testCase1 = 1 to "[[1]]"
doWork(testCase1)
val testCase2 = 15 to "[[1]," +
" [1, 1]," +
" [1, 2, 1]," +
" [1, 3, 3, 1]," +
" [1, 4, 6, 4, 1]," +
" [1, 5, 10, 10, 5, 1]," +
" [1, 6, 15, 20, 15, 6, 1]," +
" [1, 7, 21, 35, 35, 21, 7, 1]," +
" [1, 8, 28, 56, 70, 56, 28, 8, 1]," +
" [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]," +
" [1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]," +
" [1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1]," +
" [1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1]," +
" [1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1]," +
" [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]]"
doWork(testCase2)
}
private fun doWork(data: Pair<Int, Any>) {
val solution = Solution()
val result = solution.generate(data.first)
println("Data: ${data.first}")
println("Expected: ${data.second}")
println("Result: $result\n")
}
}
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 2,744 | playground | MIT License |
src/_2022/Day01.kt | albertogarrido | 572,874,945 | false | {"Kotlin": 36434} | package _2022
import readInput
fun main() {
fun getCaloriesPerElf(input: List<String>): Array<Int> {
val calories = Array(input.count { it == "" } + 2) { 0 }
var elf = 1
input.forEach {
if (it == "") {
elf++
} else {
calories[elf] = calories[elf] + it.toInt()
}
}
return calories
}
fun part1(input: List<String>): Int {
val calories = getCaloriesPerElf(input)
return calories.max()
}
fun part2(input: List<String>): Int {
val calories = getCaloriesPerElf(input).also { array -> array.sortBy { it } }
var sum = 0
calories.lastIndex.let { idx ->
(idx downTo idx - 2).forEach {
sum += calories[it]
}
}
return sum
}
val input = readInput("2022", "day01")
println("part1: ${part1(input)}")
println("part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | ef310c5375f67d66f4709b5ac410d3a6a4889ca6 | 967 | AdventOfCode.kt | Apache License 2.0 |
src/main/kotlin/g1101_1200/s1143_longest_common_subsequence/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1101_1200.s1143_longest_common_subsequence
// #Medium #Top_100_Liked_Questions #String #Dynamic_Programming
// #Algorithm_II_Day_17_Dynamic_Programming #Dynamic_Programming_I_Day_19
// #Udemy_Dynamic_Programming #Big_O_Time_O(n*m)_Space_O(n*m)
// #2022_09_13_Time_307_ms_(38.36%)_Space_38.7_MB_(86.99%)
class Solution {
fun longestCommonSubsequence(text1: String, text2: String): Int {
val n = text1.length
val m = text2.length
val dp = Array(n + 1) { IntArray(m + 1) }
for (i in 1..n) {
for (j in 1..m) {
if (text1[i - 1] == text2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[n][m]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 836 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/day03/Day03.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day03
import readResourceAsBufferedReader
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("3_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("3_1.txt").readLines())}")
}
fun part1(input: List<String>): Int {
return input.map { parsePart1(it) }
.flatMap { it.overlap }
.sumOf { it.priority() }
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map { Grouping(it) }
.flatMap { it.overlap }
.sumOf { it.priority() }
}
fun Char.priority(): Int {
return if (this.isLowerCase()) {
this.code - 'a'.code + 1
} else {
27 + this.code - 'A'.code
}
}
private fun parsePart1(input: String): Grouping {
return Grouping(listOf(
input.subSequence(0, input.length / 2).toString(),
input.subSequence(input.length / 2, input.length).toString()
))
}
data class Grouping(val groups: List<String>) {
private val asSets = groups.map { it.toSet() }
val overlap = asSets.reduce { l, r -> l.intersect(r) }
} | 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 1,078 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReversePairs.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
data class Node(val value: Int, var cnt: Int = 1, var left: Node? = null, var right: Node? = null)
private fun Node?.search(value: Int): Int {
return when {
this == null -> {
0
}
value == this.value -> {
this.cnt
}
value < this.value -> {
this.cnt + this.left.search(value)
}
else -> {
this.right.search(value)
}
}
}
private fun insert(r: Node?, value: Int): Node {
var root = r
when {
root == null -> {
root = Node(value)
}
value == root.value -> {
root.cnt++
}
value < root.value -> {
root.left = insert(root.left, value)
}
else -> {
root.cnt++
root.right = insert(root.right, value)
}
}
return root
}
fun IntArray.reversePairsBST(): Int {
var res = 0
var root: Node? = null
for (ele in this) {
res += root.search(2 * ele + 1)
root = insert(root, ele)
}
return res
}
fun IntArray.reversePairsBIT(): Int {
var res = 0
val copy = this.clone()
val bit = IntArray(copy.size + 1)
copy.sort()
for (num in this) {
res += bit.search(copy.index(2L * num + 1))
bit.insert(copy.index(num.toLong()))
}
return res
}
private fun IntArray.search(num: Int): Int {
var sum = 0
var i = num
while (i < size) {
sum += this[i]
i += i and -i
}
return sum
}
private fun IntArray.insert(num: Int) {
var i = num
while (i > 0) {
this[i] += 1
i -= i and -i
}
}
private fun IntArray.index(value: Long): Int {
var l = 0
var r = size - 1
var m: Int
while (l <= r) {
m = l + (r - l shr 1)
if (this[m] >= value) {
r = m - 1
} else {
l = m + 1
}
}
return l + 1
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,572 | kotlab | Apache License 2.0 |
neetcode/src/main/java/org/linkedlist/LinkedList.kt | gouthamhusky | 682,822,938 | false | {"Kotlin": 24242, "Java": 24233} | package org.linkedlist
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
fun deleteDuplicates(head: ListNode?): ListNode? {
var node = head ?: return null
while (node!!.next != null){
if(node.`val` == node.next!!.`val`)
node.next = node.next!!.next
else
node = node.next!!
}
return head
}
fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
var f = list1
var s = list2
var tail: ListNode? = null
var mergedLL: ListNode? = null
while (f != null && s != null){
if (f.`val` < s.`val`){
if (mergedLL == null){
mergedLL = ListNode(f.`val`)
tail = mergedLL
}
else{
tail!!.next = ListNode(f.`val`)
tail = tail.next
}
f = f.next
}
else{
if (mergedLL == null){
mergedLL = ListNode(s.`val`)
tail = mergedLL
}
else{
tail!!.next = ListNode(s.`val`)
tail = tail.next
}
s = s.next
}
}
if (f != null){
while (f != null){
if(tail == null){
mergedLL = ListNode(f.`val`)
tail = mergedLL
}
else{
tail.next = ListNode(f.`val`)
tail = tail.next
}
f = f.next
}
}
if (s != null){
while (s != null){
if(tail == null){
mergedLL = ListNode(s.`val`)
tail = mergedLL
}
else{
tail.next = ListNode(s.`val`)
tail = tail.next
}
s = s.next
}
}
return mergedLL
}
/* https://leetcode.com/problems/linked-list-cycle/
*/
fun hasCycle(head: ListNode?): Boolean {
var fast = head
var slow = head
while (fast?.next != null){
slow = slow!!.next
fast = fast.next?.next
if (fast == slow)
return true
}
return false
}
// find length of cycle
fun lengthCycle(head: ListNode?): Int {
var fast = head
var slow = head
while (fast?.next != null){
slow = slow!!.next
fast = fast.next?.next
if (fast == slow){
var length = 0
do {
length++
slow = slow?.next
}while (slow != fast)
}
}
return 0
}
// https://leetcode.com/problems/linked-list-cycle-ii/
fun detectCycle(head: ListNode?): ListNode? {
var fast = head
var slow = head
var length = 0
while (fast?.next != null){
slow = slow?.next
fast = fast.next!!.next
if (fast == slow){
do {
length++
fast = fast?.next
}while (fast != slow)
break;
}
}
if (length == 0)
return null
var first = head
var second = head
while (length > 0){
second = second?.next
length--
}
while (first != second){
first = first?.next
second = second?.next
}
return second
}
fun isHappy(n: Int): Boolean {
var slow = n
var fast = n
do {
slow = findSquare(slow)
fast = findSquare(findSquare(fast))
}while (fast != slow)
return slow == 1
}
private fun findSquare(n: Int): Int{
var ans = 0
var num = n
while (num > 0){
var rem = num % 10
ans += rem * rem
num /= 10
}
return ans
}
fun middleNode(head: ListNode?): ListNode? {
var fast = head
var slow = head
while (fast?.next != null){
slow = slow?.next
fast = fast.next?.next
}
return slow
}
/*
https://leetcode.com/problems/reverse-linked-list/
in reversal
*/
fun reverseList(head: ListNode?): ListNode? {
var prev: ListNode? = null
var pres = head
var next = head?.next
while (pres != null){
pres.next = prev
prev = pres
pres = next
next = next?.next
}
return prev
}
// https://leetcode.com/problems/reverse-linked-list-ii/
fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode? {
var h = head
if (left == right)
return head
// skip the first left - 1 nodes
var current = head
var prev: ListNode? = null
for (i in 0..<left - 1){
prev = current
current = current?.next
}
val last = prev
val newEnd = current
// reverse between left and right
var next = current?.next
for (i in 0 ..< right - left +1){
current?.next = prev
prev = current
current = next
next = next?.next
}
if (last != null)
last.next = prev
else
h = prev
newEnd?.next = current
return h
}
fun isPalindrome(head: ListNode?): Boolean {
var node = head
// find middle
var mid = middleNode(head)
// reverse second half
var secondHead = reverseList(mid)
var reReverseHead = secondHead
// compare
while (node != null && secondHead != null){
if (node.`val` != secondHead.`val`)
break
node = node.next
secondHead = secondHead.next
}
// re-reverse
reverseList(reReverseHead)
return node == null || secondHead == null
}
fun reorderList(head: ListNode?): Unit {
if(head?.next == null)
return
val mid = middleNode(head)
var hs = reverseList(mid)
var hf = head
while (hf != null && hs != null){
var temp = hf.next
hf.next = hs
hf = temp
temp = hs.next
hs.next = hf
hs = temp
}
if (hf != null)
hf.next = null
}
| 0 | Kotlin | 0 | 0 | a0e158c8f9df8b2e1f84660d5b0721af97593920 | 5,783 | leetcode-journey | MIT License |
src/main/kotlin/com/chriswk/aoc/advent2021/Day10.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day10: AdventDay(2021, 10) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day10()
report {
day.part1()
}
report {
day.part2()
}
}
val errors = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137)
val closers = mapOf('(' to ')', '{' to '}', '[' to ']', '<' to '>')
val completion = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4)
}
fun handleLine(line: String): Pair<Long, Int> {
val stack = ArrayDeque<Char>()
line.forEach {
when(it) {
'(', '{', '[', '<' -> stack.addFirst(closers[it]!!)
')', '}', ']', '>' -> {
val expectedClose = stack.firstOrNull()?: ' '
if (it == expectedClose) {
stack.removeFirst()
} else {
return 0L to errors[it]!!
}
}
}
}
return stack.fold(0L) { soFar, char -> (soFar * 5) + completion[char]!! } to 0
}
fun errorScore(lines: List<String>): Int {
return lines.sumOf { handleLine(it).second }
}
fun completionScore(line: String): Long {
return handleLine(line).first
}
fun completionScores(lines: List<String>): List<Long> {
return lines.map { completionScore(it) }.filter { it > 0 }
}
fun middleCompletionScore(lines: List<String>): Long {
val scores = completionScores(lines).sorted()
return scores[scores.size / 2]
}
fun part1(): Int {
return errorScore(inputAsLines)
}
fun part2(): Long {
return middleCompletionScore(inputAsLines)
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 1,900 | adventofcode | MIT License |
src/main/kotlin/com/sk/set2/229. Majority Element II.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set2
private fun majorityElement(nums: IntArray): List<Int> {
val l = nums.size / 3
val g = nums
.toList()
.groupingBy { it }
.eachCount()
.filter { it.value > l }
.map { it.key }
return g
}
private fun majorityElement2(nums: IntArray): List<Int> {
var ans = mutableListOf<Int>()
if (nums.isEmpty()) return ans
var a = 0
var b = 1
var ca = 0
var cb = 0
for (x in nums) {
if (x == a) ca++
else if (x == b) cb++
else if (ca == 0) {
a = x
ca = 1
} else if (cb == 0) {
b = x
cb = 1
} else {
ca--
cb--
}
}
ca = 0.also { cb = 0 }
for (x in nums)
if (x == a) ca++
else if (x == b) cb++
if (ca > nums.size / 3) ans.add(a)
if (cb > nums.size / 3) ans.add(b)
return ans
}
private fun majorityElement3(nums: IntArray): List<Int>? {
val K = 3
val candidates: MutableMap<Int, Int> = HashMap()
//get all candidates
for (a in nums) {
candidates[a] = candidates.getOrDefault(a, 0) + 1
if (candidates.size == K) {
val it = candidates.entries.iterator()
while (it.hasNext()) {
val item = it.next()
if (item.value == 1) it.remove() else item.setValue(item.value - 1)
}
}
}
//check correctness of candidates
val ans: MutableList<Int> = ArrayList()
val it: Iterator<Map.Entry<Int, Int>> = candidates.entries.iterator()
while (it.hasNext()) {
val key = it.next().key
var count = 0
for (a in nums) {
if (a == key) count++
if (count > nums.size / K) {
ans.add(key)
break
}
}
}
return ans
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,861 | leetcode-kotlin | Apache License 2.0 |
src/day12/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day12
import Coord
import closeNeighbours
import day06.main
import readInput
fun main() {
fun parse(input: List<String>): Triple<Coord, Coord, Map<Coord, Char>> {
val map = input.flatMapIndexed { y, s -> s.mapIndexed { x, c -> Coord(x, y) to c } }.toMap()
val start = map.entries.first { it.value == 'S' }.key
val end = map.entries.first { it.value == 'E' }.key
val heightmap = map.mapValues {
when (it.value) {
'S' -> 'a'
'E' -> 'z'
else -> it.value
}
}
return Triple(start, end, heightmap)
}
fun part1(start: Coord, end: Coord, heightmap: Map<Coord, Char>) = mutableSetOf<Coord>().let { seen ->
fun Coord.isAccessible(from: Coord) = heightmap[this]?.takeIf { it - heightmap[from]!! <= 1 } != null
generateSequence(setOf(start)) { frontier ->
frontier.flatMap { coord ->
coord.closeNeighbours.filter { newCoord -> newCoord !in seen && newCoord.isAccessible(coord) }
}.toSet().takeIf { end !in seen }?.also { seen += it }
}
}.count()
fun part2(end: Coord, heightmap: Map<Coord, Char>) = mutableSetOf<Coord>().let { seen ->
fun Coord.isAccessible(from: Coord) = heightmap[this]?.takeIf { heightmap[from]!! - it <= 1 } != null
generateSequence(setOf(end)) { frontier ->
frontier.flatMap { coord ->
coord.closeNeighbours.filter { newCoord -> newCoord !in seen && newCoord.isAccessible(coord) }
}.toSet().takeIf { it.none { heightmap[it] == 'a' } }?.also { seen += it }
}
}.count()
val (start, end, heightmap) = parse(readInput(::main.javaClass.packageName))
println("Part1=\n" + part1(start, end, heightmap))
println("Part2=\n" + part2(end, heightmap))
}
| 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 1,849 | AOC2022 | Apache License 2.0 |
src/main/kotlin/day10/Adapters.kt | lukasz-marek | 317,632,409 | false | {"Kotlin": 172913} | package day10
data class Adapter(val output: Int)
interface AdaptersConnector {
fun connect(adapters: List<Adapter>): Map<Int, Int>
}
class AdaptersConnectorImpl : AdaptersConnector {
override fun connect(adapters: List<Adapter>): Map<Int, Int> {
val sortedAdapterValues = adapters.map { it.output }.sorted().toMutableList()
val lastAdapterValue = sortedAdapterValues.last() + 3
val firstAdapterValue = 0
sortedAdapterValues.add(0, firstAdapterValue)
sortedAdapterValues.add(sortedAdapterValues.size, lastAdapterValue)
return sortedAdapterValues
.zipWithNext()
.fold(emptyMap()) { acc, pair ->
val diff = pair.second - pair.first
val previousValue = acc[diff] ?: 0
acc + (diff to (previousValue + 1))
}
}
}
interface ArrangementsCounter {
fun count(adapters: List<Adapter>): Long
}
class ArrangementsCounterImpl : ArrangementsCounter {
override fun count(adapters: List<Adapter>): Long {
val frontier = mapOf(Adapter(0) to 1L)
val sortedAdapters = adapters.sortedBy { it.output }
val lastAdapter = Adapter(sortedAdapters.last().output + 3)
return count(frontier, sortedAdapters + lastAdapter, 0L)
}
private tailrec fun count(frontier: Map<Adapter, Long>, adapters: List<Adapter>, acc: Long): Long {
val newFrontier = frontier.asSequence().map { entry ->
entry to adapters.filter { adapter ->
val diff = adapter.output - entry.key.output
diff in 1..3
}
}.map { pair ->
val multiplier = pair.first.value
pair.second.map { it to multiplier }
}
.fold(mutableMapOf<Adapter, Long>()) { frontierInProgress, list ->
list.forEach { frontierElement ->
val oldValue = frontierInProgress[frontierElement.first] ?: 0
val newValue = oldValue + frontierElement.second
frontierInProgress[frontierElement.first] = newValue
}
frontierInProgress
}
val newAcc = acc + frontier.filter { it.key == adapters.last() }.map { it.value }.sum()
return if (newFrontier.isEmpty()) newAcc else count(newFrontier, adapters, newAcc)
}
} | 0 | Kotlin | 0 | 0 | a16e95841e9b8ff9156b54e74ace9ccf33e6f2a6 | 2,358 | aoc2020 | MIT License |
src/deselby/std/NDRange.kt | deselby-research | 166,023,166 | false | null | package deselby.std
import kotlin.math.max
import kotlin.math.min
class NDRange(val range : Array<IntProgression>) : Iterable<IntArray> {
val nDimensions : Int
get() = range.size
val shape : IntArray
get() = IntArray(nDimensions) {
(this[it].last - this[it].first + 1)/this[it].step
}
constructor(size : Int, filler : (Int) -> IntProgression) : this(Array(size, filler))
operator fun get(dimension : Int) = range.get(dimension)
operator fun set(dimension : Int, intRange : IntProgression) {
range[dimension] = intRange
}
override fun iterator(): Iterator<IntArray> {
return NDRangeIterator(range)
}
infix fun step(step : IntArray) = NDRange(Array(range.size) {
IntProgression.fromClosedRange(range[it].first, range[it].last, step[it])
})
fun first() = IntArray(range.size) {
range[it].first
}
fun last() = IntArray(range.size) {
range[it].last
}
// smallest bounding box (with step 1) that contains both NDRanges
fun rectangularUnion(other : NDRange) : NDRange {
if(nDimensions != other.nDimensions)
throw(IllegalArgumentException("Union of NDRanges with differing dimensionality: This is probably not what you intended to do"))
return NDRange(nDimensions) {
min(range[it].first, other.range[it].first) .. max(range[it].last, other.range[it].last)
}
}
// largest box (ignoring steps) that is contained within both NDRanges
fun rectangularIntersection(other : NDRange) : NDRange {
if(nDimensions != other.nDimensions)
throw(IllegalArgumentException("Intersection of NDIndexSets with differing dimensionality: This is probably not what you intended to do"))
return NDRange(nDimensions) {
max(range[it].first, other.range[it].first) .. min(range[it].last, other.range[it].last)
}
}
}
class NDRangeIterator(val range : Array<out IntProgression>) : Iterator<IntArray> {
val index = IntArray(range.size) { if(it == range.size-1) range[it].first-range[it].step else range[it].first }
override fun hasNext(): Boolean {
return index.foldIndexed(false) {i, acc, v -> acc || v < range[i].last}
}
override fun next(): IntArray {
var i = index.size - 1
index[i] += range[i].step
while (index[i] > range[i].last) {
index[i] = range[i].first
index[--i] += range[i].step
}
return index
}
}
operator fun IntArray.rangeTo(other : IntArray) = NDRange(Array(this.size) {
this[it] .. other[it]
})
infix fun IntArray.until(other : IntArray) = NDRange(Array(this.size) {
this[it] until other[it]
}) | 0 | Kotlin | 1 | 8 | 6c76a9a18e2caafc1ff00ab970d0df4d703f0119 | 2,738 | ProbabilisticABM | MIT License |
common/comparison/src/main/kotlin/com/curtislb/adventofcode/common/comparison/MinMax.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.common.comparison
/**
* The minimum and maximum of a group of comparable values.
*
* @param min The minimum value from the original group.
* @param max The maximum value from the original group.
*/
data class MinMax<T>(val min: T, val max: T)
/**
* Returns the minimum and maximum elements from this iterable, or `null` if there are no elements.
*/
fun <T : Comparable<T>> Iterable<T>.minMaxOrNull(): MinMax<T>? {
var minElement: T? = null
var maxElement: T? = null
for (element in this) {
minElement = if (minElement == null) element else element.coerceAtMost(minElement)
maxElement = if (maxElement == null) element else element.coerceAtLeast(maxElement)
}
return if (minElement == null) null else MinMax(minElement, maxElement!!)
}
/**
* Returns the elements that produce the minimum and maximum value, respectively, after applying the
* [transform] function to each element in this iterable, or `null` if there are no elements.
*/
inline fun <T, R : Comparable<R>> Iterable<T>.minMaxByOrNull(
transform: (element: T) -> R
): MinMax<T>? {
var minElement: T? = null
var maxElement: T? = null
var minValue: R? = null
var maxValue: R? = null
for (element in this) {
val value = transform(element)
// Update minimum element and value if necessary
if (minValue == null || value < minValue) {
minElement = element
minValue = value
}
// Update maximum element and value if necessary
if (maxValue == null || value > maxValue) {
maxElement = element
maxValue = value
}
}
return if (minElement == null) null else MinMax(minElement, maxElement!!)
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 1,764 | AdventOfCode | MIT License |
src/chapter1/section4/ex2.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter1.section4
/**
* 修改ThreeSum,正确处理两个较大的int值相加可能溢出的情况。
*
* 解:两个数正负号相同才可能溢出,如果两个数正负号相同,相加后和的正负号和原来的符号不同,则发生溢出
* 如果两个数相加溢出,第三个数在整数范围内无论取什么值,三个数的和都不可能为0
* 唯一例外是前两个数的和溢出后的值为Int.MIN_VALUE,第三个值为Int.MIN_VALUE 前两个值溢出,但和为0
* (因为最小负整数Int.MIN_VALUE的绝对值比最大正整数Int.MAX_VALUE的绝对值大1)
* 也可以将Int转换为Long或BigInteger计算,这样比较简单一些
*/
fun ex2(array: IntArray): Long {
val n = array.size
var count = 0L
for (i in 0 until n) {
for (j in i + 1 until n) {
for (k in j + 1 until n) {
val twoSum = array[i] + array[j]
if (array[i] > 0 && array[j] > 0 && twoSum < 0) {
if (twoSum == Int.MIN_VALUE && array[k] == Int.MIN_VALUE) {
count++
} else {
continue
}
} else if (array[i] < 0 && array[j] < 0 && twoSum > 0) {
continue
} else if (twoSum + array[k] == 0) {
count++
}
}
}
}
return count
}
fun main() {
//这组测试数据中三元素和为0的组合有
//a[0]+a[2]+a[6] a[1]+a[2]+a[6] a[3]+a[4]+a[5]
//被threeSum()函数误判的组合为 a[0]+a[1]+a[2]
val array = intArrayOf(Int.MAX_VALUE, Int.MAX_VALUE, 1, 2, 3, -5, Int.MIN_VALUE)
println("threeSumCount = ${threeSum(array)}")
println("fixIntegerOverflowCount = ${ex2(array)}")
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,809 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/day01/day01.kt | brighta | 572,053,290 | false | null | package day01
import readInput
fun main() {
fun splitFileIntoElves(file: List<String>): List<Int> {
val elves: MutableList<Int> = mutableListOf()
var currentElf = 0
for (line in file) {
if (line == "") {
elves.add(currentElf)
currentElf = 0
} else {
currentElf += line.toInt()
}
}
elves.add(currentElf)
elves.sortDescending()
return elves
}
fun part1(input: List<String>): Int {
val elves: List<Int> = splitFileIntoElves(input)
return elves[0]
}
fun part2(input: List<String>): Int {
val elves: List<Int> = splitFileIntoElves(input)
return elves.subList(0, 3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01", "_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("day01")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 23971f6b72523f91aa6488e87cf12e804a089a78 | 1,081 | advent-of-code-kotlin | Apache License 2.0 |
advent-of-code-2018/src/test/java/aoc/Advent16.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | package aoc
import org.assertj.core.api.KotlinAssertions.assertThat
import org.junit.Test
class Advent16 {
data class UnknownOperation(val opcode: Int, val a: Int, val b: Int, val c: Int)
data class Observation(
val before: Registers,
val operation: UnknownOperation,
val after: Registers
)
val opcodes = listOf(
"addr",
"addi",
"mulr",
"muli",
"banr",
"bani",
"borr",
"bori",
"setr",
"seti",
"gtir",
"gtri",
"gtrr",
"eqir",
"eqri",
"eqrr"
)
@Test
fun `Star 1`() {
val observations = parseObservations()
val result = observations
// .onEach { println(it.toString()) }
.map { observation ->
opcodes
.map { Operation(it, observation.operation.a, observation.operation.b, observation.operation.c) }
.count { operation -> operation.mutate(observation.before) == observation.after }
}.count { it >= 3 }
assertThat(result).isEqualTo(493)
}
private fun opcodeMapping(): Map<Int, String> {
return generateSequence(emptyList()) { found: List<Pair<Int, String>> ->
val newlyFound: List<Pair<Int, String>> = findDefinitiveMappings(parseObservations(), found)
found.plus(newlyFound)
}
.filter { it.size == opcodes.size }
.first()
.toMap()
}
@Test
fun `Star2`() {
val map: Map<Int, String> = opcodeMapping()
val result = program.lines()
.filterNot { it.isBlank() }
.map { it.split(' ').map(String::toInt) }
.map { (one, two, three, four) -> Operation(map[one]!!, two, three, four) }
.fold(Registers(0, 0, 0, 0)) { regs, operation ->
operation.mutate(regs)
}.reg0
assertThat(result).isEqualTo(445)
}
private fun findDefinitiveMappings(
observations: List<Observation>,
known: List<Pair<Int, String>>
): List<Pair<Int, String>> {
return observations
.filter { observation -> observation.operation.opcode !in known.map { it.first } }
.mapNotNull { observation ->
val possibleOperations = opcodes
.filter { op -> op !in known.map { it.second } }
.map { Operation(it, observation.operation.a, observation.operation.b, observation.operation.c) }
val applicableOperations = possibleOperations
.filter { operation -> operation.mutate(observation.before) == observation.after }
when {
applicableOperations.count() == 1 -> observation.operation.opcode to applicableOperations.first().opcode
else -> null
}
}.distinct()
}
private fun parseObservations(): List<Observation> {
return observationsStr.split("\n\n").map { record ->
record.split('[', ']', ',', ' ', '\n')
}.map { record ->
val mapNotNull = record.mapNotNull { it.trim().toIntOrNull() }
mapNotNull.iterator().run {
Observation(
before = Registers(next(), next(), next(), next()),
operation = UnknownOperation(next(), next(), next(), next()),
after = Registers(next(), next(), next(), next())
)
}
}
}
val program = """
1 0 0 1
4 1 1 1
14 0 0 3
14 3 2 2
12 3 2 1
1 1 2 1
11 1 0 0
3 0 2 1
14 2 2 0
9 0 2 0
1 0 2 0
11 0 1 1
3 1 2 3
1 1 0 0
4 0 1 0
14 1 1 1
14 2 0 2
3 0 2 2
1 2 1 2
11 2 3 3
3 3 2 0
14 1 3 3
14 3 1 1
14 3 0 2
4 3 1 3
1 3 3 3
11 3 0 0
14 2 0 2
14 0 0 3
7 3 2 3
1 3 2 3
11 3 0 0
3 0 3 3
14 2 3 0
14 3 0 2
14 0 1 1
14 2 1 1
1 1 3 1
1 1 2 1
11 1 3 3
3 3 2 1
1 3 0 2
4 2 0 2
14 2 2 3
5 0 3 3
1 3 3 3
11 3 1 1
3 1 0 0
14 2 1 2
14 3 2 1
14 2 0 3
0 1 3 3
1 3 2 3
11 0 3 0
3 0 0 2
14 1 3 3
14 3 3 0
4 3 1 0
1 0 2 0
1 0 2 0
11 2 0 2
14 0 1 0
1 0 0 1
4 1 1 1
1 1 0 3
4 3 2 3
13 1 3 3
1 3 2 3
11 2 3 2
14 3 3 1
1 1 0 3
4 3 2 3
14 2 1 0
14 3 0 1
1 1 3 1
11 1 2 2
3 2 2 0
14 3 3 2
14 2 3 1
14 1 0 3
1 3 2 1
1 1 1 1
11 0 1 0
14 2 3 2
14 2 3 3
14 0 3 1
2 2 3 2
1 2 1 2
1 2 1 2
11 0 2 0
3 0 1 1
1 2 0 2
4 2 0 2
14 2 3 0
14 3 2 3
0 3 0 2
1 2 1 2
11 2 1 1
3 1 1 0
14 0 1 1
14 3 3 2
1 1 0 3
4 3 1 3
4 3 1 1
1 1 1 1
11 1 0 0
3 0 3 1
14 2 0 3
14 0 1 2
14 2 2 0
5 0 3 0
1 0 2 0
11 0 1 1
3 1 0 3
14 2 1 0
14 3 2 2
1 1 0 1
4 1 2 1
9 0 2 0
1 0 1 0
1 0 2 0
11 0 3 3
3 3 0 1
14 2 1 3
14 0 2 2
1 3 0 0
4 0 2 0
12 2 3 2
1 2 2 2
11 2 1 1
14 3 2 2
14 0 0 3
9 0 2 3
1 3 3 3
1 3 2 3
11 1 3 1
3 1 1 2
14 1 2 3
14 2 1 1
14 3 0 0
0 0 1 3
1 3 1 3
11 3 2 2
14 1 3 3
14 2 0 0
15 0 3 1
1 1 3 1
11 1 2 2
1 0 0 1
4 1 3 1
14 2 2 3
6 0 1 1
1 1 3 1
11 2 1 2
3 2 0 1
14 2 0 2
14 1 3 0
2 2 3 3
1 3 3 3
11 3 1 1
14 1 3 3
14 2 1 0
1 1 0 2
4 2 3 2
15 0 3 0
1 0 3 0
1 0 2 0
11 0 1 1
14 3 0 0
1 3 0 3
4 3 0 3
12 3 2 3
1 3 3 3
1 3 2 3
11 3 1 1
14 2 1 0
1 1 0 3
4 3 3 3
1 2 0 2
4 2 1 2
0 3 0 0
1 0 3 0
11 0 1 1
14 2 1 0
14 2 1 3
5 0 3 3
1 3 3 3
1 3 3 3
11 1 3 1
14 2 3 3
14 0 0 2
14 3 0 0
12 2 3 0
1 0 3 0
11 0 1 1
3 1 2 2
14 3 1 3
14 3 1 1
1 1 0 0
4 0 2 0
6 0 1 1
1 1 2 1
11 1 2 2
3 2 0 1
14 2 0 3
1 3 0 0
4 0 1 0
14 0 2 2
11 0 0 3
1 3 1 3
11 3 1 1
3 1 1 2
1 1 0 0
4 0 2 0
14 3 0 3
14 0 2 1
14 1 3 1
1 1 2 1
1 1 2 1
11 1 2 2
3 2 3 0
14 3 0 2
14 1 2 1
14 1 2 3
11 3 3 2
1 2 3 2
11 0 2 0
3 0 0 1
14 1 1 2
14 2 0 0
13 3 0 3
1 3 3 3
11 3 1 1
3 1 0 3
14 3 2 1
14 1 2 0
14 3 3 2
4 0 1 1
1 1 2 1
11 3 1 3
3 3 0 1
14 2 0 0
14 0 3 3
8 0 2 0
1 0 1 0
11 1 0 1
3 1 2 2
14 3 0 3
14 2 1 1
14 2 2 0
0 3 0 0
1 0 3 0
11 0 2 2
3 2 2 3
14 3 3 0
14 2 0 2
6 2 0 2
1 2 1 2
11 2 3 3
3 3 0 0
14 0 2 2
1 1 0 3
4 3 0 3
14 3 2 1
10 1 2 2
1 2 1 2
11 2 0 0
3 0 2 2
1 3 0 1
4 1 1 1
14 2 0 0
1 2 0 3
4 3 1 3
15 0 3 0
1 0 1 0
11 2 0 2
3 2 0 1
14 2 0 2
14 3 1 0
6 2 0 3
1 3 1 3
11 1 3 1
3 1 3 2
14 2 0 3
14 0 0 1
0 0 3 1
1 1 3 1
11 2 1 2
3 2 2 1
14 2 2 0
14 3 3 2
5 0 3 3
1 3 3 3
1 3 3 3
11 3 1 1
14 3 3 3
14 1 0 0
1 0 2 0
1 0 2 0
11 1 0 1
14 2 3 3
14 0 3 2
14 3 1 0
9 2 0 3
1 3 1 3
11 1 3 1
1 0 0 2
4 2 3 2
14 0 0 3
12 3 2 0
1 0 2 0
11 1 0 1
14 1 3 0
14 2 3 2
14 3 2 3
3 0 2 0
1 0 1 0
11 0 1 1
3 1 0 0
14 1 2 1
14 1 3 3
14 3 0 2
1 3 2 1
1 1 3 1
11 1 0 0
3 0 3 2
1 2 0 1
4 1 2 1
14 0 0 3
1 3 0 0
4 0 3 0
2 1 3 1
1 1 3 1
11 2 1 2
3 2 0 1
14 2 2 0
14 2 2 3
1 3 0 2
4 2 3 2
5 0 3 0
1 0 1 0
11 1 0 1
3 1 0 3
1 3 0 2
4 2 2 2
14 3 2 0
1 2 0 1
4 1 0 1
6 2 0 1
1 1 1 1
1 1 1 1
11 3 1 3
3 3 3 1
14 0 3 0
14 0 1 2
14 2 3 3
12 2 3 3
1 3 2 3
11 1 3 1
3 1 3 0
14 3 3 3
14 3 2 1
10 3 2 1
1 1 3 1
1 1 3 1
11 0 1 0
3 0 3 2
14 0 2 1
14 2 0 0
14 1 3 3
15 0 3 0
1 0 3 0
11 0 2 2
3 2 3 0
14 2 0 2
14 2 3 3
14 2 0 1
2 2 3 2
1 2 1 2
11 0 2 0
3 0 3 1
14 2 2 2
14 3 2 0
2 2 3 3
1 3 2 3
11 1 3 1
14 2 2 0
14 1 3 3
14 3 2 2
9 0 2 0
1 0 2 0
11 0 1 1
14 2 1 0
9 0 2 3
1 3 1 3
11 1 3 1
14 1 2 3
1 1 0 0
4 0 1 0
1 3 2 3
1 3 1 3
11 1 3 1
3 1 3 0
1 2 0 1
4 1 1 1
14 2 2 2
14 0 3 3
7 3 2 3
1 3 1 3
11 3 0 0
3 0 2 2
14 2 0 1
14 0 3 3
14 3 1 0
8 1 0 3
1 3 2 3
11 3 2 2
3 2 1 1
14 2 1 3
14 0 0 2
14 0 0 0
12 2 3 0
1 0 2 0
11 0 1 1
3 1 0 0
14 2 2 2
1 1 0 3
4 3 0 3
14 0 1 1
7 3 2 1
1 1 1 1
11 1 0 0
3 0 1 1
14 2 2 3
14 3 0 2
14 2 2 0
9 0 2 3
1 3 2 3
1 3 3 3
11 3 1 1
3 1 0 0
14 1 0 3
1 1 0 1
4 1 3 1
14 1 3 2
10 1 2 1
1 1 2 1
11 1 0 0
3 0 0 1
1 3 0 3
4 3 0 3
14 0 2 0
14 3 2 0
1 0 3 0
11 0 1 1
3 1 2 0
14 1 2 3
14 0 0 1
11 3 3 1
1 1 2 1
1 1 3 1
11 0 1 0
3 0 0 3
14 2 3 0
1 1 0 1
4 1 2 1
14 3 3 2
9 0 2 2
1 2 1 2
11 2 3 3
3 3 0 1
14 0 2 3
14 0 0 0
1 2 0 2
4 2 2 2
7 3 2 2
1 2 2 2
11 2 1 1
3 1 0 2
14 3 0 1
14 3 2 0
14 2 2 3
0 0 3 0
1 0 3 0
11 0 2 2
3 2 2 1
14 1 0 3
14 2 1 0
14 0 3 2
15 0 3 2
1 2 1 2
11 1 2 1
1 1 0 2
4 2 0 2
15 0 3 0
1 0 1 0
11 1 0 1
14 3 3 0
14 0 1 3
14 2 2 2
7 3 2 0
1 0 2 0
11 1 0 1
3 1 0 3
1 1 0 2
4 2 0 2
14 3 0 0
14 1 1 1
1 1 2 2
1 2 3 2
11 2 3 3
3 3 1 1
14 2 0 0
14 0 1 3
14 2 1 2
7 3 2 0
1 0 3 0
11 0 1 1
3 1 2 3
14 0 0 1
14 1 1 0
3 0 2 0
1 0 2 0
1 0 2 0
11 3 0 3
3 3 0 2
14 1 0 1
14 2 3 3
14 2 2 0
5 0 3 1
1 1 1 1
11 2 1 2
3 2 0 1
14 3 0 2
9 0 2 0
1 0 2 0
11 1 0 1
3 1 3 3
14 2 1 0
1 3 0 2
4 2 2 2
14 3 2 1
6 2 1 1
1 1 2 1
11 1 3 3
3 3 0 1
1 2 0 3
4 3 0 3
14 1 3 0
3 0 2 2
1 2 3 2
1 2 1 2
11 2 1 1
3 1 1 2
14 2 2 3
14 3 3 1
1 0 0 0
4 0 3 0
0 1 3 0
1 0 1 0
11 0 2 2
3 2 3 1
14 0 1 2
14 3 1 0
14 1 3 3
1 3 2 0
1 0 1 0
11 1 0 1
14 2 0 3
14 3 2 2
14 2 3 0
5 0 3 2
1 2 2 2
11 2 1 1
3 1 2 0
14 3 3 1
14 0 3 2
12 2 3 3
1 3 1 3
1 3 3 3
11 3 0 0
3 0 2 2
14 0 0 1
14 2 3 0
14 1 2 3
15 0 3 3
1 3 3 3
11 2 3 2
3 2 0 1
14 2 0 3
14 1 3 2
5 0 3 2
1 2 2 2
11 1 2 1
3 1 3 3
1 3 0 0
4 0 1 0
14 0 3 1
14 1 0 2
4 0 1 2
1 2 1 2
11 3 2 3
3 3 1 0
14 0 1 3
1 1 0 2
4 2 3 2
14 2 2 1
12 3 2 2
1 2 3 2
11 2 0 0
3 0 2 1
14 3 2 0
1 1 0 2
4 2 0 2
14 2 3 3
12 2 3 3
1 3 1 3
1 3 1 3
11 3 1 1
3 1 0 3
14 2 0 1
9 2 0 2
1 2 2 2
11 3 2 3
3 3 1 2
14 2 2 0
14 1 3 3
14 0 3 1
15 0 3 1
1 1 1 1
11 1 2 2
3 2 3 0
14 2 1 2
14 0 0 1
14 0 1 3
7 3 2 3
1 3 2 3
11 3 0 0
3 0 2 3
14 2 1 1
14 3 0 0
0 0 1 0
1 0 1 0
11 0 3 3
3 3 3 0
1 2 0 3
4 3 0 3
14 1 2 1
7 3 2 2
1 2 1 2
11 2 0 0
3 0 1 1
14 3 0 2
14 1 0 3
14 2 0 0
15 0 3 2
1 2 3 2
11 2 1 1
14 3 1 0
14 0 2 3
14 2 0 2
7 3 2 2
1 2 2 2
11 1 2 1
14 1 0 0
14 2 2 2
3 0 2 3
1 3 2 3
1 3 3 3
11 1 3 1
3 1 0 0
14 2 2 1
14 0 3 3
14 3 1 1
1 1 2 1
11 1 0 0
3 0 1 1
14 1 0 0
11 0 0 0
1 0 1 0
1 0 1 0
11 1 0 1
3 1 2 2
14 2 1 1
14 3 2 0
14 3 1 3
8 1 0 0
1 0 3 0
1 0 1 0
11 2 0 2
3 2 1 0
14 1 3 3
14 0 3 1
14 2 3 2
4 3 1 3
1 3 2 3
11 3 0 0
3 0 0 3
14 3 1 0
14 1 0 1
8 2 0 2
1 2 3 2
1 2 1 2
11 3 2 3
14 1 1 0
14 3 3 1
14 0 3 2
11 0 0 0
1 0 2 0
11 0 3 3
3 3 0 2
1 3 0 0
4 0 2 0
1 2 0 3
4 3 1 3
15 0 3 0
1 0 3 0
11 0 2 2
14 1 3 0
14 1 0 1
14 2 0 3
11 0 0 3
1 3 1 3
1 3 1 3
11 3 2 2
3 2 0 1
14 0 0 3
14 2 0 2
7 3 2 0
1 0 3 0
11 0 1 1
3 1 2 0
14 1 3 3
14 1 0 1
14 0 2 2
1 1 2 1
1 1 3 1
11 1 0 0
3 0 3 2
14 2 2 0
1 2 0 1
4 1 1 1
13 1 0 0
1 0 1 0
1 0 2 0
11 2 0 2
3 2 1 1
1 3 0 0
4 0 3 0
14 0 3 2
14 2 0 3
9 2 0 2
1 2 3 2
11 1 2 1
14 0 2 2
14 1 3 3
9 2 0 0
1 0 1 0
11 0 1 1
3 1 2 3
14 2 1 0
14 3 0 2
14 1 1 1
14 2 1 0
1 0 1 0
11 0 3 3
14 3 2 0
14 0 1 2
14 2 3 1
10 0 2 0
1 0 2 0
11 3 0 3
3 3 3 2
14 3 1 0
1 0 0 3
4 3 2 3
14 1 1 1
13 1 3 1
1 1 1 1
11 1 2 2
14 1 1 1
14 1 3 3
14 2 3 0
15 0 3 3
1 3 2 3
11 2 3 2
3 2 1 1
14 1 2 0
14 0 3 3
14 2 1 2
7 3 2 2
1 2 2 2
11 2 1 1
14 1 0 2
14 1 3 3
14 2 1 0
15 0 3 3
1 3 2 3
11 1 3 1
14 1 2 3
1 2 0 0
4 0 1 0
14 2 0 2
3 0 2 3
1 3 3 3
11 3 1 1
14 2 3 3
14 2 3 0
5 0 3 3
1 3 1 3
1 3 2 3
11 1 3 1
3 1 3 3
14 1 2 0
1 3 0 1
4 1 1 1
14 3 1 2
1 0 2 0
1 0 2 0
11 0 3 3
14 2 0 2
1 1 0 0
4 0 1 0
14 3 0 1
4 0 1 1
1 1 1 1
1 1 2 1
11 1 3 3
3 3 3 0
14 0 3 3
14 3 0 1
7 3 2 1
1 1 2 1
1 1 2 1
11 0 1 0
3 0 2 1
14 1 3 2
14 2 1 0
14 1 1 3
13 3 0 2
1 2 3 2
11 2 1 1
3 1 1 3
14 2 2 2
14 2 2 1
14 1 3 0
3 0 2 1
1 1 2 1
11 3 1 3
3 3 2 0
""".trimIndent()
val observationsStr = """
Before: [3, 0, 1, 3]
15 2 1 3
After: [3, 0, 1, 1]
Before: [1, 3, 2, 0]
11 2 2 0
After: [4, 3, 2, 0]
Before: [0, 3, 3, 1]
14 3 2 0
After: [3, 3, 3, 1]
Before: [2, 3, 1, 3]
9 2 1 1
After: [2, 1, 1, 3]
Before: [1, 2, 3, 0]
0 2 1 2
After: [1, 2, 2, 0]
Before: [3, 2, 1, 3]
8 2 3 2
After: [3, 2, 3, 3]
Before: [1, 0, 1, 3]
15 2 1 2
After: [1, 0, 1, 3]
Before: [0, 0, 1, 1]
15 3 1 1
After: [0, 1, 1, 1]
Before: [1, 3, 2, 3]
9 0 1 0
After: [1, 3, 2, 3]
Before: [1, 0, 0, 1]
15 3 1 1
After: [1, 1, 0, 1]
Before: [0, 2, 2, 0]
4 0 1 3
After: [0, 2, 2, 1]
Before: [0, 0, 3, 1]
5 0 2 0
After: [0, 0, 3, 1]
Before: [0, 1, 0, 2]
14 3 1 0
After: [3, 1, 0, 2]
Before: [0, 2, 2, 0]
5 0 2 3
After: [0, 2, 2, 0]
Before: [1, 1, 2, 3]
10 3 2 0
After: [2, 1, 2, 3]
Before: [1, 2, 3, 2]
13 0 1 1
After: [1, 2, 3, 2]
Before: [0, 3, 2, 0]
1 1 2 1
After: [0, 6, 2, 0]
Before: [1, 2, 2, 3]
1 0 2 1
After: [1, 2, 2, 3]
Before: [3, 1, 2, 2]
13 0 3 2
After: [3, 1, 6, 2]
Before: [3, 3, 2, 1]
14 3 2 3
After: [3, 3, 2, 3]
Before: [0, 3, 1, 0]
5 0 1 0
After: [0, 3, 1, 0]
Before: [1, 0, 2, 3]
12 0 1 0
After: [1, 0, 2, 3]
Before: [3, 0, 2, 2]
3 2 2 0
After: [2, 0, 2, 2]
Before: [0, 1, 1, 3]
6 0 0 1
After: [0, 0, 1, 3]
Before: [0, 0, 2, 2]
6 0 0 2
After: [0, 0, 0, 2]
Before: [2, 3, 1, 3]
9 2 1 0
After: [1, 3, 1, 3]
Before: [3, 0, 1, 1]
15 2 1 1
After: [3, 1, 1, 1]
Before: [1, 2, 1, 2]
8 0 3 1
After: [1, 3, 1, 2]
Before: [3, 2, 3, 2]
13 0 3 2
After: [3, 2, 6, 2]
Before: [0, 0, 0, 2]
6 0 0 1
After: [0, 0, 0, 2]
Before: [1, 2, 3, 3]
1 1 2 3
After: [1, 2, 3, 4]
Before: [3, 1, 2, 2]
10 0 2 3
After: [3, 1, 2, 2]
Before: [0, 2, 3, 3]
5 0 2 3
After: [0, 2, 3, 0]
Before: [1, 0, 3, 0]
10 2 2 2
After: [1, 0, 2, 0]
Before: [1, 0, 3, 3]
12 0 1 1
After: [1, 1, 3, 3]
Before: [0, 1, 3, 2]
6 0 0 1
After: [0, 0, 3, 2]
Before: [2, 1, 2, 2]
2 2 3 0
After: [3, 1, 2, 2]
Before: [1, 2, 1, 0]
4 1 1 0
After: [3, 2, 1, 0]
Before: [3, 1, 0, 3]
7 2 1 0
After: [1, 1, 0, 3]
Before: [0, 2, 0, 2]
6 0 0 3
After: [0, 2, 0, 0]
Before: [0, 0, 1, 3]
5 0 3 1
After: [0, 0, 1, 3]
Before: [1, 3, 2, 0]
10 1 2 2
After: [1, 3, 2, 0]
Before: [1, 0, 3, 3]
3 3 1 2
After: [1, 0, 3, 3]
Before: [0, 1, 1, 3]
6 0 0 2
After: [0, 1, 0, 3]
Before: [2, 0, 3, 1]
0 2 0 2
After: [2, 0, 2, 1]
Before: [1, 1, 0, 2]
7 2 1 0
After: [1, 1, 0, 2]
Before: [2, 1, 3, 3]
0 2 0 1
After: [2, 2, 3, 3]
Before: [0, 2, 2, 1]
6 0 0 0
After: [0, 2, 2, 1]
Before: [1, 0, 1, 0]
15 2 1 1
After: [1, 1, 1, 0]
Before: [2, 3, 0, 0]
4 2 3 0
After: [3, 3, 0, 0]
Before: [3, 1, 1, 2]
13 0 3 3
After: [3, 1, 1, 6]
Before: [2, 3, 2, 1]
11 0 2 1
After: [2, 4, 2, 1]
Before: [0, 0, 2, 1]
4 0 3 1
After: [0, 3, 2, 1]
Before: [2, 3, 1, 2]
13 1 3 3
After: [2, 3, 1, 6]
Before: [1, 3, 3, 2]
9 0 1 1
After: [1, 1, 3, 2]
Before: [2, 0, 3, 2]
13 2 3 0
After: [6, 0, 3, 2]
Before: [0, 0, 2, 0]
3 2 2 2
After: [0, 0, 2, 0]
Before: [2, 2, 3, 3]
0 2 1 3
After: [2, 2, 3, 2]
Before: [1, 0, 3, 2]
8 0 3 0
After: [3, 0, 3, 2]
Before: [0, 2, 3, 2]
6 0 0 1
After: [0, 0, 3, 2]
Before: [0, 0, 2, 0]
6 0 0 0
After: [0, 0, 2, 0]
Before: [0, 2, 3, 1]
0 2 1 3
After: [0, 2, 3, 2]
Before: [1, 2, 1, 2]
4 1 1 0
After: [3, 2, 1, 2]
Before: [2, 1, 1, 2]
2 0 3 0
After: [3, 1, 1, 2]
Before: [0, 2, 1, 3]
6 0 0 2
After: [0, 2, 0, 3]
Before: [1, 0, 0, 1]
15 3 1 2
After: [1, 0, 1, 1]
Before: [2, 3, 3, 0]
10 2 2 1
After: [2, 2, 3, 0]
Before: [0, 1, 3, 1]
10 2 2 3
After: [0, 1, 3, 2]
Before: [0, 0, 0, 2]
6 0 0 2
After: [0, 0, 0, 2]
Before: [1, 2, 2, 1]
8 0 2 2
After: [1, 2, 3, 1]
Before: [2, 3, 3, 3]
0 2 0 0
After: [2, 3, 3, 3]
Before: [0, 3, 1, 2]
9 2 1 2
After: [0, 3, 1, 2]
Before: [0, 1, 2, 3]
5 0 2 1
After: [0, 0, 2, 3]
Before: [0, 3, 0, 3]
6 0 0 0
After: [0, 3, 0, 3]
Before: [0, 2, 2, 1]
13 3 1 2
After: [0, 2, 2, 1]
Before: [1, 3, 1, 3]
3 3 1 0
After: [3, 3, 1, 3]
Before: [3, 3, 2, 3]
10 1 2 2
After: [3, 3, 2, 3]
Before: [2, 2, 0, 3]
4 1 1 0
After: [3, 2, 0, 3]
Before: [1, 1, 2, 3]
10 3 2 2
After: [1, 1, 2, 3]
Before: [0, 2, 2, 1]
11 2 2 3
After: [0, 2, 2, 4]
Before: [0, 1, 0, 2]
4 0 2 1
After: [0, 2, 0, 2]
Before: [3, 1, 3, 0]
10 2 2 1
After: [3, 2, 3, 0]
Before: [3, 3, 1, 1]
9 2 1 3
After: [3, 3, 1, 1]
Before: [1, 3, 0, 3]
3 3 3 3
After: [1, 3, 0, 3]
Before: [3, 0, 2, 1]
8 1 2 2
After: [3, 0, 2, 1]
Before: [1, 0, 1, 3]
3 3 1 2
After: [1, 0, 3, 3]
Before: [3, 2, 3, 2]
1 1 2 1
After: [3, 4, 3, 2]
Before: [1, 0, 0, 1]
12 0 1 3
After: [1, 0, 0, 1]
Before: [3, 0, 2, 3]
1 3 3 2
After: [3, 0, 9, 3]
Before: [3, 2, 3, 2]
13 2 3 3
After: [3, 2, 3, 6]
Before: [0, 0, 3, 3]
1 3 3 1
After: [0, 9, 3, 3]
Before: [0, 2, 1, 3]
1 1 3 3
After: [0, 2, 1, 6]
Before: [3, 1, 2, 3]
10 3 2 3
After: [3, 1, 2, 2]
Before: [1, 3, 2, 0]
9 0 1 1
After: [1, 1, 2, 0]
Before: [1, 0, 3, 1]
12 0 1 3
After: [1, 0, 3, 1]
Before: [0, 2, 2, 3]
11 1 2 1
After: [0, 4, 2, 3]
Before: [2, 0, 3, 0]
10 2 2 1
After: [2, 2, 3, 0]
Before: [2, 1, 1, 2]
8 1 3 3
After: [2, 1, 1, 3]
Before: [0, 0, 0, 0]
6 0 0 3
After: [0, 0, 0, 0]
Before: [0, 0, 1, 0]
6 0 0 3
After: [0, 0, 1, 0]
Before: [0, 1, 1, 0]
4 2 2 0
After: [3, 1, 1, 0]
Before: [1, 0, 2, 1]
12 0 1 0
After: [1, 0, 2, 1]
Before: [2, 3, 1, 3]
3 3 1 1
After: [2, 3, 1, 3]
Before: [1, 0, 0, 3]
3 3 1 0
After: [3, 0, 0, 3]
Before: [0, 3, 3, 3]
4 0 1 0
After: [1, 3, 3, 3]
Before: [1, 3, 2, 0]
3 2 2 3
After: [1, 3, 2, 2]
Before: [3, 1, 0, 2]
14 3 1 0
After: [3, 1, 0, 2]
Before: [0, 2, 3, 3]
0 2 1 1
After: [0, 2, 3, 3]
Before: [3, 2, 3, 2]
10 2 2 3
After: [3, 2, 3, 2]
Before: [1, 1, 2, 1]
8 2 1 3
After: [1, 1, 2, 3]
Before: [0, 3, 2, 3]
10 3 2 2
After: [0, 3, 2, 3]
Before: [0, 3, 1, 0]
6 0 0 2
After: [0, 3, 0, 0]
Before: [3, 0, 1, 1]
15 3 1 0
After: [1, 0, 1, 1]
Before: [1, 2, 3, 3]
0 2 1 1
After: [1, 2, 3, 3]
Before: [0, 0, 3, 1]
10 2 2 0
After: [2, 0, 3, 1]
Before: [0, 1, 3, 1]
6 0 0 1
After: [0, 0, 3, 1]
Before: [0, 2, 0, 1]
6 0 0 1
After: [0, 0, 0, 1]
Before: [1, 0, 2, 1]
15 3 1 2
After: [1, 0, 1, 1]
Before: [1, 2, 0, 3]
13 0 1 2
After: [1, 2, 2, 3]
Before: [1, 0, 2, 0]
12 0 1 2
After: [1, 0, 1, 0]
Before: [3, 3, 0, 2]
13 0 3 0
After: [6, 3, 0, 2]
Before: [1, 2, 2, 1]
11 1 2 1
After: [1, 4, 2, 1]
Before: [0, 3, 3, 0]
5 0 1 1
After: [0, 0, 3, 0]
Before: [1, 1, 2, 2]
14 3 1 0
After: [3, 1, 2, 2]
Before: [0, 2, 2, 2]
11 1 2 3
After: [0, 2, 2, 4]
Before: [2, 1, 3, 3]
1 3 3 1
After: [2, 9, 3, 3]
Before: [0, 2, 3, 0]
2 1 3 3
After: [0, 2, 3, 3]
Before: [1, 2, 0, 2]
4 1 1 1
After: [1, 3, 0, 2]
Before: [1, 0, 0, 1]
12 0 1 0
After: [1, 0, 0, 1]
Before: [1, 1, 0, 0]
7 3 1 2
After: [1, 1, 1, 0]
Before: [2, 1, 0, 0]
7 3 1 1
After: [2, 1, 0, 0]
Before: [2, 3, 0, 3]
3 3 1 0
After: [3, 3, 0, 3]
Before: [2, 0, 2, 1]
14 3 2 3
After: [2, 0, 2, 3]
Before: [2, 3, 2, 3]
11 0 2 2
After: [2, 3, 4, 3]
Before: [2, 0, 2, 1]
11 0 2 3
After: [2, 0, 2, 4]
Before: [3, 3, 3, 2]
13 2 3 0
After: [6, 3, 3, 2]
Before: [2, 2, 2, 1]
3 2 2 2
After: [2, 2, 2, 1]
Before: [0, 1, 2, 3]
10 3 2 3
After: [0, 1, 2, 2]
Before: [0, 3, 2, 3]
5 0 2 1
After: [0, 0, 2, 3]
Before: [1, 0, 0, 2]
12 0 1 3
After: [1, 0, 0, 1]
Before: [2, 1, 0, 1]
7 2 1 2
After: [2, 1, 1, 1]
Before: [2, 0, 2, 1]
15 3 1 3
After: [2, 0, 2, 1]
Before: [3, 2, 2, 1]
11 1 2 1
After: [3, 4, 2, 1]
Before: [0, 1, 1, 2]
14 3 1 0
After: [3, 1, 1, 2]
Before: [2, 2, 1, 2]
2 1 3 1
After: [2, 3, 1, 2]
Before: [1, 1, 2, 0]
1 0 3 1
After: [1, 3, 2, 0]
Before: [0, 0, 2, 2]
8 1 2 3
After: [0, 0, 2, 2]
Before: [1, 0, 3, 0]
12 0 1 3
After: [1, 0, 3, 1]
Before: [3, 0, 1, 2]
15 2 1 1
After: [3, 1, 1, 2]
Before: [0, 3, 1, 3]
6 0 0 1
After: [0, 0, 1, 3]
Before: [0, 1, 2, 0]
5 0 2 1
After: [0, 0, 2, 0]
Before: [0, 0, 3, 0]
6 0 0 2
After: [0, 0, 0, 0]
Before: [1, 1, 2, 0]
7 3 1 2
After: [1, 1, 1, 0]
Before: [0, 2, 2, 2]
11 2 2 0
After: [4, 2, 2, 2]
Before: [0, 2, 1, 3]
3 3 0 0
After: [3, 2, 1, 3]
Before: [1, 2, 3, 1]
0 2 1 3
After: [1, 2, 3, 2]
Before: [2, 1, 0, 2]
7 2 1 3
After: [2, 1, 0, 1]
Before: [3, 0, 1, 2]
13 0 3 0
After: [6, 0, 1, 2]
Before: [2, 2, 3, 2]
0 2 0 3
After: [2, 2, 3, 2]
Before: [0, 2, 1, 3]
5 0 3 1
After: [0, 0, 1, 3]
Before: [2, 1, 2, 0]
8 3 2 0
After: [2, 1, 2, 0]
Before: [2, 2, 0, 1]
9 3 1 2
After: [2, 2, 1, 1]
Before: [1, 1, 1, 0]
1 2 3 1
After: [1, 3, 1, 0]
Before: [2, 0, 2, 0]
5 1 0 3
After: [2, 0, 2, 0]
Before: [0, 2, 1, 2]
6 0 0 1
After: [0, 0, 1, 2]
Before: [0, 1, 1, 2]
6 0 0 3
After: [0, 1, 1, 0]
Before: [3, 0, 3, 3]
10 2 2 0
After: [2, 0, 3, 3]
Before: [0, 3, 2, 2]
1 1 2 2
After: [0, 3, 6, 2]
Before: [3, 3, 2, 0]
10 1 2 3
After: [3, 3, 2, 2]
Before: [2, 3, 1, 3]
8 2 3 2
After: [2, 3, 3, 3]
Before: [1, 0, 0, 1]
12 0 1 1
After: [1, 1, 0, 1]
Before: [1, 0, 0, 2]
12 0 1 0
After: [1, 0, 0, 2]
Before: [1, 3, 1, 2]
13 1 3 0
After: [6, 3, 1, 2]
Before: [3, 1, 0, 2]
7 2 1 2
After: [3, 1, 1, 2]
Before: [3, 0, 1, 1]
5 1 0 2
After: [3, 0, 0, 1]
Before: [3, 1, 2, 0]
11 2 2 2
After: [3, 1, 4, 0]
Before: [3, 3, 3, 2]
0 2 3 2
After: [3, 3, 2, 2]
Before: [1, 3, 3, 3]
10 2 2 1
After: [1, 2, 3, 3]
Before: [0, 0, 1, 0]
15 2 1 1
After: [0, 1, 1, 0]
Before: [3, 2, 1, 1]
9 3 1 3
After: [3, 2, 1, 1]
Before: [0, 3, 1, 0]
9 2 1 2
After: [0, 3, 1, 0]
Before: [0, 1, 3, 3]
10 2 2 3
After: [0, 1, 3, 2]
Before: [1, 2, 1, 0]
2 1 3 3
After: [1, 2, 1, 3]
Before: [0, 1, 3, 2]
14 3 1 0
After: [3, 1, 3, 2]
Before: [3, 1, 2, 0]
1 1 2 1
After: [3, 2, 2, 0]
Before: [1, 0, 0, 0]
12 0 1 3
After: [1, 0, 0, 1]
Before: [0, 1, 2, 1]
1 1 3 1
After: [0, 3, 2, 1]
Before: [3, 2, 2, 1]
11 2 2 3
After: [3, 2, 2, 4]
Before: [3, 0, 2, 0]
8 1 2 1
After: [3, 2, 2, 0]
Before: [1, 0, 1, 3]
15 2 1 0
After: [1, 0, 1, 3]
Before: [0, 2, 2, 2]
8 0 2 2
After: [0, 2, 2, 2]
Before: [3, 0, 2, 1]
11 2 2 2
After: [3, 0, 4, 1]
Before: [3, 2, 3, 1]
14 3 2 2
After: [3, 2, 3, 1]
Before: [0, 2, 1, 1]
6 0 0 1
After: [0, 0, 1, 1]
Before: [3, 2, 0, 1]
9 3 1 2
After: [3, 2, 1, 1]
Before: [2, 0, 3, 1]
15 3 1 3
After: [2, 0, 3, 1]
Before: [0, 1, 0, 3]
6 0 0 3
After: [0, 1, 0, 0]
Before: [1, 0, 2, 3]
1 0 2 1
After: [1, 2, 2, 3]
Before: [1, 3, 3, 2]
0 2 3 2
After: [1, 3, 2, 2]
Before: [0, 0, 1, 3]
6 0 0 3
After: [0, 0, 1, 0]
Before: [3, 3, 2, 0]
11 2 2 0
After: [4, 3, 2, 0]
Before: [0, 0, 0, 3]
4 0 2 2
After: [0, 0, 2, 3]
Before: [0, 3, 2, 2]
11 2 2 0
After: [4, 3, 2, 2]
Before: [2, 3, 1, 3]
1 3 3 0
After: [9, 3, 1, 3]
Before: [2, 0, 3, 3]
0 2 0 2
After: [2, 0, 2, 3]
Before: [2, 3, 0, 2]
4 2 3 2
After: [2, 3, 3, 2]
Before: [0, 2, 3, 3]
5 0 1 2
After: [0, 2, 0, 3]
Before: [1, 0, 3, 1]
10 2 2 2
After: [1, 0, 2, 1]
Before: [2, 0, 0, 3]
1 0 3 3
After: [2, 0, 0, 6]
Before: [1, 3, 3, 0]
9 0 1 1
After: [1, 1, 3, 0]
Before: [0, 3, 1, 2]
6 0 0 3
After: [0, 3, 1, 0]
Before: [0, 0, 2, 0]
11 2 2 2
After: [0, 0, 4, 0]
Before: [2, 1, 3, 2]
13 2 3 0
After: [6, 1, 3, 2]
Before: [1, 0, 3, 2]
12 0 1 2
After: [1, 0, 1, 2]
Before: [3, 1, 3, 2]
13 2 3 3
After: [3, 1, 3, 6]
Before: [0, 3, 2, 0]
4 0 1 3
After: [0, 3, 2, 1]
Before: [3, 3, 2, 2]
10 0 2 2
After: [3, 3, 2, 2]
Before: [0, 2, 2, 0]
8 0 2 1
After: [0, 2, 2, 0]
Before: [0, 0, 0, 3]
5 0 3 2
After: [0, 0, 0, 3]
Before: [2, 2, 3, 1]
0 2 0 2
After: [2, 2, 2, 1]
Before: [1, 0, 2, 1]
14 3 2 3
After: [1, 0, 2, 3]
Before: [1, 0, 2, 2]
12 0 1 0
After: [1, 0, 2, 2]
Before: [3, 0, 3, 0]
10 2 2 3
After: [3, 0, 3, 2]
Before: [0, 1, 0, 1]
7 2 1 0
After: [1, 1, 0, 1]
Before: [0, 1, 0, 0]
7 2 1 3
After: [0, 1, 0, 1]
Before: [1, 1, 0, 3]
1 3 3 1
After: [1, 9, 0, 3]
Before: [3, 0, 1, 0]
15 2 1 1
After: [3, 1, 1, 0]
Before: [0, 3, 0, 3]
5 0 3 0
After: [0, 3, 0, 3]
Before: [3, 1, 0, 1]
7 2 1 3
After: [3, 1, 0, 1]
Before: [0, 3, 3, 1]
5 0 3 2
After: [0, 3, 0, 1]
Before: [1, 1, 2, 1]
14 3 2 3
After: [1, 1, 2, 3]
Before: [1, 2, 2, 0]
11 1 2 1
After: [1, 4, 2, 0]
Before: [2, 2, 1, 3]
1 1 3 2
After: [2, 2, 6, 3]
Before: [0, 2, 1, 0]
6 0 0 0
After: [0, 2, 1, 0]
Before: [0, 0, 3, 3]
6 0 0 3
After: [0, 0, 3, 0]
Before: [0, 0, 3, 1]
14 3 2 0
After: [3, 0, 3, 1]
Before: [0, 0, 2, 1]
6 0 0 2
After: [0, 0, 0, 1]
Before: [1, 0, 2, 1]
14 3 2 2
After: [1, 0, 3, 1]
Before: [0, 2, 2, 1]
11 2 2 0
After: [4, 2, 2, 1]
Before: [3, 0, 3, 3]
10 2 2 1
After: [3, 2, 3, 3]
Before: [2, 0, 1, 0]
2 0 3 0
After: [3, 0, 1, 0]
Before: [3, 3, 2, 3]
3 3 1 0
After: [3, 3, 2, 3]
Before: [1, 3, 2, 1]
14 3 2 2
After: [1, 3, 3, 1]
Before: [3, 0, 3, 2]
0 2 3 1
After: [3, 2, 3, 2]
Before: [0, 0, 0, 1]
15 3 1 2
After: [0, 0, 1, 1]
Before: [1, 1, 3, 1]
14 3 2 0
After: [3, 1, 3, 1]
Before: [0, 2, 3, 2]
5 0 1 1
After: [0, 0, 3, 2]
Before: [3, 1, 3, 3]
1 2 3 3
After: [3, 1, 3, 9]
Before: [2, 0, 1, 1]
1 2 3 2
After: [2, 0, 3, 1]
Before: [1, 0, 2, 3]
10 3 2 2
After: [1, 0, 2, 3]
Before: [0, 2, 1, 2]
4 0 3 2
After: [0, 2, 3, 2]
Before: [0, 3, 2, 0]
3 2 0 0
After: [2, 3, 2, 0]
Before: [3, 2, 2, 2]
11 1 2 3
After: [3, 2, 2, 4]
Before: [1, 0, 1, 2]
15 2 1 3
After: [1, 0, 1, 1]
Before: [2, 1, 1, 2]
14 3 1 0
After: [3, 1, 1, 2]
Before: [1, 3, 2, 3]
11 2 2 3
After: [1, 3, 2, 4]
Before: [0, 2, 2, 1]
3 2 2 3
After: [0, 2, 2, 2]
Before: [1, 0, 2, 3]
12 0 1 1
After: [1, 1, 2, 3]
Before: [1, 3, 0, 3]
8 2 3 1
After: [1, 3, 0, 3]
Before: [0, 2, 2, 3]
10 3 2 2
After: [0, 2, 2, 3]
Before: [0, 1, 3, 2]
5 0 3 1
After: [0, 0, 3, 2]
Before: [3, 1, 1, 2]
8 1 3 1
After: [3, 3, 1, 2]
Before: [2, 3, 1, 3]
1 0 3 2
After: [2, 3, 6, 3]
Before: [2, 0, 3, 1]
14 3 2 0
After: [3, 0, 3, 1]
Before: [1, 2, 2, 1]
13 0 1 0
After: [2, 2, 2, 1]
Before: [1, 2, 3, 3]
10 2 2 2
After: [1, 2, 2, 3]
Before: [3, 1, 0, 0]
7 2 1 3
After: [3, 1, 0, 1]
Before: [2, 3, 2, 2]
13 1 3 0
After: [6, 3, 2, 2]
Before: [0, 1, 3, 3]
10 2 2 2
After: [0, 1, 2, 3]
Before: [2, 1, 2, 2]
14 3 1 0
After: [3, 1, 2, 2]
Before: [2, 3, 3, 2]
0 2 3 3
After: [2, 3, 3, 2]
Before: [2, 3, 0, 1]
4 2 3 1
After: [2, 3, 0, 1]
Before: [0, 1, 2, 0]
4 0 3 1
After: [0, 3, 2, 0]
Before: [0, 1, 2, 0]
6 0 0 2
After: [0, 1, 0, 0]
Before: [2, 1, 0, 2]
2 0 3 3
After: [2, 1, 0, 3]
Before: [0, 3, 3, 0]
4 0 2 1
After: [0, 2, 3, 0]
Before: [0, 1, 3, 3]
3 3 0 0
After: [3, 1, 3, 3]
Before: [3, 1, 1, 0]
7 3 1 0
After: [1, 1, 1, 0]
Before: [1, 3, 1, 1]
9 0 1 1
After: [1, 1, 1, 1]
Before: [0, 2, 0, 1]
9 3 1 2
After: [0, 2, 1, 1]
Before: [0, 0, 2, 3]
11 2 2 3
After: [0, 0, 2, 4]
Before: [1, 2, 2, 1]
1 0 2 1
After: [1, 2, 2, 1]
Before: [0, 2, 2, 2]
11 3 2 2
After: [0, 2, 4, 2]
Before: [0, 1, 1, 0]
7 3 1 3
After: [0, 1, 1, 1]
Before: [2, 3, 2, 0]
11 2 2 3
After: [2, 3, 2, 4]
Before: [2, 0, 2, 0]
2 0 3 1
After: [2, 3, 2, 0]
Before: [0, 3, 3, 3]
6 0 0 0
After: [0, 3, 3, 3]
Before: [1, 1, 3, 1]
8 1 2 1
After: [1, 3, 3, 1]
Before: [2, 3, 0, 3]
8 2 3 1
After: [2, 3, 0, 3]
Before: [2, 2, 3, 2]
0 2 3 2
After: [2, 2, 2, 2]
Before: [1, 2, 1, 1]
13 0 1 1
After: [1, 2, 1, 1]
Before: [2, 3, 2, 2]
2 2 3 1
After: [2, 3, 2, 2]
Before: [0, 1, 2, 0]
3 2 0 2
After: [0, 1, 2, 0]
Before: [1, 3, 0, 3]
9 0 1 0
After: [1, 3, 0, 3]
Before: [1, 1, 0, 3]
7 2 1 1
After: [1, 1, 0, 3]
Before: [1, 0, 2, 1]
12 0 1 1
After: [1, 1, 2, 1]
Before: [0, 0, 2, 0]
8 0 2 1
After: [0, 2, 2, 0]
Before: [0, 2, 1, 0]
5 0 1 3
After: [0, 2, 1, 0]
Before: [1, 2, 3, 0]
8 0 2 0
After: [3, 2, 3, 0]
Before: [1, 0, 2, 2]
12 0 1 2
After: [1, 0, 1, 2]
Before: [2, 3, 2, 0]
2 2 3 1
After: [2, 3, 2, 0]
Before: [1, 3, 3, 2]
13 1 3 1
After: [1, 6, 3, 2]
Before: [2, 0, 2, 1]
15 3 1 1
After: [2, 1, 2, 1]
Before: [0, 3, 1, 3]
9 2 1 2
After: [0, 3, 1, 3]
Before: [3, 3, 1, 0]
4 3 2 1
After: [3, 2, 1, 0]
Before: [2, 1, 0, 2]
7 2 1 2
After: [2, 1, 1, 2]
Before: [0, 2, 2, 3]
4 0 1 2
After: [0, 2, 1, 3]
Before: [2, 0, 2, 1]
5 1 0 0
After: [0, 0, 2, 1]
Before: [2, 0, 3, 0]
0 2 0 1
After: [2, 2, 3, 0]
Before: [1, 3, 2, 3]
9 0 1 2
After: [1, 3, 1, 3]
Before: [3, 1, 1, 3]
3 3 1 2
After: [3, 1, 3, 3]
Before: [0, 1, 0, 2]
14 3 1 2
After: [0, 1, 3, 2]
Before: [3, 0, 1, 2]
15 2 1 0
After: [1, 0, 1, 2]
Before: [2, 2, 2, 3]
10 3 2 0
After: [2, 2, 2, 3]
Before: [1, 2, 0, 1]
13 3 1 0
After: [2, 2, 0, 1]
Before: [0, 3, 0, 3]
6 0 0 2
After: [0, 3, 0, 3]
Before: [0, 2, 2, 1]
14 3 2 3
After: [0, 2, 2, 3]
Before: [2, 1, 0, 3]
7 2 1 3
After: [2, 1, 0, 1]
Before: [0, 1, 0, 3]
7 2 1 0
After: [1, 1, 0, 3]
Before: [3, 0, 2, 3]
1 2 3 1
After: [3, 6, 2, 3]
Before: [0, 2, 3, 2]
5 0 3 3
After: [0, 2, 3, 0]
Before: [1, 3, 3, 2]
13 1 3 0
After: [6, 3, 3, 2]
Before: [1, 1, 1, 3]
1 3 3 2
After: [1, 1, 9, 3]
Before: [3, 2, 2, 0]
4 1 1 0
After: [3, 2, 2, 0]
Before: [1, 1, 3, 2]
0 2 3 1
After: [1, 2, 3, 2]
Before: [1, 0, 2, 0]
12 0 1 1
After: [1, 1, 2, 0]
Before: [0, 0, 2, 1]
14 3 2 2
After: [0, 0, 3, 1]
Before: [3, 1, 3, 0]
4 3 2 1
After: [3, 2, 3, 0]
Before: [2, 0, 0, 3]
1 0 2 0
After: [4, 0, 0, 3]
Before: [1, 2, 3, 0]
13 0 1 1
After: [1, 2, 3, 0]
Before: [0, 1, 3, 0]
7 3 1 2
After: [0, 1, 1, 0]
Before: [0, 1, 2, 0]
2 2 3 0
After: [3, 1, 2, 0]
Before: [1, 0, 3, 2]
0 2 3 3
After: [1, 0, 3, 2]
Before: [1, 3, 2, 3]
1 1 3 2
After: [1, 3, 9, 3]
Before: [1, 0, 2, 3]
12 0 1 3
After: [1, 0, 2, 1]
Before: [3, 2, 2, 2]
2 1 3 3
After: [3, 2, 2, 3]
Before: [0, 1, 0, 1]
7 2 1 3
After: [0, 1, 0, 1]
Before: [3, 0, 2, 3]
10 0 2 0
After: [2, 0, 2, 3]
Before: [0, 3, 3, 3]
5 0 3 1
After: [0, 0, 3, 3]
Before: [2, 1, 3, 1]
0 2 0 2
After: [2, 1, 2, 1]
Before: [2, 1, 2, 1]
3 2 0 2
After: [2, 1, 2, 1]
Before: [1, 2, 0, 0]
2 1 3 3
After: [1, 2, 0, 3]
Before: [3, 0, 0, 1]
15 3 1 0
After: [1, 0, 0, 1]
Before: [2, 2, 3, 0]
10 2 2 2
After: [2, 2, 2, 0]
Before: [1, 1, 3, 0]
8 0 2 3
After: [1, 1, 3, 3]
Before: [2, 1, 2, 2]
14 3 1 2
After: [2, 1, 3, 2]
Before: [3, 1, 2, 2]
11 3 2 3
After: [3, 1, 2, 4]
Before: [1, 1, 3, 0]
10 2 2 3
After: [1, 1, 3, 2]
Before: [1, 2, 0, 1]
9 3 1 0
After: [1, 2, 0, 1]
Before: [1, 3, 3, 2]
13 1 3 2
After: [1, 3, 6, 2]
Before: [3, 3, 3, 2]
13 2 3 3
After: [3, 3, 3, 6]
Before: [2, 1, 0, 2]
7 2 1 1
After: [2, 1, 0, 2]
Before: [3, 2, 3, 1]
0 2 1 2
After: [3, 2, 2, 1]
Before: [0, 0, 1, 1]
5 0 3 2
After: [0, 0, 0, 1]
Before: [0, 1, 1, 0]
5 0 1 1
After: [0, 0, 1, 0]
Before: [3, 1, 0, 1]
7 2 1 0
After: [1, 1, 0, 1]
Before: [1, 1, 1, 3]
8 2 3 3
After: [1, 1, 1, 3]
Before: [1, 0, 2, 1]
12 0 1 2
After: [1, 0, 1, 1]
Before: [2, 2, 1, 0]
2 0 3 3
After: [2, 2, 1, 3]
Before: [3, 0, 2, 2]
3 2 2 2
After: [3, 0, 2, 2]
Before: [0, 2, 0, 0]
2 1 3 3
After: [0, 2, 0, 3]
Before: [2, 2, 2, 1]
14 3 2 1
After: [2, 3, 2, 1]
Before: [0, 1, 2, 3]
11 2 2 1
After: [0, 4, 2, 3]
Before: [3, 2, 0, 0]
4 1 1 1
After: [3, 3, 0, 0]
Before: [1, 1, 3, 3]
8 1 3 1
After: [1, 3, 3, 3]
Before: [1, 0, 3, 2]
8 0 2 3
After: [1, 0, 3, 3]
Before: [3, 1, 2, 3]
11 2 2 0
After: [4, 1, 2, 3]
Before: [3, 1, 2, 1]
10 0 2 1
After: [3, 2, 2, 1]
Before: [3, 1, 2, 1]
3 2 2 0
After: [2, 1, 2, 1]
Before: [0, 1, 0, 0]
6 0 0 2
After: [0, 1, 0, 0]
Before: [1, 0, 1, 2]
8 2 3 0
After: [3, 0, 1, 2]
Before: [3, 0, 3, 2]
13 0 3 1
After: [3, 6, 3, 2]
Before: [1, 2, 2, 1]
11 1 2 3
After: [1, 2, 2, 4]
Before: [0, 2, 0, 3]
6 0 0 3
After: [0, 2, 0, 0]
Before: [1, 0, 3, 3]
12 0 1 2
After: [1, 0, 1, 3]
Before: [0, 1, 2, 2]
6 0 0 3
After: [0, 1, 2, 0]
Before: [2, 2, 0, 0]
2 1 3 3
After: [2, 2, 0, 3]
Before: [0, 1, 3, 2]
6 0 0 0
After: [0, 1, 3, 2]
Before: [3, 0, 3, 1]
15 3 1 1
After: [3, 1, 3, 1]
Before: [0, 0, 2, 1]
14 3 2 3
After: [0, 0, 2, 3]
Before: [0, 3, 0, 1]
6 0 0 3
After: [0, 3, 0, 0]
Before: [1, 3, 1, 1]
9 2 1 1
After: [1, 1, 1, 1]
Before: [1, 0, 1, 0]
12 0 1 3
After: [1, 0, 1, 1]
Before: [3, 0, 1, 1]
1 2 3 3
After: [3, 0, 1, 3]
Before: [3, 3, 3, 1]
14 3 2 0
After: [3, 3, 3, 1]
Before: [2, 2, 1, 1]
9 3 1 3
After: [2, 2, 1, 1]
Before: [1, 1, 3, 2]
14 3 1 2
After: [1, 1, 3, 2]
Before: [1, 0, 2, 2]
1 0 2 3
After: [1, 0, 2, 2]
Before: [1, 2, 3, 3]
4 1 1 1
After: [1, 3, 3, 3]
Before: [2, 2, 3, 1]
9 3 1 0
After: [1, 2, 3, 1]
Before: [2, 2, 3, 0]
0 2 0 0
After: [2, 2, 3, 0]
Before: [0, 1, 3, 1]
10 2 2 1
After: [0, 2, 3, 1]
Before: [3, 1, 2, 3]
8 2 1 1
After: [3, 3, 2, 3]
Before: [1, 0, 0, 3]
12 0 1 0
After: [1, 0, 0, 3]
Before: [1, 0, 1, 0]
12 0 1 1
After: [1, 1, 1, 0]
Before: [2, 2, 2, 2]
2 0 3 1
After: [2, 3, 2, 2]
Before: [2, 1, 3, 0]
7 3 1 3
After: [2, 1, 3, 1]
Before: [3, 2, 2, 0]
11 1 2 2
After: [3, 2, 4, 0]
Before: [1, 0, 1, 3]
3 3 0 2
After: [1, 0, 3, 3]
Before: [3, 3, 3, 1]
10 2 2 0
After: [2, 3, 3, 1]
Before: [2, 0, 1, 1]
15 2 1 0
After: [1, 0, 1, 1]
Before: [2, 0, 2, 2]
11 2 2 3
After: [2, 0, 2, 4]
Before: [0, 0, 1, 1]
15 3 1 0
After: [1, 0, 1, 1]
Before: [3, 2, 3, 0]
2 1 3 3
After: [3, 2, 3, 3]
Before: [2, 1, 1, 2]
1 0 2 3
After: [2, 1, 1, 4]
Before: [3, 2, 3, 1]
10 2 2 1
After: [3, 2, 3, 1]
Before: [2, 2, 3, 2]
13 2 3 0
After: [6, 2, 3, 2]
Before: [1, 3, 2, 1]
14 3 2 0
After: [3, 3, 2, 1]
Before: [1, 0, 0, 3]
8 0 3 3
After: [1, 0, 0, 3]
Before: [3, 1, 1, 2]
14 3 1 2
After: [3, 1, 3, 2]
Before: [2, 3, 0, 3]
1 3 3 3
After: [2, 3, 0, 9]
Before: [0, 3, 1, 3]
3 3 3 3
After: [0, 3, 1, 3]
Before: [0, 2, 0, 1]
9 3 1 0
After: [1, 2, 0, 1]
Before: [1, 2, 2, 1]
1 0 2 3
After: [1, 2, 2, 2]
Before: [2, 0, 1, 0]
15 2 1 3
After: [2, 0, 1, 1]
Before: [0, 1, 2, 3]
10 3 2 2
After: [0, 1, 2, 3]
Before: [1, 1, 3, 2]
14 3 1 0
After: [3, 1, 3, 2]
Before: [0, 0, 1, 3]
15 2 1 0
After: [1, 0, 1, 3]
Before: [0, 1, 0, 1]
5 0 1 0
After: [0, 1, 0, 1]
Before: [3, 0, 3, 2]
13 0 3 3
After: [3, 0, 3, 6]
Before: [2, 3, 3, 1]
14 3 2 1
After: [2, 3, 3, 1]
Before: [3, 0, 3, 1]
15 3 1 0
After: [1, 0, 3, 1]
Before: [0, 2, 2, 3]
5 0 1 1
After: [0, 0, 2, 3]
Before: [0, 3, 1, 0]
4 0 3 0
After: [3, 3, 1, 0]
Before: [1, 0, 2, 3]
12 0 1 2
After: [1, 0, 1, 3]
Before: [3, 0, 1, 1]
15 3 1 3
After: [3, 0, 1, 1]
Before: [0, 3, 3, 3]
5 0 2 2
After: [0, 3, 0, 3]
Before: [2, 0, 0, 3]
4 1 2 3
After: [2, 0, 0, 2]
Before: [1, 3, 1, 0]
9 0 1 3
After: [1, 3, 1, 1]
Before: [0, 0, 1, 2]
15 2 1 0
After: [1, 0, 1, 2]
Before: [1, 0, 0, 3]
8 0 3 0
After: [3, 0, 0, 3]
Before: [0, 2, 3, 2]
10 2 2 0
After: [2, 2, 3, 2]
Before: [0, 1, 0, 2]
5 0 3 0
After: [0, 1, 0, 2]
Before: [0, 0, 3, 0]
5 0 2 0
After: [0, 0, 3, 0]
Before: [3, 2, 2, 2]
13 0 3 0
After: [6, 2, 2, 2]
Before: [3, 0, 2, 1]
4 2 1 1
After: [3, 3, 2, 1]
Before: [1, 3, 3, 1]
9 0 1 2
After: [1, 3, 1, 1]
Before: [1, 0, 3, 3]
3 3 0 2
After: [1, 0, 3, 3]
Before: [0, 1, 0, 2]
14 3 1 1
After: [0, 3, 0, 2]
Before: [0, 0, 2, 3]
4 2 1 3
After: [0, 0, 2, 3]
Before: [1, 2, 2, 3]
13 0 1 3
After: [1, 2, 2, 2]
Before: [1, 1, 2, 0]
8 0 2 1
After: [1, 3, 2, 0]
Before: [0, 0, 2, 2]
6 0 0 1
After: [0, 0, 2, 2]
Before: [2, 2, 2, 3]
3 2 2 3
After: [2, 2, 2, 2]
Before: [3, 0, 2, 2]
13 0 3 2
After: [3, 0, 6, 2]
Before: [0, 2, 0, 2]
5 0 1 3
After: [0, 2, 0, 0]
Before: [2, 0, 0, 3]
3 3 3 3
After: [2, 0, 0, 3]
Before: [1, 3, 2, 1]
10 1 2 0
After: [2, 3, 2, 1]
Before: [0, 1, 3, 2]
0 2 3 0
After: [2, 1, 3, 2]
Before: [2, 0, 1, 3]
1 0 3 1
After: [2, 6, 1, 3]
Before: [0, 3, 1, 2]
6 0 0 2
After: [0, 3, 0, 2]
Before: [3, 1, 3, 0]
10 2 2 2
After: [3, 1, 2, 0]
Before: [3, 1, 3, 2]
14 3 1 1
After: [3, 3, 3, 2]
Before: [0, 1, 3, 2]
0 2 3 3
After: [0, 1, 3, 2]
Before: [0, 1, 2, 1]
11 2 2 3
After: [0, 1, 2, 4]
Before: [0, 2, 1, 0]
4 2 2 0
After: [3, 2, 1, 0]
Before: [1, 1, 3, 1]
14 3 2 1
After: [1, 3, 3, 1]
Before: [3, 3, 3, 3]
1 1 3 3
After: [3, 3, 3, 9]
Before: [2, 3, 1, 1]
9 2 1 0
After: [1, 3, 1, 1]
Before: [2, 1, 3, 2]
2 0 3 3
After: [2, 1, 3, 3]
Before: [0, 1, 0, 2]
8 1 3 3
After: [0, 1, 0, 3]
Before: [2, 3, 3, 2]
13 2 3 2
After: [2, 3, 6, 2]
Before: [2, 3, 1, 2]
9 2 1 2
After: [2, 3, 1, 2]
Before: [3, 2, 2, 0]
2 1 3 2
After: [3, 2, 3, 0]
Before: [3, 2, 1, 1]
13 3 1 0
After: [2, 2, 1, 1]
Before: [0, 0, 1, 3]
15 2 1 1
After: [0, 1, 1, 3]
Before: [1, 3, 2, 1]
9 0 1 0
After: [1, 3, 2, 1]
Before: [0, 0, 1, 2]
5 0 2 0
After: [0, 0, 1, 2]
Before: [0, 1, 3, 1]
6 0 0 3
After: [0, 1, 3, 0]
Before: [3, 1, 3, 0]
7 3 1 2
After: [3, 1, 1, 0]
Before: [0, 3, 2, 1]
1 1 2 1
After: [0, 6, 2, 1]
Before: [0, 2, 1, 3]
3 3 3 3
After: [0, 2, 1, 3]
Before: [0, 0, 3, 3]
5 0 2 2
After: [0, 0, 0, 3]
Before: [0, 2, 2, 0]
3 2 2 3
After: [0, 2, 2, 2]
Before: [2, 0, 1, 0]
15 2 1 2
After: [2, 0, 1, 0]
Before: [3, 2, 2, 3]
3 3 3 0
After: [3, 2, 2, 3]
Before: [1, 0, 3, 0]
12 0 1 2
After: [1, 0, 1, 0]
Before: [0, 1, 2, 0]
7 3 1 1
After: [0, 1, 2, 0]
Before: [2, 0, 3, 1]
0 2 0 1
After: [2, 2, 3, 1]
Before: [3, 3, 2, 2]
11 2 2 2
After: [3, 3, 4, 2]
Before: [0, 0, 2, 3]
6 0 0 0
After: [0, 0, 2, 3]
Before: [0, 3, 0, 2]
6 0 0 2
After: [0, 3, 0, 2]
Before: [2, 1, 0, 2]
2 0 3 2
After: [2, 1, 3, 2]
Before: [0, 3, 1, 0]
5 0 1 2
After: [0, 3, 0, 0]
Before: [3, 1, 1, 1]
1 1 3 2
After: [3, 1, 3, 1]
Before: [2, 0, 3, 1]
0 2 0 3
After: [2, 0, 3, 2]
Before: [1, 0, 1, 1]
15 3 1 3
After: [1, 0, 1, 1]
Before: [1, 0, 2, 1]
12 0 1 3
After: [1, 0, 2, 1]
Before: [3, 2, 2, 3]
11 2 2 1
After: [3, 4, 2, 3]
Before: [1, 3, 0, 0]
9 0 1 1
After: [1, 1, 0, 0]
Before: [2, 1, 2, 0]
7 3 1 0
After: [1, 1, 2, 0]
Before: [0, 3, 0, 3]
3 3 1 1
After: [0, 3, 0, 3]
Before: [0, 1, 1, 3]
8 2 3 2
After: [0, 1, 3, 3]
Before: [2, 1, 0, 3]
7 2 1 1
After: [2, 1, 0, 3]
Before: [2, 2, 3, 1]
0 2 1 3
After: [2, 2, 3, 2]
Before: [1, 0, 1, 1]
12 0 1 1
After: [1, 1, 1, 1]
Before: [0, 3, 1, 0]
9 2 1 3
After: [0, 3, 1, 1]
Before: [1, 0, 3, 0]
12 0 1 0
After: [1, 0, 3, 0]
Before: [0, 0, 3, 2]
4 0 2 1
After: [0, 2, 3, 2]
Before: [0, 0, 1, 1]
15 2 1 2
After: [0, 0, 1, 1]
Before: [2, 2, 2, 2]
2 2 3 0
After: [3, 2, 2, 2]
Before: [0, 0, 1, 1]
15 3 1 3
After: [0, 0, 1, 1]
Before: [1, 0, 3, 3]
3 3 3 1
After: [1, 3, 3, 3]
Before: [2, 0, 2, 2]
2 2 3 3
After: [2, 0, 2, 3]
Before: [0, 1, 0, 1]
7 2 1 1
After: [0, 1, 0, 1]
Before: [0, 2, 3, 1]
10 2 2 3
After: [0, 2, 3, 2]
Before: [1, 0, 1, 2]
12 0 1 2
After: [1, 0, 1, 2]
Before: [3, 1, 2, 0]
1 1 3 3
After: [3, 1, 2, 3]
Before: [0, 3, 1, 0]
9 2 1 0
After: [1, 3, 1, 0]
Before: [2, 0, 1, 2]
15 2 1 3
After: [2, 0, 1, 1]
Before: [2, 3, 1, 0]
9 2 1 1
After: [2, 1, 1, 0]
Before: [1, 0, 0, 0]
12 0 1 1
After: [1, 1, 0, 0]
Before: [2, 2, 3, 3]
3 3 3 2
After: [2, 2, 3, 3]
Before: [3, 3, 1, 1]
1 2 3 2
After: [3, 3, 3, 1]
Before: [3, 3, 2, 2]
13 0 3 0
After: [6, 3, 2, 2]
Before: [0, 1, 1, 0]
4 1 2 2
After: [0, 1, 3, 0]
Before: [1, 3, 2, 0]
2 2 3 3
After: [1, 3, 2, 3]
Before: [0, 3, 1, 1]
9 2 1 1
After: [0, 1, 1, 1]
Before: [0, 2, 3, 1]
5 0 1 0
After: [0, 2, 3, 1]
Before: [0, 2, 2, 2]
5 0 3 3
After: [0, 2, 2, 0]
Before: [0, 3, 3, 3]
10 2 2 2
After: [0, 3, 2, 3]
Before: [1, 3, 1, 3]
3 3 1 3
After: [1, 3, 1, 3]
Before: [3, 3, 3, 2]
0 2 3 1
After: [3, 2, 3, 2]
Before: [3, 3, 0, 1]
4 2 3 0
After: [3, 3, 0, 1]
Before: [0, 0, 0, 3]
6 0 0 3
After: [0, 0, 0, 0]
Before: [3, 0, 2, 1]
14 3 2 3
After: [3, 0, 2, 3]
Before: [1, 0, 3, 2]
13 2 3 2
After: [1, 0, 6, 2]
Before: [0, 1, 2, 0]
7 3 1 2
After: [0, 1, 1, 0]
Before: [3, 3, 2, 2]
11 3 2 1
After: [3, 4, 2, 2]
Before: [2, 2, 2, 3]
1 3 2 3
After: [2, 2, 2, 6]
Before: [2, 0, 2, 2]
11 3 2 1
After: [2, 4, 2, 2]
Before: [0, 2, 3, 2]
0 2 1 1
After: [0, 2, 3, 2]
Before: [1, 0, 2, 0]
12 0 1 3
After: [1, 0, 2, 1]
Before: [3, 3, 1, 2]
13 0 3 3
After: [3, 3, 1, 6]
Before: [3, 2, 3, 1]
9 3 1 2
After: [3, 2, 1, 1]
Before: [2, 2, 2, 0]
11 2 2 3
After: [2, 2, 2, 4]
Before: [1, 0, 1, 1]
4 2 2 1
After: [1, 3, 1, 1]
Before: [2, 2, 2, 1]
14 3 2 2
After: [2, 2, 3, 1]
Before: [1, 1, 2, 2]
11 3 2 0
After: [4, 1, 2, 2]
Before: [2, 2, 3, 2]
0 2 0 2
After: [2, 2, 2, 2]
Before: [1, 1, 0, 1]
1 1 3 0
After: [3, 1, 0, 1]
Before: [2, 3, 1, 0]
2 0 3 3
After: [2, 3, 1, 3]
Before: [1, 3, 3, 1]
9 0 1 1
After: [1, 1, 3, 1]
Before: [3, 3, 2, 2]
10 1 2 1
After: [3, 2, 2, 2]
Before: [0, 2, 3, 0]
0 2 1 2
After: [0, 2, 2, 0]
Before: [0, 3, 3, 1]
6 0 0 0
After: [0, 3, 3, 1]
Before: [3, 2, 2, 2]
2 2 3 0
After: [3, 2, 2, 2]
Before: [1, 0, 0, 2]
12 0 1 1
After: [1, 1, 0, 2]
Before: [1, 0, 0, 2]
12 0 1 2
After: [1, 0, 1, 2]
Before: [0, 2, 1, 2]
5 0 3 1
After: [0, 0, 1, 2]
Before: [0, 0, 3, 3]
5 0 3 2
After: [0, 0, 0, 3]
Before: [0, 1, 1, 0]
1 2 3 0
After: [3, 1, 1, 0]
Before: [0, 1, 1, 2]
5 0 3 3
After: [0, 1, 1, 0]
Before: [3, 3, 2, 0]
10 0 2 0
After: [2, 3, 2, 0]
Before: [1, 0, 0, 1]
12 0 1 2
After: [1, 0, 1, 1]
Before: [1, 3, 1, 1]
9 0 1 3
After: [1, 3, 1, 1]
Before: [1, 0, 2, 1]
14 3 2 1
After: [1, 3, 2, 1]
Before: [0, 0, 1, 1]
5 0 2 3
After: [0, 0, 1, 0]
Before: [2, 3, 2, 3]
3 3 3 1
After: [2, 3, 2, 3]
Before: [1, 2, 2, 0]
2 2 3 3
After: [1, 2, 2, 3]
Before: [3, 3, 1, 0]
9 2 1 1
After: [3, 1, 1, 0]
Before: [1, 0, 3, 3]
12 0 1 0
After: [1, 0, 3, 3]
Before: [3, 0, 3, 0]
10 2 2 2
After: [3, 0, 2, 0]
Before: [2, 2, 3, 2]
0 2 3 0
After: [2, 2, 3, 2]
Before: [2, 0, 0, 2]
2 0 3 2
After: [2, 0, 3, 2]
Before: [2, 1, 2, 3]
11 2 2 2
After: [2, 1, 4, 3]
Before: [3, 3, 2, 2]
2 2 3 1
After: [3, 3, 2, 2]
Before: [0, 0, 2, 1]
11 2 2 2
After: [0, 0, 4, 1]
Before: [0, 3, 3, 1]
14 3 2 1
After: [0, 3, 3, 1]
Before: [3, 2, 0, 2]
13 0 3 2
After: [3, 2, 6, 2]
Before: [2, 2, 2, 0]
4 2 1 0
After: [3, 2, 2, 0]
Before: [3, 0, 1, 1]
15 2 1 3
After: [3, 0, 1, 1]
Before: [2, 1, 3, 2]
0 2 0 1
After: [2, 2, 3, 2]
Before: [1, 3, 1, 0]
9 0 1 0
After: [1, 3, 1, 0]
Before: [1, 1, 1, 0]
4 1 2 3
After: [1, 1, 1, 3]
Before: [1, 1, 2, 0]
7 3 1 3
After: [1, 1, 2, 1]
Before: [2, 3, 1, 3]
9 2 1 3
After: [2, 3, 1, 1]
Before: [3, 3, 1, 0]
9 2 1 3
After: [3, 3, 1, 1]
Before: [2, 3, 2, 3]
3 3 1 3
After: [2, 3, 2, 3]
Before: [3, 1, 2, 2]
8 2 1 2
After: [3, 1, 3, 2]
Before: [0, 0, 1, 0]
15 2 1 2
After: [0, 0, 1, 0]
Before: [1, 0, 2, 2]
4 1 3 1
After: [1, 3, 2, 2]
Before: [0, 3, 2, 1]
5 0 1 2
After: [0, 3, 0, 1]
Before: [1, 3, 0, 3]
9 0 1 3
After: [1, 3, 0, 1]
Before: [1, 2, 3, 2]
1 3 2 0
After: [4, 2, 3, 2]
Before: [1, 1, 0, 0]
4 0 2 0
After: [3, 1, 0, 0]
Before: [1, 0, 1, 0]
4 1 2 1
After: [1, 2, 1, 0]
Before: [1, 3, 3, 2]
10 2 2 0
After: [2, 3, 3, 2]
Before: [3, 2, 3, 2]
2 1 3 2
After: [3, 2, 3, 2]
Before: [1, 2, 1, 1]
9 3 1 3
After: [1, 2, 1, 1]
Before: [0, 1, 2, 2]
14 3 1 0
After: [3, 1, 2, 2]
Before: [3, 3, 0, 2]
13 1 3 0
After: [6, 3, 0, 2]
Before: [3, 0, 2, 0]
1 0 2 3
After: [3, 0, 2, 6]
Before: [0, 3, 3, 2]
13 2 3 1
After: [0, 6, 3, 2]
Before: [1, 0, 3, 1]
12 0 1 0
After: [1, 0, 3, 1]
Before: [0, 0, 0, 1]
4 0 3 2
After: [0, 0, 3, 1]
Before: [2, 0, 1, 1]
15 3 1 3
After: [2, 0, 1, 1]
Before: [3, 0, 2, 1]
15 3 1 2
After: [3, 0, 1, 1]
Before: [3, 3, 2, 3]
1 3 2 3
After: [3, 3, 2, 6]
Before: [2, 1, 1, 3]
8 2 3 2
After: [2, 1, 3, 3]
Before: [0, 0, 1, 3]
15 2 1 2
After: [0, 0, 1, 3]
Before: [3, 1, 3, 1]
10 2 2 2
After: [3, 1, 2, 1]
Before: [2, 3, 1, 0]
9 2 1 2
After: [2, 3, 1, 0]
Before: [0, 0, 2, 2]
6 0 0 3
After: [0, 0, 2, 0]
Before: [0, 0, 2, 0]
8 0 2 0
After: [2, 0, 2, 0]
Before: [0, 0, 2, 1]
3 2 2 1
After: [0, 2, 2, 1]
Before: [3, 2, 2, 0]
2 2 3 0
After: [3, 2, 2, 0]
Before: [3, 2, 3, 2]
0 2 3 3
After: [3, 2, 3, 2]
Before: [2, 0, 2, 3]
11 2 2 3
After: [2, 0, 2, 4]
Before: [1, 2, 2, 2]
11 2 2 3
After: [1, 2, 2, 4]
Before: [0, 1, 0, 1]
8 0 1 2
After: [0, 1, 1, 1]
Before: [1, 0, 1, 2]
15 2 1 2
After: [1, 0, 1, 2]
Before: [1, 2, 1, 1]
9 3 1 2
After: [1, 2, 1, 1]
Before: [3, 1, 3, 0]
7 3 1 1
After: [3, 1, 3, 0]
Before: [0, 1, 1, 3]
8 1 3 0
After: [3, 1, 1, 3]
Before: [2, 2, 3, 0]
0 2 1 0
After: [2, 2, 3, 0]
Before: [2, 0, 0, 3]
5 1 0 3
After: [2, 0, 0, 0]
Before: [2, 0, 2, 2]
2 2 3 0
After: [3, 0, 2, 2]
Before: [0, 2, 3, 3]
10 2 2 0
After: [2, 2, 3, 3]
Before: [3, 0, 1, 2]
15 2 1 3
After: [3, 0, 1, 1]
Before: [3, 1, 2, 0]
2 2 3 1
After: [3, 3, 2, 0]
Before: [0, 1, 3, 2]
4 0 2 1
After: [0, 2, 3, 2]
Before: [1, 0, 0, 3]
12 0 1 3
After: [1, 0, 0, 1]
Before: [2, 2, 3, 3]
0 2 1 0
After: [2, 2, 3, 3]
Before: [0, 1, 1, 1]
5 0 1 3
After: [0, 1, 1, 0]
Before: [1, 0, 1, 2]
15 2 1 0
After: [1, 0, 1, 2]
Before: [2, 1, 3, 0]
10 2 2 2
After: [2, 1, 2, 0]
Before: [0, 2, 3, 2]
1 1 2 3
After: [0, 2, 3, 4]
Before: [1, 1, 0, 1]
7 2 1 0
After: [1, 1, 0, 1]
Before: [0, 3, 1, 0]
6 0 0 0
After: [0, 3, 1, 0]
Before: [3, 1, 0, 0]
7 3 1 3
After: [3, 1, 0, 1]
Before: [1, 0, 1, 3]
12 0 1 0
After: [1, 0, 1, 3]
Before: [1, 0, 1, 1]
12 0 1 2
After: [1, 0, 1, 1]
Before: [0, 3, 3, 3]
1 1 3 0
After: [9, 3, 3, 3]
Before: [3, 0, 3, 2]
5 1 0 0
After: [0, 0, 3, 2]
Before: [1, 2, 1, 1]
13 3 1 2
After: [1, 2, 2, 1]
Before: [1, 3, 0, 3]
9 0 1 1
After: [1, 1, 0, 3]
Before: [0, 3, 2, 3]
8 0 2 1
After: [0, 2, 2, 3]
Before: [2, 1, 0, 1]
7 2 1 0
After: [1, 1, 0, 1]
Before: [0, 0, 3, 2]
6 0 0 2
After: [0, 0, 0, 2]
Before: [0, 3, 0, 2]
4 2 1 0
After: [1, 3, 0, 2]
Before: [0, 1, 2, 1]
5 0 3 3
After: [0, 1, 2, 0]
Before: [2, 3, 1, 2]
9 2 1 0
After: [1, 3, 1, 2]
Before: [0, 3, 1, 2]
9 2 1 3
After: [0, 3, 1, 1]
Before: [0, 2, 1, 2]
4 0 1 2
After: [0, 2, 1, 2]
Before: [1, 0, 2, 2]
12 0 1 1
After: [1, 1, 2, 2]
Before: [3, 3, 1, 2]
9 2 1 3
After: [3, 3, 1, 1]
Before: [2, 2, 0, 2]
2 0 3 2
After: [2, 2, 3, 2]
Before: [3, 2, 2, 0]
1 0 2 2
After: [3, 2, 6, 0]
Before: [0, 3, 2, 0]
2 2 3 2
After: [0, 3, 3, 0]
Before: [1, 2, 3, 2]
0 2 3 0
After: [2, 2, 3, 2]
Before: [0, 1, 2, 3]
3 3 0 2
After: [0, 1, 3, 3]
Before: [0, 3, 1, 2]
6 0 0 1
After: [0, 0, 1, 2]
Before: [1, 2, 2, 0]
2 2 3 1
After: [1, 3, 2, 0]
Before: [1, 3, 1, 0]
9 2 1 3
After: [1, 3, 1, 1]
Before: [2, 1, 0, 0]
4 1 2 0
After: [3, 1, 0, 0]
Before: [0, 1, 3, 2]
8 0 1 2
After: [0, 1, 1, 2]
Before: [0, 2, 3, 2]
1 3 2 2
After: [0, 2, 4, 2]
Before: [0, 1, 0, 0]
7 2 1 1
After: [0, 1, 0, 0]
Before: [0, 2, 3, 1]
0 2 1 2
After: [0, 2, 2, 1]
Before: [3, 3, 2, 2]
11 2 2 0
After: [4, 3, 2, 2]
Before: [3, 0, 0, 3]
1 0 3 3
After: [3, 0, 0, 9]
Before: [1, 1, 0, 3]
7 2 1 0
After: [1, 1, 0, 3]
Before: [3, 1, 0, 2]
7 2 1 0
After: [1, 1, 0, 2]
Before: [1, 0, 2, 0]
2 2 3 0
After: [3, 0, 2, 0]
Before: [2, 1, 0, 0]
7 3 1 2
After: [2, 1, 1, 0]
Before: [2, 2, 1, 2]
1 3 2 3
After: [2, 2, 1, 4]
Before: [2, 0, 3, 0]
0 2 0 0
After: [2, 0, 3, 0]
Before: [3, 0, 3, 2]
0 2 3 3
After: [3, 0, 3, 2]
Before: [0, 1, 2, 2]
11 3 2 0
After: [4, 1, 2, 2]
Before: [1, 1, 2, 0]
7 3 1 0
After: [1, 1, 2, 0]
Before: [0, 1, 2, 0]
2 2 3 2
After: [0, 1, 3, 0]
Before: [2, 0, 1, 1]
1 0 2 3
After: [2, 0, 1, 4]
Before: [0, 1, 3, 1]
5 0 2 2
After: [0, 1, 0, 1]
Before: [0, 2, 2, 0]
2 2 3 3
After: [0, 2, 2, 3]
Before: [1, 3, 0, 3]
9 0 1 2
After: [1, 3, 1, 3]
Before: [2, 0, 3, 3]
10 2 2 1
After: [2, 2, 3, 3]
Before: [2, 2, 3, 1]
0 2 1 1
After: [2, 2, 3, 1]
Before: [0, 0, 1, 2]
6 0 0 2
After: [0, 0, 0, 2]
Before: [0, 0, 2, 3]
10 3 2 2
After: [0, 0, 2, 3]
Before: [3, 2, 2, 1]
3 2 2 3
After: [3, 2, 2, 2]
Before: [0, 0, 0, 2]
1 3 2 1
After: [0, 4, 0, 2]
Before: [1, 0, 3, 3]
12 0 1 3
After: [1, 0, 3, 1]
Before: [2, 1, 2, 2]
11 0 2 1
After: [2, 4, 2, 2]
Before: [1, 3, 2, 3]
10 3 2 1
After: [1, 2, 2, 3]
Before: [0, 0, 1, 2]
5 0 3 3
After: [0, 0, 1, 0]
Before: [0, 0, 2, 0]
11 2 2 3
After: [0, 0, 2, 4]
Before: [1, 1, 2, 0]
11 2 2 0
After: [4, 1, 2, 0]
Before: [3, 1, 1, 3]
3 3 3 2
After: [3, 1, 3, 3]
Before: [1, 3, 0, 2]
13 1 3 2
After: [1, 3, 6, 2]
Before: [1, 1, 0, 0]
1 0 3 0
After: [3, 1, 0, 0]
Before: [1, 0, 1, 1]
12 0 1 3
After: [1, 0, 1, 1]
Before: [1, 0, 3, 2]
12 0 1 3
After: [1, 0, 3, 1]
Before: [0, 0, 3, 3]
10 2 2 0
After: [2, 0, 3, 3]
Before: [0, 2, 3, 3]
0 2 1 3
After: [0, 2, 3, 2]
Before: [2, 2, 1, 1]
9 3 1 0
After: [1, 2, 1, 1]
Before: [1, 3, 3, 2]
10 2 2 1
After: [1, 2, 3, 2]
Before: [1, 3, 1, 3]
3 3 0 3
After: [1, 3, 1, 3]
Before: [0, 0, 2, 3]
6 0 0 2
After: [0, 0, 0, 3]
Before: [1, 1, 1, 0]
7 3 1 2
After: [1, 1, 1, 0]
Before: [1, 1, 0, 1]
7 2 1 3
After: [1, 1, 0, 1]
Before: [3, 3, 0, 0]
4 3 2 0
After: [2, 3, 0, 0]
Before: [2, 1, 1, 1]
4 1 2 3
After: [2, 1, 1, 3]
Before: [3, 0, 2, 3]
4 2 1 3
After: [3, 0, 2, 3]
Before: [1, 0, 2, 0]
4 2 1 2
After: [1, 0, 3, 0]
Before: [1, 0, 1, 2]
12 0 1 1
After: [1, 1, 1, 2]
Before: [0, 1, 0, 0]
5 0 1 0
After: [0, 1, 0, 0]
Before: [1, 1, 2, 0]
7 3 1 1
After: [1, 1, 2, 0]
Before: [0, 2, 1, 0]
2 1 3 0
After: [3, 2, 1, 0]
Before: [2, 1, 2, 0]
2 0 3 1
After: [2, 3, 2, 0]
Before: [0, 3, 2, 2]
10 1 2 3
After: [0, 3, 2, 2]
Before: [1, 0, 0, 0]
12 0 1 0
After: [1, 0, 0, 0]
Before: [2, 1, 0, 2]
14 3 1 0
After: [3, 1, 0, 2]
Before: [3, 2, 2, 1]
9 3 1 2
After: [3, 2, 1, 1]
Before: [1, 0, 1, 2]
15 2 1 1
After: [1, 1, 1, 2]
Before: [2, 0, 1, 1]
15 2 1 1
After: [2, 1, 1, 1]
Before: [3, 0, 3, 3]
3 3 3 0
After: [3, 0, 3, 3]
Before: [1, 1, 1, 0]
1 1 3 1
After: [1, 3, 1, 0]
Before: [2, 2, 0, 1]
9 3 1 1
After: [2, 1, 0, 1]
Before: [1, 3, 1, 2]
9 2 1 3
After: [1, 3, 1, 1]
Before: [0, 3, 1, 1]
6 0 0 2
After: [0, 3, 0, 1]
Before: [3, 1, 3, 1]
8 1 2 2
After: [3, 1, 3, 1]
Before: [1, 2, 2, 1]
4 1 1 1
After: [1, 3, 2, 1]
Before: [2, 3, 3, 0]
0 2 0 0
After: [2, 3, 3, 0]
Before: [0, 2, 1, 1]
9 3 1 1
After: [0, 1, 1, 1]
Before: [0, 3, 3, 0]
5 0 1 2
After: [0, 3, 0, 0]
Before: [0, 3, 1, 0]
9 2 1 1
After: [0, 1, 1, 0]
Before: [3, 2, 3, 2]
2 1 3 3
After: [3, 2, 3, 3]
Before: [1, 1, 2, 2]
11 3 2 3
After: [1, 1, 2, 4]
Before: [0, 3, 3, 3]
5 0 2 0
After: [0, 3, 3, 3]
Before: [1, 0, 2, 2]
11 2 2 1
After: [1, 4, 2, 2]
Before: [3, 2, 3, 1]
14 3 2 0
After: [3, 2, 3, 1]
Before: [0, 3, 2, 0]
6 0 0 0
After: [0, 3, 2, 0]
Before: [1, 1, 1, 3]
3 3 1 2
After: [1, 1, 3, 3]
Before: [3, 1, 3, 2]
0 2 3 3
After: [3, 1, 3, 2]
Before: [2, 1, 2, 2]
2 2 3 3
After: [2, 1, 2, 3]
Before: [0, 3, 0, 3]
6 0 0 3
After: [0, 3, 0, 0]
Before: [0, 2, 2, 3]
6 0 0 2
After: [0, 2, 0, 3]
Before: [0, 1, 3, 3]
6 0 0 2
After: [0, 1, 0, 3]
Before: [1, 1, 2, 2]
8 2 1 2
After: [1, 1, 3, 2]
Before: [2, 2, 1, 1]
1 2 3 2
After: [2, 2, 3, 1]
Before: [2, 0, 1, 2]
15 2 1 2
After: [2, 0, 1, 2]
Before: [2, 1, 2, 3]
1 3 3 2
After: [2, 1, 9, 3]
Before: [0, 1, 0, 0]
7 2 1 2
After: [0, 1, 1, 0]
Before: [2, 1, 0, 3]
8 2 3 0
After: [3, 1, 0, 3]
Before: [0, 3, 2, 1]
14 3 2 0
After: [3, 3, 2, 1]
Before: [2, 0, 1, 2]
15 2 1 0
After: [1, 0, 1, 2]
Before: [1, 2, 2, 1]
13 3 1 3
After: [1, 2, 2, 2]
Before: [1, 0, 1, 0]
12 0 1 0
After: [1, 0, 1, 0]
Before: [2, 2, 3, 0]
0 2 1 3
After: [2, 2, 3, 2]
Before: [0, 0, 1, 1]
15 2 1 3
After: [0, 0, 1, 1]
Before: [0, 3, 0, 3]
3 3 0 0
After: [3, 3, 0, 3]
Before: [2, 2, 2, 1]
11 2 2 2
After: [2, 2, 4, 1]
Before: [2, 1, 2, 0]
2 0 3 0
After: [3, 1, 2, 0]
Before: [1, 2, 2, 0]
13 0 1 0
After: [2, 2, 2, 0]
Before: [1, 0, 3, 0]
12 0 1 1
After: [1, 1, 3, 0]
Before: [3, 1, 0, 3]
5 2 0 3
After: [3, 1, 0, 0]
Before: [1, 2, 1, 0]
1 2 3 0
After: [3, 2, 1, 0]
Before: [0, 1, 3, 2]
13 2 3 0
After: [6, 1, 3, 2]
Before: [1, 0, 1, 2]
12 0 1 0
After: [1, 0, 1, 2]
Before: [0, 0, 1, 1]
1 2 3 3
After: [0, 0, 1, 3]
Before: [1, 3, 0, 2]
9 0 1 2
After: [1, 3, 1, 2]
Before: [2, 3, 2, 2]
11 3 2 0
After: [4, 3, 2, 2]
Before: [2, 2, 3, 1]
10 2 2 0
After: [2, 2, 3, 1]
Before: [3, 0, 3, 2]
10 2 2 3
After: [3, 0, 3, 2]
Before: [2, 1, 2, 2]
11 3 2 2
After: [2, 1, 4, 2]
Before: [0, 3, 3, 1]
10 2 2 1
After: [0, 2, 3, 1]
Before: [0, 0, 2, 1]
15 3 1 3
After: [0, 0, 2, 1]
Before: [1, 2, 3, 2]
13 2 3 1
After: [1, 6, 3, 2]
Before: [2, 3, 2, 1]
14 3 2 2
After: [2, 3, 3, 1]
Before: [1, 0, 1, 3]
12 0 1 2
After: [1, 0, 1, 3]
Before: [0, 2, 2, 3]
8 0 3 0
After: [3, 2, 2, 3]
Before: [0, 1, 1, 2]
14 3 1 3
After: [0, 1, 1, 3]
Before: [1, 3, 3, 2]
9 0 1 2
After: [1, 3, 1, 2]
Before: [2, 2, 2, 1]
11 2 2 1
After: [2, 4, 2, 1]
Before: [1, 3, 3, 3]
9 0 1 0
After: [1, 3, 3, 3]
Before: [3, 3, 2, 1]
1 3 2 0
After: [2, 3, 2, 1]
Before: [0, 1, 3, 1]
14 3 2 3
After: [0, 1, 3, 3]
Before: [2, 0, 3, 3]
0 2 0 0
After: [2, 0, 3, 3]
Before: [3, 2, 3, 2]
13 2 3 0
After: [6, 2, 3, 2]
Before: [2, 3, 2, 1]
11 2 2 2
After: [2, 3, 4, 1]
Before: [3, 0, 0, 2]
5 2 0 2
After: [3, 0, 0, 2]
Before: [1, 1, 1, 3]
3 3 3 1
After: [1, 3, 1, 3]
Before: [2, 1, 2, 0]
3 2 0 0
After: [2, 1, 2, 0]
Before: [0, 3, 1, 3]
6 0 0 0
After: [0, 3, 1, 3]
Before: [2, 1, 0, 0]
2 0 3 3
After: [2, 1, 0, 3]
Before: [0, 1, 0, 3]
5 0 1 3
After: [0, 1, 0, 0]
Before: [3, 0, 2, 1]
15 3 1 0
After: [1, 0, 2, 1]
Before: [2, 2, 2, 2]
2 1 3 0
After: [3, 2, 2, 2]
Before: [2, 1, 0, 2]
14 3 1 3
After: [2, 1, 0, 3]
Before: [0, 0, 2, 1]
11 2 2 3
After: [0, 0, 2, 4]
Before: [2, 3, 1, 2]
9 2 1 3
After: [2, 3, 1, 1]
Before: [0, 3, 1, 1]
6 0 0 3
After: [0, 3, 1, 0]
""".trimIndent()
} | 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 51,622 | advent-of-code | MIT License |
kotlin/src/com/s13g/aoc/aoc2018/Day24.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | /*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.s13g.aoc.aoc2018
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/** https://adventofcode.com/2018/day/24 */
class Day24 : Solver {
override fun solve(lines: List<String>): Result {
val env = parseGroups(lines)
while (!env.isBattleOver()) fightStep(env)
val solutionA = env.countUnitsRemaining().toString()
// Find the lowest boost that makes the immune system win.
for (boost in 1..100) {
if (runBattle(env, boost)) break
}
val immuneUnitsLeft = env.immuneGroups.sumBy { g -> g.numUnits }
return Result(solutionA, immuneUnitsLeft.toString())
}
/** Returns whether the infection was killed. */
private fun runBattle(env: Environment, boost: Int): Boolean {
env.allGroupsSorted().forEach { g -> g.reset() }
env.immuneGroups.forEach { g -> g.boost = boost }
while (!env.isBattleOver()) {
if (!fightStep(env)) break
}
return env.isInfectionDead()
}
/** Returns whether any units were lost. If false, battle is stuck. */
private fun fightStep(env: Environment): Boolean {
// Phase 1 - Target Selection (each group)
val selectedTargets = HashMap<UnitGroup, UnitGroup>()
selectedTargets.putAll(selectAllTargets(env.infectionGroups, env.immuneGroups))
selectedTargets.putAll(selectAllTargets(env.immuneGroups, env.infectionGroups))
// Attack!
var unitsLost = 0
for (attacker in env.allGroupsSorted()) {
val defender = selectedTargets[attacker] ?: continue
unitsLost += defender.attackedBy(attacker)
}
return unitsLost > 0
}
private fun selectAllTargets(attackers: List<UnitGroup>,
defenders: List<UnitGroup>): HashMap<UnitGroup, UnitGroup> {
val selections = HashMap<UnitGroup, UnitGroup>()
for (att in attackers.sortedWith(selectionComparator)) {
if (att.numUnits == 0) continue
var selectedDefender: UnitGroup? = null
var selectedDamage = 0
for (def in defenders) {
if (def.numUnits == 0 || selections.values.contains(def)) continue
val damage = calcDamage(att, def)
if (damage < selectedDamage || damage == 0) continue
if (damage > selectedDamage) {
selectedDefender = def
selectedDamage = damage
} else if (damage == selectedDamage && selectedDefender != null) {
if (def.effectivePower() > selectedDefender.effectivePower()) {
selectedDefender = def
} else if (def.effectivePower() == selectedDefender.effectivePower()) {
if (def.initiative > selectedDefender.initiative) {
selectedDefender = def
} else {
continue
}
}
}
}
if (selectedDefender != null && selectedDamage > 0) {
selections[att] = selectedDefender
}
}
return selections
}
}
private fun parseGroups(lines: List<String>): Environment {
val immuneUnits = arrayListOf<UnitGroup>()
val infectionUnits = arrayListOf<UnitGroup>()
var infection = false
for (line in lines) {
if (line.startsWith("Infection")) {
infection = true
continue
}
if (line.isBlank() || line.startsWith("Immune")) continue
addTo(if (infection) infectionUnits else immuneUnits, line, infection)
}
return Environment(
immuneUnits.sortedByDescending { s -> s.effectivePower() },
infectionUnits.sortedByDescending { s -> s.effectivePower() })
}
private fun addTo(list: ArrayList<UnitGroup>, line: String, infection: Boolean) {
list.add(parseUnitGroup(line, list.size + 1, infection))
}
private fun parseUnitGroup(line: String, idx: Int, infection: Boolean): UnitGroup {
val split = line.split(' ')
val numUnits = split[0].toInt()
val hitPoints = split[4].toInt()
val initiative = split[split.size - 1].toInt()
val tail = line.substringAfter("that does ").split(' ')
val attackDamage = tail[0].toInt()
val attackType = tail[1]
val attributesStr = line.substringAfter('(', "").substringBefore(')')
val attributesSplit = attributesStr.split("; ")
val weaknesses = arrayListOf<String>()
val immunities = arrayListOf<String>()
for (a in attributesSplit) {
if (a.startsWith("weak")) {
weaknesses.addAll(a.substringAfter("weak to ").split(", "))
} else {
immunities.addAll(a.substringAfter("immune to ").split(", "))
}
}
return UnitGroup(idx, numUnits, hitPoints, attackDamage, attackType, initiative,
weaknesses, immunities, if (infection) "Infection" else "Immune System")
}
/** Used during selection stage. */
private val selectionComparator = Comparator<UnitGroup> { a, b ->
if (b.effectivePower() == a.effectivePower()) {
b.initiative - a.initiative
} else {
b.effectivePower() - a.effectivePower()
}
}
/** Used during fight stage. */
private val initiativeComparator = Comparator<UnitGroup> { a, b ->
// Descending order.
b.initiative - a.initiative
}
private class Environment(val immuneGroups: List<UnitGroup>,
val infectionGroups: List<UnitGroup>) {
fun allGroupsSorted(): List<UnitGroup> {
val allGroups = arrayListOf<UnitGroup>()
allGroups.addAll(immuneGroups)
allGroups.addAll(infectionGroups)
return allGroups.sortedWith(initiativeComparator)
}
fun isBattleOver() =
immuneGroups.sumBy { g -> g.numUnits } == 0 ||
infectionGroups.sumBy { g -> g.numUnits } == 0
fun countUnitsRemaining() = allGroupsSorted().sumBy { g -> g.numUnits }
fun isInfectionDead() = infectionGroups.sumBy { g -> g.numUnits } == 0
}
private fun calcDamage(attacker: UnitGroup, defender: UnitGroup): Int {
if (attacker.numUnits == 0) return 0
var damage =
if (defender.immunities.contains(attacker.attackType)) 0
else attacker.effectivePower()
if (defender.weaknesses.contains(attacker.attackType)) damage *= 2
return damage
}
private class UnitGroup(val idx: Int, var numUnits: Int, val hitPoints: Int,
val attackDamage: Int, val attackType: String,
val initiative: Int, val weaknesses: List<String>,
val immunities: List<String>, val group: String,
val origNumUnits: Int = numUnits, var boost: Int = 0) {
fun effectivePower() = this.numUnits * (attackDamage + boost)
fun attackedBy(att: UnitGroup): Int {
val damage = calcDamage(att, this)
val unitsLost = minOf(damage / hitPoints, numUnits)
numUnits -= unitsLost
return unitsLost
}
fun reset() {
numUnits = origNumUnits
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 7,173 | euler | Apache License 2.0 |
day-3/src/Part1.kt | woojiahao | 225,170,972 | false | null | import Direction.*
import kotlin.math.abs
import kotlin.system.measureTimeMillis
val o = 0 to 0
fun manhattanDistance(i: Point) = abs(o.x - i.x) + abs(o.y - i.y)
fun move(pos: Point, t: Travel) =
when (t.direction) {
L -> (pos.x - 1 downTo (pos.x - t.distance)).map { it to pos.y }
R -> ((pos.x + 1)..(pos.x + t.distance)).map { it to pos.y }
U -> ((pos.y + 1)..(pos.y + t.distance)).map { pos.x to it }
D -> (pos.y - 1 downTo (pos.y - t.distance)).map { pos.x to it }
}
fun path(t: List<Travel>): List<Point> {
var cur = o.copy()
return t
.map {
with(move(cur, it)) {
cur = last()
this
}
}
.flatten()
}
fun intersections(p1: List<Point>, p2: List<Point>) = p1.intersect(p2).toList()
fun solve(t1: List<Travel>, t2: List<Travel>) = intersections(path(t1), path(t2)).map { manhattanDistance(it) }.min()!!
fun main() {
val (t1, t2) = data()
println("Answer: ${solve(t1, t2)}")
val rawTime = measureTimeMillis {
println(solve(t1, t2))
}
println("Raw time: $rawTime")
val p1 = path(t1)
val p2 = path(t2)
val betterTime = measureTimeMillis {
intersections(p1, p2).map { manhattanDistance(it) }.min()!!
}
println("Better time: $betterTime")
} | 0 | Kotlin | 0 | 2 | 4c9220a49dbc093fbe7f0d6692fa0390a63e702a | 1,237 | aoc-19 | MIT License |
2022/Day20/problems.kt | moozzyk | 317,429,068 | false | {"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794} | import java.io.File
import kotlin.math.*
class Node(val value: Long, var next: Node?, var prev: Node?) {}
fun addNode(value: Long, predecessor: Node?): Node {
if (predecessor == null) {
var newNode = Node(value, null, null)
newNode.next = newNode
newNode.prev = newNode
return newNode
}
var newNode = Node(value, next = predecessor.next, prev = predecessor.next!!.prev)
predecessor.next!!.prev = newNode
predecessor.next = newNode
return newNode
}
fun removeNode(node: Node): Node {
node.prev!!.next = node.next
node.next!!.prev = node.prev
return node
}
fun insertAfter(node: Node, predecessor: Node) {
node.next = predecessor.next
node.prev = predecessor
predecessor.next!!.prev = node
predecessor.next = node
}
fun insertBefore(node: Node, successor: Node) {
node.next = successor
node.prev = successor.prev!!
successor.prev!!.next = node
successor.prev = node
}
fun printList(head: Node) {
var node = head
do {
print("${node.value} ")
node = node.next!!
} while (node != head)
println()
}
fun getNode(startNode: Node, count: Int): Node {
var n = startNode
for (i in 0 until count) {
n = n.next!!
}
return n
}
fun main(args: Array<String>) {
val numbers = File(args[0]).readLines().map { it.toLong() }
println(problem1(numbers))
println(problem2(numbers))
}
fun problem1(numbers: List<Long>): Long {
return solve(numbers, 1)
}
fun problem2(numbers: List<Long>): Long {
return solve(numbers.map { it * 811589153L }, 10)
}
fun solve(numbers: List<Long>, reps: Int): Long {
var nodes = mutableListOf<Node>()
for (n in numbers) {
nodes.add(addNode(n, nodes.lastOrNull()))
}
for (i in 0 until reps) {
mixNodes(nodes)
}
val startNode = nodes.first { it.value == 0L }
return getNode(startNode, 1000 % nodes.size).value +
getNode(startNode, 2000 % nodes.size).value +
getNode(startNode, 3000 % nodes.size).value
}
fun mixNodes(nodes: List<Node>) {
for (n in nodes) {
if (n.value == 0L) {
continue
}
if (n.value > 0 && (n.value % (nodes.size - 1)) != 0L) {
var tmp = removeNode(n)
var count = n.value % (nodes.size - 1)
do {
tmp = tmp.next!!
count--
} while (count > 0)
insertAfter(n, tmp)
} else if (n.value < 0 && ((-n.value) % (nodes.size - 1)) != 0L) {
var tmp = removeNode(n)
var count = (-n.value) % (nodes.size - 1)
do {
tmp = tmp.prev!!
count--
} while (count > 0)
insertBefore(n, tmp)
}
}
}
| 0 | Rust | 0 | 0 | c265f4c0bddb0357fe90b6a9e6abdc3bee59f585 | 2,795 | AdventOfCode | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.