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/2023/Day3_1.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
val grid = mutableListOf<String>()
val symbols = Regex("[^\\.\\d\\s]")
val partNumbers = mutableListOf<Int>()
fun String.isPrevDigit(pos: Int) = pos > 0 && this[pos-1].isDigit()
File("input/2023/day3").apply {
forEachLine { grid.add(it) }
grid.forEachIndexed { y, row ->
val numbers = row.split(Regex("\\D")).filter { it.isNotEmpty() }
val passedIndices = mutableSetOf<Int>()
numbers.forEach { number ->
var xStart = row.indexOf(number)
var offset: Int
if (row.isPrevDigit(xStart)) passedIndices.add(xStart)
while (passedIndices.contains(xStart)) {
offset = xStart + number.length
xStart = row.substring(xStart + number.length).indexOf(number) + offset
if (row.isPrevDigit(xStart)) passedIndices.add(xStart)
}
passedIndices.add(xStart)
val xEnd = xStart + number.length - 1
var isPartNumber = false
for (x in xStart..xEnd) {
val lu = if (y > 0 && x > 0) symbols.matches(grid[y - 1][x - 1].toString()) else false
val u = if (y > 0) symbols.matches(grid[y - 1][x].toString()) else false
val ru = if (y > 0 && x < row.length - 1) symbols.matches(grid[y - 1][x + 1].toString()) else false
val l = if (x - 1 < xStart && x > 0) symbols.matches(grid[y][x - 1].toString()) else false
val r = if (x + 1 > xEnd && x < row.length - 1) symbols.matches(grid[y][x + 1].toString()) else false
val ld = if (y < grid.size - 1 && x > 0) symbols.matches(grid[y + 1][x - 1].toString()) else false
val d = if (y < grid.size - 1) symbols.matches(grid[y + 1][x].toString()) else false
val rd = if (y < grid.size - 1 && x < row.length - 1) symbols.matches(grid[y + 1][x + 1].toString()) else false
isPartNumber = lu || l || ld || u || d || ru || r || rd
if (isPartNumber) break
}
if (isPartNumber) partNumbers.add(number.toInt())
}
}
}
println(partNumbers.sum())
| 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 2,151 | adventofcode | MIT License |
src/main/kotlin/aoc22/Day25.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc22
import aoc22.Day25Domain.BaseConvertor.toBalancedQuinary
import aoc22.Day25Domain.BaseConvertor.toDecimal
import aoc22.Day25Domain.SnafuConvertor.toBalancedQuinary
import aoc22.Day25Domain.SnafuConvertor.toSnafu
import aoc22.Day25Solution.part1Day25
import common.Year22
import kotlin.math.pow
object Day25: Year22 {
fun List<Snafu>.part1(): Snafu = part1Day25()
}
object Day25Solution {
fun List<Snafu>.part1Day25(): Snafu =
map { snafu -> snafu.toBalancedQuinary().toDecimal() }.sum()
.toBalancedQuinary()
.toSnafu()
}
private typealias Decimal = Long
private typealias BalancedQuinary = List<Int>
private typealias Snafu = String
object Day25Domain {
object BaseConvertor {
fun BalancedQuinary.toDecimal(): Decimal =
reversed().foldIndexed(0L) { index, acc, i ->
acc +
when (index) {
0 -> i
else -> 5.toDouble().pow(index) * i
}.toLong()
}
fun Decimal.toBalancedQuinary(): BalancedQuinary =
generateSequence(this) { (it + 2) / 5 }.takeWhile { it != 0L }
.map {
when(val mod = (it % 5).toInt()) {
3 -> -2
4 -> -1
else -> mod
}
}
.toList()
.reversed()
}
object SnafuConvertor {
private val snafuIntMap =
mapOf(
'=' to -2,
'-' to -1,
'0' to 0,
'1' to 1,
'2' to 2,
)
fun Snafu.toBalancedQuinary(): BalancedQuinary = map { snafuIntMap[it]!! }
fun BalancedQuinary.toSnafu(): Snafu =
map { int -> snafuIntMap.filter { it.value == int }.keys.single() }
.joinToString("")
}
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 1,937 | aoc | Apache License 2.0 |
src/main/kotlin/graph/variation/EvenLenWalk.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.Edge
import graph.core.Graph
import graph.core.Vertex
import graph.core.bfs
import util.Tuple2
import util.tu
// given an undirected graph G, find a shortest even length walk from s to e
// or report that such walk does not exist
fun main(args: Array<String>) {
val vertices = (0 until 9).map { Vertex(it) }
val edges = setOf(
Edge(vertices[0], vertices[1]),
Edge(vertices[1], vertices[2]),
Edge(vertices[1], vertices[5]),
Edge(vertices[2], vertices[5]),
Edge(vertices[3], vertices[4]),
Edge(vertices[4], vertices[7]),
Edge(vertices[5], vertices[7]),
Edge(vertices[6], vertices[8]),
Edge(vertices[7], vertices[6]))
val graph = Graph(vertices, edges)
println(graph.shortestEvenLen(vertices[0], vertices[8]))
}
fun Graph<Int>.shortestEvenLen(s: Vertex<Int>, e: Vertex<Int>): List<Vertex<Int>> {
// given G = (V, E), construct a new graph G' = (V', E') :
// V' = { (v, i) : v in V, i in { true, false } indicating whether the walk
// is either odd, i.e. true or even, i.e. false o/w }
// E' = { (v, i) -> (u, i') : v -> u in E, i' = !i }
// now we want to find the minimum path from (s, false) to (e, false)
val newVertices = vertices.map { listOf(Vertex(it tu false), Vertex(it tu true)) }
.flatten()
val newEdges = HashSet<Edge<Tuple2<Vertex<Int>, Boolean>>>()
vertices.forEach { v ->
getEdgesOf(v).forEach { (es, ee) ->
val u = if (es === v) ee else es
newEdges.add(Edge(Vertex(v tu false), Vertex(u tu true)))
newEdges.add(Edge(Vertex(v tu true), Vertex(u tu false)))
}
}
val g = Graph(newVertices, newEdges)
val start = Vertex(s tu false)
val map = g.bfs(start)
val list = ArrayList<Vertex<Int>>()
var curr: Vertex<Tuple2<Vertex<Int>, Boolean>>? = Vertex(e tu false)
while (curr != null && curr != start) {
list.add(curr.data.first)
curr = map[curr]
}
return list.reversed()
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,901 | AlgoKt | MIT License |
core/src/main/kotlin/net/olegg/aoc/utils/Collections.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.utils
/**
* Generates the sequence of all permutations of items in current list.
*/
fun <T : Any> List<T>.permutations(): Sequence<List<T>> = if (size == 1) {
sequenceOf(this)
} else {
val iterator = iterator()
var head = iterator.next()
var permutations = (this - head).permutations().iterator()
fun nextPermutation(): List<T>? = if (permutations.hasNext()) {
listOf(head) + permutations.next()
} else {
if (iterator.hasNext()) {
head = iterator.next()
permutations = (this - head).permutations().iterator()
nextPermutation()
} else {
null
}
}
generateSequence { nextPermutation() }
}
fun <T : Any> List<T>.pairs(): Sequence<Pair<T, T>> {
require(size > 1)
return sequence {
for (x in indices) {
for (y in x + 1..<size) {
yield(get(x) to get(y))
}
}
}
}
/**
* Splits iterable into run-length encoded list.
*/
fun <T> Iterable<T>.series(): List<Pair<T, Int>> {
return buildList {
var curr: T? = null
var count = 0
for (element in this@series) {
if (element == curr) {
count++
} else {
curr?.let { add(it to count) }
curr = element
count = 1
}
}
curr?.let { add(it to count) }
}
}
/**
* Finds first entry equal to [value] in matrix
*/
fun <T> List<List<T>>.find(value: T): Vector2D? {
forEachIndexed { y, row ->
row.forEachIndexed { x, curr ->
if (curr == value) {
return Vector2D(x, y)
}
}
}
return null
}
operator fun <T> List<MutableList<T>>.set(
v: Vector2D,
value: T
) {
when {
v.y !in indices -> throw IndexOutOfBoundsException("index: ${v.y}.${v.x}")
v.x !in this[v.y].indices -> throw IndexOutOfBoundsException("index: ${v.y}.${v.x}")
else -> this[v.y][v.x] = value
}
}
operator fun <T> List<MutableList<T>>.set(
i: Int,
j: Int,
value: T
) {
this[i][j] = value
}
operator fun <T> List<List<T>>.get(v: Vector2D): T? = when {
v.y !in indices -> null
v.x !in this[v.y].indices -> null
else -> this[v.y][v.x]
}
fun <T> List<List<T>>.fit(v: Vector2D) = v.y in indices && v.x in this[v.y].indices
fun <T> List<T>.toPair(): Pair<T, T> = Pair(get(0), get(1))
fun <T> List<T>.toTriple(): Triple<T, T, T> = Triple(get(0), get(1), get(2))
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,307 | adventofcode | MIT License |
src/main/kotlin/aoc/Day01.kt | fluxxion82 | 573,716,300 | false | {"Kotlin": 39632} | package aoc
import aoc.utils.readInput
fun main() {
fun part1(input: List<String>): Int {
val data = input.filterNot { it == "" } .map { elf ->
elf.lines().map { it.toInt() }
}
return data.maxOf { it.sum() }
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01")
// check(part1(testInput) == 1)
val input = readInput("Day01.txt")
data class Elf(val id: Int, val calories: MutableList<Int> = mutableListOf()) {
fun total() = calories.sumOf { it }
}
var elf = Elf(0)
val elves = mutableListOf<Elf>()
input.forEach { calorie ->
if (calorie == "") {
elves.add(elf)
elf = Elf(elves.size)
} else {
elf.calories.add(calorie.toInt())
}
}
elves.sortByDescending { it.total() }
val winner = elves.first()
println("elf ${winner.id} with ${winner.total()}")
val newInput = readInput("Day01.txt")
println(part1(newInput)) // 69836
val topThree = elves.take(3).sumOf { it.total() }
println("top three total: $topThree") // 207968
}
| 0 | Kotlin | 0 | 0 | 3920d2c3adfa83c1549a9137ffea477a9734a467 | 1,238 | advent-of-code-kotlin-22 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch1/Problem12.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch1
import dev.bogwalk.util.maths.gaussSum
import dev.bogwalk.util.maths.primeFactors
import dev.bogwalk.util.maths.primeNumbers
/**
* Problem 12: Highly Divisible Triangular Number
*
* https://projecteuler.net/problem=12
*
* Goal: Find the value of the first triangle number to have more than N divisors.
*
* Constraints: 1 <= N <= 1e3
*
* Triangle Number: A number generated by adding all natural numbers prior to & including itself.
*
* e.g.: N = 5
* 1st = 1 from [1] -> {1]
* 2nd = 3 from [1+2] -> {1,3}
* 3rd = 6 from [1+2+3] -> {1,2,3,6}
* 4th = 10 from [1+2+3+4] -> {1,2,5,10}
* 5th = 15 from [1+2+3+4+5] -> {1,3,5,15}
* 6th = 21 from [1+2+3+4+5+6] -> {1,3,7,21}
* 7th = 28 from [1+2+3+4+5+6+7] -> {1,2,4,7,14,28}
* result = 28
*/
class HighlyDivisibleTriangularNumber {
/**
* Returns the found triangle number generated as a Gaussian sum that has had its divisors
* counted using prime decomposition.
*
* Since the components of a Gaussian sum (n & n+1) are co-prime (i.e. they can have neither
* a common prime factor nor a common divisor), the amount of divisors can be assessed based
* on the cycling formulae using these smaller values:
*
* t represents Gaussian sum = n(n + 1)/2
*
* (even n) D(t) = D(n/2) * D(n+1)
* D(n+1) becomes D(n) for the next number, which will be odd.
*
* (odd n) D(t) = D(n) * D((n+1)/2)
*
* SPEED (WORSE) 137.26ms for N = 1e3
*/
fun firstTriangleBruteA(limit: Int): Int {
if (limit == 1) return 3
var n = 2 // D(2) = D(1) * D(3)
var isEven = true
var dn1 = 2 // D(3) = 2
var count = 2
while (count <= limit) {
n++
isEven = !isEven
val dn2 = if (isEven) countDivisors(n+1) else countDivisors((n+1)/2)
count = dn1 * dn2
dn1 = dn2
}
return n.gaussSum().toInt()
}
/**
* Identical to the first brute solution except that each triangle number is calculated
* manually and its own divisors counted.
*
* SPEED (WORST) 396.69ms for N = 1e3
*/
fun firstTriangleBruteB(limit: Int): Int {
var t = 3
if (limit == 1) return t
var n = 2
var count = 2
while (count <= limit) {
n++
t = n.gaussSum().toInt()
count = countDivisors(t)
}
return t
}
/**
* Identical to the above brute solution except that triangle numbers are generated as a
* sequence until the first to exceed [limit] is found.
*
* SPEED (WORST) 381.42ms for N = 1e3
*/
fun firstTriangleBruteC(limit: Int): Int {
return generateSequence(Pair(3, 3)) { Pair(it.first + it.second, it.second + 1) }
.first { countDivisors(it.first) > limit }
.first
}
/**
* Counts unique divisors of [n] using prime decomposition, based on the formulae:
*
* n = p_1{e_1} * p_2{e_2} * ... * p_r{e_r}
* d(n) = {r}Pi{x=1}(a_x + 1)
*
* e.g. 28 = 2^2 * 7^1, therefore
*
* number of divisors of 28 = (2 + 1) * (1 + 1) = 6 -> {1, 2, 4, 7, 14, 28}
*/
fun countDivisors(n: Int): Int {
return primeFactors(1L * n).values
.map { it + 1 }
.reduce { acc, v -> acc * v }
}
/**
* Quick pick solution finds the first triangle number to have over N divisors for every
* N <= [limit] & stores the results as an IntArray that can be repeatedly accessed afterwards.
*
* SPEED (BETTER) 94.44ms for N = 1e3
*/
fun firstTrianglesCache(limit: Int): IntArray {
val triangles = IntArray(limit + 1).apply {
this[0] = 1
this[1] = 3
this[2] = 6
}
val eMax = 20_000
val divisorCount = IntArray(eMax) { 2 }.apply { this[1] = 1 }
for (divisor in 2 until eMax) {
for (num in divisor * 2 until eMax step divisor) {
divisorCount[num]++
}
}
var lastN = 3 // D(3) = D(3) * D(2)
var isEven = false
var lastDn1 = 2
var lastTriangle = 6
var lastCount = 4
for (i in 3..limit) {
if (i < lastCount) {
triangles[i] = lastTriangle
continue
}
var nextN = lastN + 1
isEven = !isEven
do {
val toCount = if (isEven) nextN + 1 else (nextN + 1) / 2
val dn2 = if (toCount < eMax) divisorCount[toCount] else {
countDivisors(toCount)
}
val count = lastDn1 * dn2
lastDn1 = dn2
if (i < count) {
val triangle = nextN.gaussSum().toInt()
triangles[i] = triangle
lastTriangle = triangle
lastN = nextN
lastCount = count
break
}
nextN++
isEven = !isEven
} while (true)
}
return triangles
}
/**
* Similar to the original single-pick function above that exploits co-prime property of
* Gaussian sum but stores cumulative divisor counts in an array for quick access instead of
* calculating the count for every new [n].
*
* Dual cyclic formulae use n - 1 instead of n + 1 to match the cached list that is generated
* with every iteration, so looking forward would produce incorrect counts.
*
* N.B. n_max was found by exhausting all solutions for n = [1, 1000] & finding the maximum
* of the ratios of t:n. At n = 1000, the valid triangle number is the 41041st term.
*
* SPEED (BEST) 27.62ms for N = 1e3
*/
fun firstTriangleOverNOptimised(n: Int): Int {
val nMax = minOf(n * 53, 41100)
val divisorCount = IntArray(nMax)
var num = 0
var dT = 0
while (dT <= n) {
num++
for (i in num until nMax step num) {
divisorCount[i]++
}
dT = if (num % 2 == 0) {
divisorCount[num/2] * divisorCount[num-1]
} else {
divisorCount[num] * divisorCount[(num-1)/2]
}
}
return num * (num - 1) / 2
}
/**
* Generates primes to count number of divisors based on prime factorisation.
*
* SPEED (BETTER): 43.76ms for N = 1e3.
*/
fun firstTriangleOverNUsingPrimes(n: Int): Int {
if (n == 1) return 3
val primes = primeNumbers(n * 2)
var prime = 3
var dn = 2 // min num of divisors for any prime
var count = 0
while (count <= n) {
prime++
var n1 = prime
if (n1 % 2 == 0) n1 /= 2
var dn1 = 1
for (i in primes.indices) {
// when the prime divisor would be greater than the residual n1
// that residual n1 is the last prime factor with an exponent == 1.
// so no need to identify it.
if (primes[i] * primes[i] > n1) {
dn1 *= 2
break
}
var exponent = 1
while (n1 % primes[i] == 0) {
exponent++
n1 /= primes[i]
}
if (exponent > 1) dn1 *= exponent
if (n1 == 1) break
}
count = dn * dn1
dn = dn1
}
return prime * (prime - 1) / 2
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 7,725 | project-euler-kotlin | MIT License |
src/Day06.kt | vladislav-og | 573,326,483 | false | {"Kotlin": 27072} | fun main() {
fun checkIfUniqueMarker(currentMarker: ArrayDeque<Char>): Boolean {
val distinctMarker = currentMarker.distinct()
return distinctMarker.size == currentMarker.size
}
fun solvePuzzle(input: List<String>, markerLength: Int): Int {
for (datastream in input) {
val currentMarker: ArrayDeque<Char> = datastream.subSequence(0, markerLength).toCollection(ArrayDeque())
var pointer = markerLength
for (element in datastream.subSequence(markerLength, datastream.length)) {
if (checkIfUniqueMarker(currentMarker)) {
return pointer
}
currentMarker.removeFirst()
currentMarker.add(element)
pointer++
}
}
return 1
}
fun part1(input: List<String>): Int {
return solvePuzzle(input, 4)
}
fun part2(input: List<String>): Int {
return solvePuzzle(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
println(part1(testInput))
check(part1(testInput) == 7)
println(part2(testInput))
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b230ebcb5705786af4c7867ef5f09ab2262297b6 | 1,328 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day03.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import findCommon
import readInput
private fun findCommonItem(vararg compartments: String): Char =
findCommon(*compartments.map { it.toCharArray().toSet() }.toTypedArray())
private val Char.priority: Int
get() = if (isLowerCase()) {
this - 'a' + 1
} else {
this - 'A' + 27
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val compartment1 = rucksack.substring(0, rucksack.length / 2)
val compartment2 = rucksack.substring(rucksack.length / 2)
val item = findCommonItem(compartment1, compartment2)
item.priority
}
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3).sumOf { elves ->
val item = findCommonItem(elves[0], elves[1], elves[2])
item.priority
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test", 2022)
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 1,172 | adventOfCode | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/IteratorForCombination.kt | faniabdullah | 382,893,751 | false | null | //Design the CombinationIterator class:
//
//
// CombinationIterator(string characters, int combinationLength) Initializes
//the object with a string characters of sorted distinct lowercase English letters
//and a number combinationLength as arguments.
// next() Returns the next combination of length combinationLength in
//lexicographical order.
// hasNext() Returns true if and only if there exists a next combination.
//
//
//
// Example 1:
//
//
//Input
//["CombinationIterator", "next", "hasNext", "next", "hasNext", "next",
//"hasNext"]
//[["abc", 2], [], [], [], [], [], []]
//Output
//[null, "ab", true, "ac", true, "bc", false]
//
//Explanation
//CombinationIterator itr = new CombinationIterator("abc", 2);
//itr.next(); // return "ab"
//itr.hasNext(); // return True
//itr.next(); // return "ac"
//itr.hasNext(); // return True
//itr.next(); // return "bc"
//itr.hasNext(); // return False
//
//
//
// Constraints:
//
//
// 1 <= combinationLength <= characters.length <= 15
// All the characters of characters are unique.
// At most 10⁴ calls will be made to next and hasNext.
// It's guaranteed that all calls of the function next are valid.
//
// Related Topics String Backtracking Design Iterator 👍 930 👎 76
package leetcodeProblem.leetcode.editor.en
class IteratorForCombination {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class CombinationIterator(val characters: String, val combinationLength: Int) {
val n = characters.length
//current combination
var curr = ""
fun next(): String {
//first combination is first consecutive combinationLength letters from characters
if (curr == "") {
curr = characters.substring(0 until combinationLength)
return curr
}
var i = 0
//count suffix length that is equal to characters suffix
while (curr[combinationLength - i - 1] == characters[n - i - 1]) i++
//index of the next letter
val from = characters.indexOf(curr[combinationLength - i - 1]) + 1
//concatenate result
curr = curr.substring(0 until combinationLength - i - 1) + characters.substring(from..from + i)
return curr
}
fun hasNext(): Boolean {
return curr != characters.substring(characters.lastIndex - combinationLength + 1..characters.lastIndex)
}
}
/**
* Your CombinationIterator object will be instantiated and called as such:
* var obj = CombinationIterator(characters, combinationLength)
* var param_1 = obj.next()
* var param_2 = obj.hasNext()
*/
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,911 | dsa-kotlin | MIT License |
src/shmulik/klein/day03/Day03.kt | shmulik-klein | 573,426,488 | false | {"Kotlin": 9136} | package shmulik.klein.day03
import readInput
fun main() {
fun getPriorityMap(): MutableMap<Char, Int> {
val lowerIntRange = 1..26
val upperIntRange = 27..52
val lowerRange = 'a'..'z'
val upperRange = 'A'..'Z'
val mutableMapOf = mutableMapOf<Char, Int>()
for ((j, i) in lowerIntRange zip lowerRange) {
mutableMapOf[i] = j
}
for ((j, i) in upperIntRange zip upperRange) {
mutableMapOf[i] = j
}
return mutableMapOf
}
fun part1(input: List<String>): Int {
val mutableMapOf = getPriorityMap()
println(mutableMapOf)
val exists = mutableSetOf<Char>()
var sum = 0
for (line in input) {
for (char in line.substring(0 until (line.length / 2))) {
exists.add(char)
}
sum += (line.substring((line.length / 2) until (line.length))
.filter { exists.contains(it) }).map { mutableMapOf[it] }.first()!!
exists.clear()
}
return sum
}
fun part2(input: List<String>): Int {
var index = 0
var sum = 0
val priorityMap = getPriorityMap()
while (input.getOrNull(index) != null) {
val set1 = input[index].toSet()
val set2 = input[index + 1].toSet()
val set3 = input[index + 2].toSet()
index += 3
val value = set1.intersect(set2).intersect(set3).first()
sum += priorityMap[value]!!
}
return sum
}
val input = readInput("shmulik/klein/day03/Day03_test")
val result1 = part1(input)
println(result1)
val result2 = part2(input)
println(result2)
} | 0 | Kotlin | 0 | 0 | 4d7b945e966dad8514ec784a4837b63a942882e9 | 1,724 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | simonbirt | 574,137,905 | false | {"Kotlin": 45762} |
fun main() {
Day7.printSolutionIfTest(95437,24933642)
}
object Day7: Day<Int, Int>(7) {
override fun part1(lines: List<String>):Int =
totals(lines).values.filter { it <= 100000 }.sum()
override fun part2(lines: List<String>):Int =
totals(lines).let{ totals ->
val requiredSpace = 30000000 - (70000000 - totals["/"]!!)
totals.values.sorted().first { it >= requiredSpace }
}
private fun totals(lines: List<String>):Map<String, Int> {
var currentDir = mutableListOf("")
val totals = HashMap<String, Int>()
lines.forEach {
when {
it.startsWith("$ cd ") -> when (val dir = it.substring(5)) {
".." -> currentDir.removeLast()
"/" -> currentDir = mutableListOf("")
else -> currentDir.add(dir)
}
it[0].isDigit() -> {currentDir.fold(""){ a,b -> "$a$b/".also{ d -> totals[d]= (totals[d] ?: 0) + it.split(" ")[0].toInt()}}}
}
}
return totals
}
}
| 0 | Kotlin | 0 | 0 | 962eccac0ab5fc11c86396fc5427e9a30c7cd5fd | 1,079 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/16_Permutation.kt | barta3 | 112,792,199 | false | null | import java.util.*
fun main(args: Array<String>) {
example()
part1()
part2()
}
private fun part1() {
val input = "abcdefghijklmnop".toMutableList()
val moves = Permutation::class.java
.getResource("16_input.txt")
.readText()
val res = Permutation(input).run(moves)
println("Part 1: $res")
}
private fun part2() {
var input = "abcdefghijklmnop".toMutableList()
val moves = Permutation::class.java
.getResource("16_input.txt")
.readText()
var res = "start"
val states = mutableSetOf<String>()
var runs = 0
val billion = 1_000_000_000
for (i in 0..billion) {
res = Permutation(input).run(moves)
if (states.contains(res)) {
println("Repeats after $i")
runs = i
break
}
states.add(res)
}
input = "abcdefghijklmnop".toMutableList()
repeat(billion % runs) {
res = Permutation(input).run(moves)
}
println("Part 2: $res")
}
class Permutation(val list: MutableList<Char>) {
fun run(moves: String): String {
moves.split(",").forEach { m ->
when (m[0]) {
's' -> spin(m.drop(1))
'x' -> {
val (a, b) = m.drop(1).split("/").map { it.toInt() }
Collections.swap(list, a, b)
}
'p' -> {
val (a, b) = m.drop(1).split("/").map { it[0] }
Collections.swap(list, list.indexOf(a), list.indexOf(b))
}
}
}
return list.joinToString("")
}
private fun spin(move: String) {
val n = Integer.valueOf(move)
for (i in 1..n) {
val r = list.removeAt(list.size - 1)
list.add(0, r)
}
}
}
fun example() {
val input = "abcde"
val moves = "s1,x3/4,pe/b"
val list = input.toMutableList()
val res = Permutation(list).run(moves)
println("Example: $res")
}
| 0 | Kotlin | 0 | 0 | 51ba74dc7b922ac11f202cece8802d23011f34f1 | 2,021 | AdventOfCode2017 | MIT License |
src/Day10.kt | jamOne- | 573,851,509 | false | {"Kotlin": 20355} | sealed class Day10Command {
object Noop : Day10Command()
class AddX(val v: Int): Day10Command()
companion object {
fun fromString(string: String): Day10Command {
return when {
string == "noop" -> Noop
string.startsWith("addx") -> AddX(string.split(" ")[1].toInt())
else -> throw IllegalArgumentException()
}
}
}
}
fun main() {
class Device constructor (commands: List<Day10Command>) {
var register = 1
var queue = ArrayDeque(commands.map { command -> Pair(command, 0) })
fun tick() {
val (command, cycles) = queue[0]
if (command is Day10Command.AddX) {
if (cycles == 0) {
queue[0] = Pair(command, 1)
return
} else {
register += command.v
}
}
queue.removeFirst()
}
}
fun part1(input: List<String>): Int {
val cyclesToConsider = listOf(20, 60, 100, 140, 180, 220)
var strength = 0
val device = Device(input.map { line -> Day10Command.fromString(line) })
for (cycle in 1..220) {
if (cycle in cyclesToConsider) {
strength += cycle * device.register
}
device.tick()
}
return strength
}
fun part2(input: List<String>): Int {
val WIDTH = 40
val HEIGHT = 6
val device = Device(input.map { line -> Day10Command.fromString(line) })
for (row in 0 until HEIGHT) {
for (col in 0 until WIDTH) {
if (col >= device.register - 1 && col <= device.register + 1) {
print("#")
} else {
print(".")
}
device.tick()
}
print('\n')
}
return 0
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == 0)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 77795045bc8e800190f00cd2051fe93eebad2aec | 2,142 | adventofcode2022 | Apache License 2.0 |
algorithms/src/main/kotlin/com/kotlinground/algorithms/sorting/quicksort/quicksort.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.algorithms.sorting.quicksort
// partitions a slice into 2 and returns the pivot index. Assumes the pivot is at the end of the slice
fun <T> partition(collection: Array<T>, startIndex: Int, endIndex: Int): Int {
val pivot = collection[endIndex]
var leftIndex = startIndex
var rightIndex = endIndex - 1
while (leftIndex <= rightIndex) {
// walk until we find something on the left side that belongs on the right (less than the pivot)
while (leftIndex <= endIndex && collection[leftIndex] < pivot) {
leftIndex++
}
// walk until we find something on the right side that belongs on the left(greater than or equal to the pivot)
while (rightIndex >= startIndex && collection[rightIndex] >= pivot) {
rightIndex--
}
if (leftIndex < rightIndex) {
// swap the items at the left_index and right_index, moving the element that's smaller than the pivot to
// the left
// half and the element that's larger than the pivot to the right half
val temp = collection[leftIndex]
collection[leftIndex] = collection[rightIndex]
collection[rightIndex] = temp
} else {
// unless we have looked at all the elements in the list and are done partitioning. In that case, move the
// pivot element
// into it's final position
val temp = collection[leftIndex]
collection[leftIndex] = collection[endIndex]
collection[endIndex] = temp
}
}
return leftIndex
}
private operator fun <T> T.compareTo(pivot: T): Int {
TODO("Not yet implemented")
}
// quicksortSubArray uses recurstion to sort each partition of the slice
fun <T> quicksortSubCollection(collection: Array<T>, startIndex: Int, endIndex: Int) {
// base case, list with 0 or 1 element
if (startIndex >= endIndex) {
return
}
// divide the list into 2 smaller sub lists
val pivotIndex = partition(collection, startIndex, endIndex)
// Recursively sort each sublist
quicksortSubCollection(collection, startIndex, pivotIndex - 1)
quicksortSubCollection(collection, pivotIndex + 1, endIndex)
}
// quicksort sorts a slice of integers using quicksort algorithm
fun <T> quicksort(collection: Array<T>): Array<T> {
val length = collection.size
collection.reversed()
// Nothing to sort here
if (length <= 1) {
return collection
}
quicksortSubCollection(collection, 0, length - 1)
return collection
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 2,597 | KotlinGround | MIT License |
src/main/kotlin/com/anahoret/aoc2022/day14/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day14
import java.io.File
data class Point(val x: Int, val y: Int) {
fun moveDown(): Point {
return Point(x, y + 1)
}
fun moveDownLeft(): Point {
return Point(x - 1, y + 1)
}
fun moveDownRight(): Point {
return Point(x + 1, y + 1)
}
companion object {
fun parse(str: String): Point {
val (x, y) = str.split(",").map(String::toInt)
return Point(x, y)
}
}
}
class RockLine(start: Point, end: Point) {
constructor(startEnd: Pair<Point, Point>) : this(startEnd.first, startEnd.second)
companion object {
fun parse(str: String): List<RockLine> {
fun trimAndParse(s: String): Point = Point.parse(s.trim())
return str.split("->")
.map(::trimAndParse)
.zipWithNext()
.map(::RockLine)
}
}
val points = range(start.y, end.y).flatMap { y ->
range(start.x, end.x).map { x ->
Point(x, y)
}
}
private fun range(start: Int, end: Int): IntProgression {
return if (start < end) start..end
else start downTo end
}
}
sealed interface DropSandResult
class Landed(val point: Point) : DropSandResult
object WentToVoid : DropSandResult
class CaveMap(occupied: Set<Point>, private val hasFloor: Boolean) {
companion object {
fun parse(str: String, hasFloor: Boolean): CaveMap {
val lines = parseRockLines(str)
val occupied = lines.flatMap(RockLine::points).toSet()
return CaveMap(occupied, hasFloor)
}
private fun parseRockLines(str: String): List<RockLine> {
return str
.split("\n")
.flatMap(RockLine::parse)
}
}
private val occupied = occupied.toMutableSet()
private val sandSpawn = Point(500, 0)
private val floorLevel = occupied.maxOf { it.y } + 2
private val maxOccupiedY = if (hasFloor) floorLevel else occupied.maxOf(Point::y)
fun dropSand(): DropSandResult {
return dropSandFrom(sandSpawn)
.also { if (it is Landed) occupied.add(it.point) }
}
private fun dropSandFrom(point: Point): DropSandResult {
val down = point.moveDown()
val downLeft = point.moveDownLeft()
val downRight = point.moveDownRight()
return when {
point in occupied -> WentToVoid
isVoid(down) -> WentToVoid
isAir(down) -> dropSandFrom(down)
isVoid(downLeft) -> WentToVoid
isAir(downLeft) -> dropSandFrom(downLeft)
isVoid(downRight) -> WentToVoid
isAir(downRight) -> dropSandFrom(downRight)
else -> Landed(point)
}
}
private fun isAir(point: Point): Boolean {
return when {
hasFloor -> point.y < floorLevel && !occupied.contains(point)
else -> !occupied.contains(point)
}
}
private fun isVoid(point: Point): Boolean {
return !hasFloor && point.y > maxOccupiedY
}
}
fun main() {
val input = File("src/main/kotlin/com/anahoret/aoc2022/day14/input.txt")
.readText()
.trim()
// Part 1
part1(CaveMap.parse(input, hasFloor = false))
// Part 2
part2(CaveMap.parse(input, hasFloor = true))
}
private fun part1(map: CaveMap) {
var rounds = 0
while (map.dropSand() is Landed) { rounds++ }
println(rounds)
}
private fun part2(map: CaveMap) {
var rounds = 0
while (map.dropSand() is Landed) { rounds++ }
println(rounds)
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 3,603 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/easy/longest-common-prefix.kt | shevtsiv | 286,838,200 | false | null | package easy
class LongestCommonPrefixSolution {
/**
* Time Complexity: O(n^2)
* Space Complexity: O(k^2), where k - length of the first string
*/
fun longestCommonPrefixBruteforce(strs: Array<String>): String {
if (strs.isEmpty()) {
return ""
}
var prefix = strs[0]
var i = 1
while (i < strs.size) {
val str = strs[i]
while (!str.startsWith(prefix)) {
prefix = prefix.substring(0, prefix.length - 1)
}
i++
}
return prefix
}
/**
* Time Complexity: O(n^2)
* Space Complexity: O(1), worst case: O(k), where k = common prefix length
*/
fun longestCommonPrefixBruteforceUsingIndex(strs: Array<String>): String {
if (strs.isEmpty() || strs[0].isEmpty()) {
return ""
}
var i = 1
var j = 0
var symbol = strs[0][0]
while (i < strs.size) {
val str = strs[i]
if (j >= str.length) {
return str
}
val anotherSymbol = str[j]
if (symbol != anotherSymbol) {
return str.substring(0, j)
}
i++
if (i == strs.size) {
j++
i = 0
if (j >= strs[i].length) {
return strs[i]
}
symbol = strs[i][j]
}
}
return strs[0]
}
/**
* Time Complexity: O(n^2)
* Space Complexity: O(k^2), where k - length of the shortest string in the array
*/
fun longestCommonPrefixBruteforceUsingHorizontalScan(strs: Array<String>): String {
if (strs.isEmpty() || strs[0].isEmpty()) {
return ""
}
if (strs.size == 1) {
return strs[0]
}
var prefix = getCommonLongestPrefix(strs[0], strs[1])
for (i in 2 until strs.size) {
if (prefix.isEmpty()) {
return ""
}
val str = strs[i]
prefix = getCommonLongestPrefix(prefix, str)
}
return prefix
}
/**
* Time Complexity: O(min(n,m)), where n - length of the first string, m - length of the second string
* Space Complexity: O(1), worst case: O(k), where k - common prefix length which is shorter than the shorter string
*/
private fun getCommonLongestPrefix(first: String, second: String): String {
val minimumLengthString = if (first.length > second.length) {
second
} else {
first
}
for (i in minimumLengthString.indices) {
if (first[i] != second[i]) {
return minimumLengthString.substring(0, i)
}
}
return minimumLengthString
}
}
| 0 | Kotlin | 0 | 0 | 95d5f74069098beddf2aee14465f069302a51b77 | 2,847 | leet | MIT License |
src/Day11.kt | allwise | 574,465,192 | false | null |
fun main() {
fun part1(input: List<String>): Int {
val monkeys = Monkeys(input)
val res = monkeys.process()
println("res1: $res")
return res
}
fun part2(input: List<String>): Long {
val monkeys = Monkeys(input)
val res = monkeys.process2()
println("res2: $res")
return res
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
class Monkeys(val input:List<String>){
var monkeys = input.chunked(7).map { Monkey(it) }
val lcm = lcm(monkeys.map{it.testDiv})
fun process():Int{
monkeys.forEach(::println)
println()
println("runround 20")
repeat(20){
runRound()
}
println(monkeys)
return monkeys.map{it.inspections}.sorted().takeLast(2).let{it[0]*it[1]}
}
fun process2():Long{
println("part 2: ")
val lcm = lcm(monkeys.map{it.testDiv}.toSet().toList())
monkeys.forEach{it.lcm=lcm}
monkeys.forEach{it.part2=true}
// runRound()
monkeys.forEach(::println)
println("20")
repeat(20){
runRound()
monkeys.forEach(::println)
println()
}
// monkeys.forEach(::println)
println("1000")
repeat(980){
runRound()
}
monkeys.forEach(::println)
println()
monkeys.forEach(::println)
println("10000")
repeat(9000){
runRound()
}
monkeys.forEach(::println)
println()
return monkeys.map{it.inspections}.sorted().takeLast(2).let{it[0].toLong()*it[1]}
}
fun lcm(divers:List<Int>):Int{
var res = 1
divers.forEach{res*=it}
println("lcm $res")
println(divers)
return res
}
private fun runRound() {
monkeys.forEach { monkey ->
while (monkey.items.size > 0) {
val cast = monkey.handleItem()
monkeys[cast.second].items.add(cast.first)
}
}
}
}
class Monkey(var description:List<String>){
val testDiv:Int
var items:MutableList<Long>
var operation:List<String>
val throwToTrue:Int
val throwToFalse:Int
var inspections=0
var part2=false
var lcm = 1
init {
/**
* Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
*/
items = description[1].split(":")[1].split(",").map { it.trim().toLong() }.toMutableList()
operation = description[2].split(" ").takeLast(3)
testDiv = description[3].split(" ").last().toInt()
throwToTrue = description[4].split(" ").last().toInt()
throwToFalse = description[5].split(" ").last().toInt()
}
//
fun runOperation(oldValue: Long): Long {
val input1 = getValue(oldValue, operation[0])
val input2 = getValue(oldValue, operation[2])
if (operation[1].trim() == "*") {
val res:Long = (input1 * input2)
if(res>Int.MAX_VALUE) {
return (res % lcm)
}
return res
}
if (operation[1].trim() == "+") {
return input1 + input2
}
return oldValue
}
fun getValue(oldValue: Long, input:String):Long =
if(input == "old"){
oldValue
}else {
input.trim().toLong()
}
fun test(value:Long):Int{
return if(value % testDiv>0)
throwToTrue
else
throwToFalse
}
fun handleItem(): Pair<Long, Int> {
var item = items.first()
inspections++
items.remove(item)
item = runOperation(item)
if(!part2)
item /= 3
else {
val before= item.mod(testDiv)
item= item%lcm
val after = item.mod(testDiv)
if(before!=after){
println("item mod before $before after $after")
}
}
return if((item.mod(testDiv)) != 0){
(item to throwToFalse)
}else{
(item to throwToTrue)
}
}
override fun toString():String{
return """Monkey: checks: $inspections, items: $items operation = $operation, check: div $testDiv, true: $throwToTrue false: $throwToFalse part2: $part2"""
}
}
| 0 | Kotlin | 0 | 0 | 400fe1b693bc186d6f510236f121167f7cc1ab76 | 4,858 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/java/ru/igla/duocamera/utils/CameraSizes.kt | iglaweb | 414,899,591 | false | {"Kotlin": 85927, "Java": 2752} | package ru.igla.duocamera.utils
import android.graphics.Point
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.params.StreamConfigurationMap
import android.util.Size
import android.view.Display
import kotlin.math.max
import kotlin.math.min
/** Helper class used to pre-compute shortest and longest sides of a [Size] */
class SmartSize(width: Int, height: Int) {
val size = Size(width, height)
var long = max(size.width, size.height)
var short = min(size.width, size.height)
override fun toString() = "SmartSize(${long}x${short})"
}
/** Standard High Definition size for pictures and video */
val SIZE_1080P: SmartSize = SmartSize(1920, 1080)
val SIZE_VGA: SmartSize = SmartSize(640, 480)
/** Returns a [SmartSize] object for the given [Display] */
fun getDisplaySmartSize(display: Display): SmartSize {
val outPoint = Point()
display.getRealSize(outPoint)
return SmartSize(outPoint.x, outPoint.y)
}
/**
* Returns the largest available PREVIEW size. For more information, see:
* https://d.android.com/reference/android/hardware/camera2/CameraDevice and
* https://developer.android.com/reference/android/hardware/camera2/params/StreamConfigurationMap
*/
fun <T> getMaxPreviewOutputSize(
display: Display,
characteristics: CameraCharacteristics,
targetClass: Class<T>,
format: Int? = null
): Size {
// Find which is smaller: screen or 1080p
val screenSize = getDisplaySmartSize(display)
val hdScreen = screenSize.long >= SIZE_1080P.long || screenSize.short >= SIZE_1080P.short
val maxSize = if (hdScreen) SIZE_1080P else screenSize
return getPreviewOutputSize(maxSize, characteristics, targetClass, format)
}
fun <T> getMinPreviewOutputSize(
characteristics: CameraCharacteristics,
targetClass: Class<T>,
format: Int? = null
): Size {
return getPreviewOutputSize(SIZE_VGA, characteristics, targetClass, format)
}
fun <T> getPreviewOutputSize(
maxSize: SmartSize,
characteristics: CameraCharacteristics,
targetClass: Class<T>,
format: Int? = null
): Size {
// If image format is provided, use it to determine supported sizes; else use target class
val config = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP
)!!
if (format == null)
assert(StreamConfigurationMap.isOutputSupportedFor(targetClass))
else
assert(config.isOutputSupportedFor(format))
val allSizes = if (format == null)
config.getOutputSizes(targetClass) else config.getOutputSizes(format)
// Get available sizes and sort them by area from largest to smallest
val validSizes = allSizes
.sortedWith(compareBy { it.height * it.width })
.map { SmartSize(it.width, it.height) }.reversed()
// Then, get the largest output size that is smaller or equal than our max size
return validSizes.first { it.long <= maxSize.long && it.short <= maxSize.short }.size
} | 1 | Kotlin | 0 | 6 | 5743d5c22fdc96d2d2f0f0e2b00e17ee4c75147e | 2,974 | DuoCamera | Apache License 2.0 |
kotlin/graphs/shortestpaths/DijkstraHeap.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.shortestpaths
import java.util.stream.Stream
// https://en.wikipedia.org/wiki/Dijkstra's_algorithm
object DijkstraHeap {
// calculate shortest paths in O(E*log(V)) time and O(E) memory
fun shortestPaths(edges: Array<List<Edge>>, s: Int, prio: IntArray, pred: IntArray) {
Arrays.fill(pred, -1)
Arrays.fill(prio, Integer.MAX_VALUE)
prio[s] = 0
val q: PriorityQueue<Long> = PriorityQueue()
q.add(s.toLong())
while (!q.isEmpty()) {
val cur: Long = q.remove()
val curu = cur.toInt()
if (cur ushr 32 != prio[curu]) continue
for (e in edges[curu]) {
val v = e.t
val nprio = prio[curu] + e.cost
if (prio[v] > nprio) {
prio[v] = nprio
pred[v] = curu
q.add((nprio.toLong() shl 32) + v)
}
}
}
}
// Usage example
fun main(args: Array<String?>?) {
val cost = arrayOf(intArrayOf(0, 3, 2), intArrayOf(0, 0, -2), intArrayOf(0, 0, 0))
val n = cost.size
val graph: Array<List<Edge>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() }
for (i in 0 until n) {
for (j in 0 until n) {
if (cost[i][j] != 0) {
graph[i].add(Edge(j, cost[i][j]))
}
}
}
val dist = IntArray(n)
val pred = IntArray(n)
shortestPaths(graph, 0, dist, pred)
System.out.println(0 == dist[0])
System.out.println(3 == dist[1])
System.out.println(1 == dist[2])
System.out.println(-1 == pred[0])
System.out.println(0 == pred[1])
System.out.println(1 == pred[2])
}
class Edge(var t: Int, var cost: Int)
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,847 | codelibrary | The Unlicense |
src/main/kotlin/com/rtarita/days/Day3.kt | RaphaelTarita | 724,581,070 | false | {"Kotlin": 64943} | package com.rtarita.days
import com.rtarita.structure.AoCDay
import com.rtarita.util.day
import com.rtarita.util.exactlyOrNull
import com.rtarita.util.indexOfFirst
import kotlinx.datetime.LocalDate
import kotlin.math.max
import kotlin.math.min
object Day3 : AoCDay {
override val day: LocalDate = day(3)
private fun getAdjacent(x: Int, y: Int, xlast: Int, ylast: Int): List<Pair<Int, Int>> {
val xrange = max(x - 1, 0)..min(x + 1, xlast)
val yrange = max(y - 1, 0)..min(y + 1, ylast)
return xrange.flatMap { xAdj ->
yrange.map { yAdj ->
xAdj to yAdj
}
}
}
private fun adjacentNumbers(posX: Int, posY: Int, table: List<String>): List<Int> = buildList {
for (y in max(0, posY - 1)..min(posY + 1, table.size)) {
val leftNum = table[y].substring(0, posX)
.takeLastWhile { it.isDigit() }
val rightNum = table[y]
.substring(posX + 1)
.takeWhile { it.isDigit() }
if (table[y][posX].isDigit()) {
add((leftNum + table[y][posX] + rightNum).toInt())
} else {
leftNum.takeIf { it.isNotEmpty() }?.let { add(it.toInt()) }
rightNum.takeIf { it.isNotEmpty() }?.let { add(it.toInt()) }
}
}
}
override fun executePart1(input: String): Any {
val table = input.lines()
var sum = 0
for (y in table.indices) {
val row = table[y]
var x = 0
while (x < row.length) {
if (!row[x].isDigit()) {
++x
} else {
val end = row.indexOfFirst(x) { !it.isDigit() }.takeIf { it != -1 } ?: row.length
val include = (x..<end).flatMap { getAdjacent(it, y, row.lastIndex, table.lastIndex) }
.toSet()
.any { (xAdj, yAdj) ->
val char = table[yAdj][xAdj]
char != '.' && !char.isDigit()
}
if (include) {
sum += row.substring(x, end).toInt()
}
x = end
}
}
}
return sum
}
override fun executePart2(input: String): Any {
val table = input.lines()
var sum = 0
for (y in table.indices) {
for (x in table[y].indices) {
if (table[y][x] == '*') {
adjacentNumbers(x, y, table).exactlyOrNull(2)
?.let { sum += it.reduce { acc, elem -> acc * elem } }
}
}
}
return sum
}
} | 0 | Kotlin | 0 | 0 | 4691126d970ab0d5034239949bd399c8692f3bb1 | 2,749 | AoC-2023 | Apache License 2.0 |
2022/src/main/kotlin/day7_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.badInput
fun main() {
Day7Imp.run()
}
sealed class Cmd {
data class ChangeDir(val relative: String): Cmd()
data class ListFiles(val output: List<FsNode>): Cmd()
}
sealed class FsNode {
abstract val name: String
data class DirNode(
override val name: String,
var parentDir: DirNode?,
val files: MutableList<FsNode>
) : FsNode() {
override fun toString() = "dir $name"
}
data class FileNode(
override val name: String,
val size: Long
) : FsNode() {
override fun toString() = "file $name (sz = $size)"
}
}
data class Session(
val rootDir: FsNode.DirNode,
var currentDir: FsNode.DirNode
)
object Day7Imp : Solution<List<Cmd>>() {
override val name = "day7"
override val parser = Parser { input ->
val cmds = input.split("$ ").filter { it.isNotBlank() }
cmds.map { invoke ->
val (cmd, output) = invoke.split("\n", limit = 2).map { it.trim() }
when {
cmd.startsWith("cd") -> Cmd.ChangeDir(cmd.split(" ", limit = 2)[1].trim())
cmd.startsWith("ls") -> Cmd.ListFiles(
output.split("\n").map { it.trim() }.map {
val (p1, p2) = it.split(" ", limit = 2)
when (p1) {
"dir" -> FsNode.DirNode(p2, null, mutableListOf())
else -> FsNode.FileNode(p2, p1.toLong())
}
}
)
else -> badInput()
}
}.drop(1) // always starts with $ cd /
}
override fun part1(input: List<Cmd>): Long {
val root = FsNode.DirNode("/", null, mutableListOf())
val session = Session(root, root)
input.forEach {
execute(session, it)
}
var sum = 0L
walk(session.rootDir) {
val sz = size(it)
if (sz <= 100000) {
sum += sz
}
}
return sum
}
override fun part2(input: List<Cmd>): Long {
val root = FsNode.DirNode("/", null, mutableListOf())
val session = Session(root, root)
input.forEach {
execute(session, it)
}
val rootSize = size(session.rootDir)
val targetToDelete = rootSize - 40000000L
var bestDirSize = Long.MAX_VALUE
walk(session.rootDir) {
val sz = size(it)
if (sz in targetToDelete until bestDirSize) {
bestDirSize = sz
}
}
return bestDirSize
}
fun walk(dir: FsNode.DirNode, fn: (FsNode.DirNode) -> Unit) {
fn(dir)
dir.files.filterIsInstance<FsNode.DirNode>().forEach {
walk(it, fn)
}
}
fun size(dir: FsNode.DirNode): Long {
var size = 0L
for (child in dir.files) {
when (child) {
is FsNode.DirNode -> size += size(child)
is FsNode.FileNode -> size += child.size
}
}
return size
}
fun execute(session: Session, cmd: Cmd) {
val pwd = session.currentDir
when (cmd) {
is Cmd.ChangeDir -> {
when (cmd.relative) {
".." -> session.currentDir = pwd.parentDir!!
else -> {
val node = pwd.files.firstOrNull { it is FsNode.DirNode && it.name == cmd.relative }
if (node != null && node is FsNode.DirNode) {
node.parentDir = pwd // fix parent dir as we didn't have this from parsing
session.currentDir = node
} else {
val newNode = FsNode.DirNode(cmd.relative, pwd, mutableListOf())
pwd.files.add(newNode)
session.currentDir = newNode
}
}
}
}
is Cmd.ListFiles -> {
for (node in cmd.output) {
if (pwd.files.any { it.name == node.name }) {
continue
}
when (node) {
is FsNode.DirNode -> {
pwd.files.add(FsNode.DirNode(node.name, pwd, mutableListOf()))
}
is FsNode.FileNode -> {
pwd.files.add(FsNode.FileNode(node.name, node.size))
}
}
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 3,933 | aoc_kotlin | MIT License |
src/main/kotlin/aoc2023/Day07.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2023
import AoCDay
import aoc2023.Day07.Hand.Type.*
import util.illegalInput
import util.pow
import kotlin.math.max
// https://adventofcode.com/2023/day/7
object Day07 : AoCDay<Int>(
title = "Camel Cards",
part1ExampleAnswer = 6440,
part1Answer = 250951660,
part2ExampleAnswer = 5905,
part2Answer = 251481660,
) {
private const val CARDS = "AKQJT98765432"
private class Hand(val cards: String) {
init {
if (cards.length != 5 || !cards.all(CARDS::contains)) illegalInput(cards)
}
enum class Type { HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, FULL_HOUSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND }
}
private fun parseHandAndBid(input: String): Pair<Hand, Int> {
val (hand, bid) = input.split(' ', limit = 2)
return Pair(Hand(hand), bid.toInt())
}
private val POWS = run {
val base = max(Hand.Type.entries.size, CARDS.length)
List(6) { i -> base.pow(i) }
}
private inline fun Hand.strength(type: Hand.() -> Hand.Type, cardStrengths: String) = type().ordinal * POWS[5] +
cards.foldIndexed(0) { index, acc, card -> acc + cardStrengths.indexOf(card) * POWS[4 - index] }
private fun calculateTotalWinnings(input: String, cardStrengths: String, handType: (Hand) -> Hand.Type) = input
.lineSequence()
.map(::parseHandAndBid)
.map { (hand, bid) -> Pair(hand.strength(handType, cardStrengths), bid) }
.sortedBy { (handStrength, _) -> handStrength }
.foldIndexed(0) { index, acc, (_, bid) -> acc + (index + 1) * bid }
private fun handType(hand: Hand): Hand.Type {
val counts = hand.cards.groupingBy { it }.eachCount()
return when (counts.size) {
1 -> FIVE_OF_A_KIND
2 -> if (4 in counts.values) FOUR_OF_A_KIND else FULL_HOUSE
3 -> if (3 in counts.values) THREE_OF_A_KIND else TWO_PAIR
4 -> ONE_PAIR
else -> HIGH_CARD
}
}
private fun handTypeWithJokers(hand: Hand): Hand.Type {
val (jokers, nonJokers) = hand.cards.partition('J'::equals)
val nonJokerCounts = nonJokers.groupingBy { it }.eachCount()
return when (jokers.length) {
0 -> handType(hand)
1 -> when (nonJokerCounts.size) {
1 -> FIVE_OF_A_KIND
2 -> if (3 in nonJokerCounts.values) FOUR_OF_A_KIND else FULL_HOUSE
3 -> THREE_OF_A_KIND
else -> ONE_PAIR
}
2 -> when (nonJokerCounts.size) {
1 -> FIVE_OF_A_KIND
2 -> FOUR_OF_A_KIND
else -> THREE_OF_A_KIND
}
3 -> if (nonJokerCounts.size == 1) FIVE_OF_A_KIND else FOUR_OF_A_KIND
else -> FIVE_OF_A_KIND
}
}
override fun part1(input: String) = calculateTotalWinnings(input, cardStrengths = "23456789TJQKA", ::handType)
override fun part2(input: String) =
calculateTotalWinnings(input, cardStrengths = "J23456789TQKA", ::handTypeWithJokers)
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 3,062 | advent-of-code-kotlin | MIT License |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/common/Utils.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019.common
import java.util.*
fun <T>dijkstra(points: Iterable<T>, source: T, target: T, neighbours: (T) -> Iterable<T>): List<T>? {
val q = points.toMutableSet()
val dist = q.map { it to Int.MAX_VALUE }.toMap().toMutableMap()
val prev: MutableMap<T, T?> = q.map { it to null }.toMap().toMutableMap()
dist[source] = 0
while (q.isNotEmpty()) {
val u = dist.filter { q.contains(it.key) }.minBy { it.value }?.key ?: error("Q is empty")
q.remove(u)
if (u == target) {
val s = mutableListOf<T>()
var n: T? = target
if (prev[n] != null || n == source) {
while (n != null) {
s.add(n)
n = prev[n]
}
}
return s.reversed().toList()
}
for (v in neighbours(u).filter { q.contains(it) }) {
val alt = (dist[u] ?: 0) + 1
if (alt < dist[v]!!) {
dist[v] = alt
prev[v] = u
}
}
}
return null
}
fun dijkstra(points: Set<Pair<Int, Int>>, source: Pair<Int, Int>, target: Pair<Int, Int>) =
dijkstra(points, source, target) { point -> Direction.neighboursOf(point) }
fun <T : Any>bfs(source: T, target: T, neighbours: (T) -> Iterable<T>): List<T>? {
val q = ArrayDeque<T>()
val discovered = mutableSetOf<T>()
val prev = mutableMapOf<T, T>()
discovered.add(source)
q.add(source)
while (q.isNotEmpty()) {
val v = q.poll()
if (v == target) {
return generateSequence(target, { prev.getOrDefault(it, null)})
.toList()
.reversed()
}
neighbours(v).filter { !discovered.contains(it) }
.forEach {
discovered.add(it)
prev[it] = v
q.add(it)
}
}
return null
}
fun powerOf(num: Long, exponent: Long): Long = if (exponent == 0L) 1L else num * powerOf(num, exponent - 1L)
fun <T> generateCombinations(items: Set<T>): Set<Set<T>> {
val length = items.size
val combinations = mutableSetOf<Set<T>>()
for (i in 0 until (1 shl length)) {
val set = mutableSetOf<T>()
for (j in 0 until length) {
if ((i and (1 shl j)) > 0) {
set.add(items.elementAt(j))
}
}
combinations.add(set)
}
return combinations
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 2,474 | advent-of-code | Apache License 2.0 |
src/main/day05/day05.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day05
import java.util.*
import readInput
val stackIndices = listOf(1, 5, 9, 13, 17, 21, 25, 29, 33)
var stacks: List<Stack<Char>> = emptyList()
var moves: List<Move> = emptyList()
val regex by lazy { """move (\d+) from (\d) to (\d)""".toRegex() }
fun main() {
val input = readInput("main/day05/Day05")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): String {
input.parse()
rearrange(::movingSingleCrate)
return message()
}
fun part2(input: List<String>): String {
input.parse()
rearrange(::movingPartialStack)
return message()
}
private fun List<String>.parse(numOfRows: Int = 8, numOfStacks: Int = 9) {
stacks = take(numOfRows).parseToStacks(numOfStacks)
moves = drop(numOfRows + 2).parseMoves()
}
private fun rearrange(move: (Move, List<Stack<Char>>) -> Unit) {
moves.forEach {
move(it, stacks)
}
}
private fun movingSingleCrate(move: Move, stacks: List<Stack<Char>>) {
repeat(move.numberOfCrates) { _ ->
stacks[move.to - 1].push(stacks[move.from - 1].pop())
}
}
private fun movingPartialStack(move: Move, stacks: List<Stack<Char>>) {
val tmp = mutableListOf<Char>()
repeat(move.numberOfCrates) { _ ->
tmp.add(stacks[move.from - 1].pop())
}
tmp.reversed().forEach { c ->
stacks[move.to - 1].push(c)
}
}
private fun message() = stacks.map {
it.pop()
}.joinToString("")
fun List<String>.parseMoves(): List<Move> {
return this.map {
regex.matchEntire(it)?.destructured?.let { (count, from, to) ->
Move(from.toInt(), to.toInt(), count.toInt())
} ?: error("")
}
}
fun List<String>.parseToStacks(numOfStacks: Int): List<Stack<Char>> {
val result = mutableListOf<Stack<Char>>()
repeat(numOfStacks) { result.add(Stack()) }
this.reversed().forEach { s ->
s.forEachIndexed { index, c ->
if (index in stackIndices) {
if (c != ' ') result[(index / 4)].push(c)
}
}
}
return result
}
data class Move(val from: Int, val to: Int, val numberOfCrates: Int) | 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 2,126 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days_2020/Day11.kt | BasKiers | 434,124,805 | false | {"Kotlin": 40804} | package days_2020
import util.Day
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
class Day11 : Day(11, 2020) {
val input = inputList.map { row ->
row.toCharArray().map {
when (it) {
'#' -> Tile.OCCUPIED_SEAT
'L' -> Tile.EMPTY_SEAT
else -> Tile.FLOOR
}
}
}
enum class Tile {
FLOOR, EMPTY_SEAT, OCCUPIED_SEAT, WALL
}
fun getNextTile(floorPlan: List<List<Tile>>, tile: Tile, position: Pair<Int, Int>): Tile {
val (x, y) = position
val adjacentTiles: Map<Tile, Int> by lazy {
val subList = floorPlan.subList(max(0, y - 1), min(y + 2, floorPlan.size))
.map { row -> row.subList(max(0, x - 1), min(x + 2, row.size)) }
subList.flatten().groupBy { it }
.mapValues { (_, it) -> it.size }
}
return when (tile) {
Tile.OCCUPIED_SEAT -> if (adjacentTiles.getOrDefault(Tile.OCCUPIED_SEAT, 0) > 4) Tile.EMPTY_SEAT else tile
Tile.EMPTY_SEAT -> if (adjacentTiles.getOrDefault(Tile.OCCUPIED_SEAT, 0) == 0) Tile.OCCUPIED_SEAT else tile
else -> tile
}
}
fun getNextState(floorPlan: List<List<Tile>>): List<List<Tile>> {
return floorPlan.mapIndexed { y, rows ->
rows.mapIndexed { x, tile -> getNextTile(floorPlan, tile, x to y) }
}
}
val directions = listOf(1 to 0, 1 to 1, 0 to 1, -1 to 1, -1 to 0, -1 to -1, 0 to -1, 1 to -1)
fun getNextTile2(floorPlan: List<List<Tile>>, tile: Tile, position: Pair<Int, Int>): Tile {
val adjacentTiles: Map<Tile, Int> by lazy {
val subList = directions.map { (xDir, yDir) ->
var pos = position
var tileAtPos: Tile;
do {
pos = pos.first + xDir to pos.second + yDir
tileAtPos =
floorPlan.getOrElse(pos.second) { listOf(Tile.WALL) }.getOrElse(pos.first) { Tile.WALL };
} while (tileAtPos == Tile.FLOOR)
tileAtPos
}
subList.groupBy { it }
.mapValues { (_, it) -> it.size }
}
return when (tile) {
Tile.OCCUPIED_SEAT -> if (adjacentTiles.getOrDefault(Tile.OCCUPIED_SEAT, 0) > 4) Tile.EMPTY_SEAT else tile
Tile.EMPTY_SEAT -> if (adjacentTiles.getOrDefault(Tile.OCCUPIED_SEAT, 0) == 0) Tile.OCCUPIED_SEAT else tile
else -> tile
}
}
fun getNextState2(floorPlan: List<List<Tile>>): List<List<Tile>> {
return floorPlan.mapIndexed { y, rows ->
rows.mapIndexed { x, tile -> getNextTile2(floorPlan, tile, x to y) }
}
}
fun getOccupiedSeats(floorPlan: List<List<Tile>>): Int = floorPlan.flatten().count { it == Tile.OCCUPIED_SEAT }
fun floorPlanToString(floorPlan: List<List<Tile>>): String =
floorPlan.map { rows ->
rows.joinToString("") { tile ->
when (tile) {
Tile.OCCUPIED_SEAT -> "#"
Tile.EMPTY_SEAT -> "L"
Tile.FLOOR -> "."
Tile.WALL -> "|"
}
}
}.joinToString("\n")
fun statesAreEqual(stateA: List<List<Tile>>, stateB: List<List<Tile>>): Boolean =
stateA.flatten().zip(stateB.flatten()).all { (a, b) -> a == b }
override fun partOne(): Any {
var stateTransition = input to input
do {
stateTransition = stateTransition.second to getNextState(stateTransition.second)
} while (!statesAreEqual(stateTransition.first, stateTransition.second))
return getOccupiedSeats(stateTransition.second)
}
override fun partTwo(): Any {
var stateTransition = input to input
do {
stateTransition = stateTransition.second to getNextState2(stateTransition.second)
} while (!statesAreEqual(stateTransition.first, stateTransition.second))
return getOccupiedSeats(stateTransition.second)
}
} | 0 | Kotlin | 0 | 0 | 870715c172f595b731ee6de275687c2d77caf2f3 | 4,089 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/2021/Day13_1.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
var switched = false
val points = ArrayList<Pair<Int, Int>>()
val instructions = ArrayList<Pair<String, Int>>()
File("input/2021/day13").forEachLine { line ->
if (line.isEmpty()) {
switched = true
} else {
if (!switched) {
val (x,y) = line.split(",").map { it.toInt() }
points.add(Pair(x,y))
} else {
val inst = line.split(" ")
val (dim,v) = inst[2].split("=")
instructions.add(Pair(dim,v.toInt()))
}
}
}
val xMax = points.maxOf { it.first }
val yMax = points.maxOf { it.second }
var grid = ArrayList<ArrayList<String>>()
for (y in 0..yMax) {
val row = ArrayList<String>()
for (x in 0..xMax) {
if (points.any { it.first == x && it.second == y }) {
row.add("#")
} else row.add(".")
}
grid.add(row)
}
fun List<List<String>>.merge(other: List<List<String>>) = mapIndexed { y, row ->
val mappedRow = row.mapIndexed { x, v -> if (other[y][x] == "#" || v == "#") "#" else "." }
ArrayList<String>().apply { addAll(mappedRow) }
}
fun ArrayList<ArrayList<String>>.fold(dim: String, value: Int): ArrayList<ArrayList<String>> {
val newGrid = ArrayList<ArrayList<String>>()
if (dim == "y") {
val top = subList(0,value)
val bottom = subList(value+1,grid.size).reversed()
newGrid.addAll(top.merge(bottom))
} else if (dim == "x") {
val left = map { row -> row.subList(0,value) }
val right = map { row -> row.subList(value+1,row.size).reversed() }
newGrid.addAll(left.merge(right))
}
return newGrid
}
grid = grid.fold(instructions[0].first, instructions[0].second)
println(grid.flatMap { it }.filter { it == "#" }.size) | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 1,753 | adventofcode | MIT License |
src/main/aoc2023/Day02.kt | Clausr | 575,584,811 | false | {"Kotlin": 65961} | package aoc2023
class Day02(input: List<String>) {
private val parsedInput = input.map {
val gameId = it.substringBefore(":").split(" ").last().toInt()
println("GameID: $gameId")
val rawThrows = it.substringAfter(": ")
val reveals = rawThrows.split("; ")
val cubesInReveals = reveals.map {
it.split(", ").map {
val reveal = it.split(" ")
reveal.first().toInt() to reveal.last()
}
}
Game(gameId, cubesInReveals)
}
data class Game(
val id: Int,
val throws: List<List<Pair<Int, String>>>
)
// Rules: only 12 red cubes, 13 green cubes, and 14 blue cubes
fun solvePart1(): Int {
val result = parsedInput.sumOf { game ->
val possible = game.throws.all { t ->
t.all { t1 ->
when {
t1.second == "red" -> t1.first <= 12
t1.second == "green" -> t1.first <= 13
t1.second == "blue" -> t1.first <= 14
else -> {
println("Lel"); false
}
}
}
}
if (possible) game.id else 0
}
return result
}
fun solvePart2(): Int {
return parsedInput.sumOf { game ->
val flat = game.throws.flatten()
val r = flat.filter { it.second == "red" }.maxOf { it.first }
val g = flat.filter { it.second == "green" }.maxOf { it.first }
val b = flat.filter { it.second == "blue" }.maxOf { it.first }
r * g * b
}
}
} | 1 | Kotlin | 0 | 0 | dd33c886c4a9b93a00b5724f7ce126901c5fb3ea | 1,703 | advent_of_code | Apache License 2.0 |
src/day16/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day16
import assert
import println
import readInput
enum class Direction(val row: Int, val column: Int) {
UP(-1, 0),
DOWN(1, 0),
LEFT(0, -1),
RIGHT(0, 1)
}
fun main() {
val OPPOSITES = mapOf(
Direction.UP to Direction.DOWN,
Direction.DOWN to Direction.UP,
Direction.LEFT to Direction.RIGHT,
Direction.RIGHT to Direction.LEFT
)
class Path(val from: Direction, val to: List<Direction>)
class Position(val row: Int, val column: Int) {
fun move(direction: Direction): Position {
return Position(row + direction.row, column + direction.column)
}
}
class LavaProductionFacility(input: List<String>) {
val map = input.map { it.toCharArray() }
val height = map.size
val width = map.first().size
inner class LightTrace(width: Int, height: Int) {
val map = Array(height) { Array(width) { mutableListOf<Path>() } }
fun addIfNotExist(position: Position, path: Path): Boolean {
if (map[position.row][position.column].contains(path)) return false
map[position.row][position.column] += path
return true
}
fun sum(): Int {
return map.sumOf { row ->
row.count { it.size > 0 }
}
}
}
val tileTypes = hashMapOf(
'|' to listOf(
Path(Direction.UP, listOf(Direction.DOWN)),
Path(Direction.DOWN, listOf(Direction.UP)),
Path(Direction.LEFT, listOf(Direction.UP, Direction.DOWN)),
Path(Direction.RIGHT, listOf(Direction.UP, Direction.DOWN))
),
'-' to listOf(
Path(Direction.LEFT, listOf(Direction.RIGHT)),
Path(Direction.RIGHT, listOf(Direction.LEFT)),
Path(Direction.UP, listOf(Direction.LEFT, Direction.RIGHT)),
Path(Direction.DOWN, listOf(Direction.LEFT, Direction.RIGHT))
),
'\\' to listOf(
Path(Direction.LEFT, listOf(Direction.DOWN)),
Path(Direction.DOWN, listOf(Direction.LEFT)),
Path(Direction.RIGHT, listOf(Direction.UP)),
Path(Direction.UP, listOf(Direction.RIGHT))
),
'/' to listOf(
Path(Direction.LEFT, listOf(Direction.UP)),
Path(Direction.UP, listOf(Direction.LEFT)),
Path(Direction.RIGHT, listOf(Direction.DOWN)),
Path(Direction.DOWN, listOf(Direction.RIGHT))
),
'.' to listOf(
Path(Direction.LEFT, listOf(Direction.RIGHT)),
Path(Direction.RIGHT, listOf(Direction.LEFT)),
Path(Direction.UP, listOf(Direction.DOWN)),
Path(Direction.DOWN, listOf(Direction.UP))
)
)
private fun get(position: Position): Char {
return map[position.row][position.column]
}
private fun isValid(position: Position): Boolean {
if (position.row !in 0..<height) return false
if (position.column !in 0..<width) return false
return true
}
private fun lightStep(lightTrace: LightTrace, position: Position, direction: Direction) {
if (!isValid(position)) return
var path = tileTypes[get(position)]?.find { it.from == OPPOSITES[direction] }!!
if (!lightTrace.addIfNotExist(position, path)) return
path.to.map {
lightStep(lightTrace, position.move(it), it)
}
}
fun countEnergised(entryPosition: Position, entryDirection: Direction): Int {
var lightTrace = LightTrace(width, height)
lightStep(lightTrace, entryPosition, entryDirection)
return lightTrace.sum()
}
private fun entryPoints(): List<Pair<Position, Direction>> {
return listOf((0..<width).map {
listOf(
Pair(Position(0, it), Direction.DOWN),
Pair(Position(height - 1, it), Direction.UP)
)
}.flatten(),
(0..<height).map {
listOf(
Pair(Position(it, 0), Direction.RIGHT),
Pair(Position(it, width - 1), Direction.LEFT),
)
}.flatten()).flatten()
}
fun maxEnergised(): Int {
return entryPoints().maxOfOrNull { this.countEnergised(it.first, it.second) }!!
}
}
LavaProductionFacility(readInput("day16/test1"))
.countEnergised(Position(0,0), Direction.RIGHT)
.assert(46)
"Part 1:".println()
LavaProductionFacility(readInput("day16/input"))
.countEnergised(Position(0,0), Direction.RIGHT)
.assert(8901).println()
LavaProductionFacility(readInput("day16/test1"))
.maxEnergised()
.assert(51)
"Part 2:".println()
LavaProductionFacility(readInput("day16/input"))
.maxEnergised()
.assert(9064)
.println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 5,175 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/Day25.kt | todynskyi | 573,152,718 | false | {"Kotlin": 47697} | import kotlin.math.pow
fun main() {
fun snafuToInt(snafu: String): Long = snafu.reversed()
.withIndex()
.fold(0L) { acc, indexedValue ->
val weight = 5.0.pow(indexedValue.index.toDouble()).toLong()
acc + when (indexedValue.value) {
'-' -> -weight
'=' -> -2 * weight
else -> (indexedValue.value - '0') * weight
}
}
fun intToSnafu(n: Long, prefix: Boolean = false): String = if (n == 0L && prefix) ""
else if (n == 0L) "0"
else {
when (val floorMod = Math.floorMod(n, 5)) {
3 -> intToSnafu(n / 5 + 1, true) + "="
4 -> intToSnafu(n / 5 + 1, true) + "-"
else -> intToSnafu(n / 5, true) + floorMod.toString()
}
}
fun part1(input: List<String>): String = intToSnafu(input.sumOf { snafuToInt(it) })
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
check(part1(testInput) == "2=-1=0")
val input = readInput("Day25")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | 5f9d9037544e0ac4d5f900f57458cc4155488f2a | 1,102 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/aoc2023/Day18.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2023
import utils.*
import kotlin.math.abs
fun main(): Unit = with(Day18) {
part1(testInput).checkEquals(62)
part1(input)
.checkEquals(35244)
// .sendAnswer(part = 1, day = "18", year = 2023)
part2(testInput).checkEquals(952408144115)
.alsoPrintln()
part2(input)
.alsoPrintln()
.checkEquals(85070763635666)
// .sendAnswer(part = 2, day = "18", year = 2023)
}
object Day18 {
fun part1(input: List<String>): Long {
val v = buildSet<Vertex> {
var curr = Vertex(0, 0)
add(curr)
for (line in input) {
val (d, count) = line.split(" ").let {
it.first().first() to it[1].toInt()
}
val process: Vertex.() -> Vertex = when (d) {
'R' -> Vertex::right
'L' -> Vertex::left
'U' -> Vertex::up
'D' -> Vertex::down
else -> error("sss")
}
repeat(count) {
curr.process()
curr = curr.process()
add(curr)
}
}
}
val rowRange = v.minOf { it.y }..v.maxOf { it.y }
val colRange = v.minOf { it.x }..v.maxOf { it.x }
val rectangleBoundsThatNotWalked = buildList<Vertex> {
for (i in rowRange){
add(Vertex(colRange.first, i))
add(Vertex(colRange.last, i))
}
for (j in colRange){
add(Vertex(j, rowRange.first))
add(Vertex(j, rowRange.last))
}
}.filter { it !in v }
val q = ArrayDeque<Vertex>(rectangleBoundsThatNotWalked)
val seen = hashSetOf<Vertex>()
while (q.any()) {
val curr = q.removeFirst()
if (curr in seen)
continue
seen += curr
curr.allAdjacent().filter {
it.isInBounds(rowRange, colRange) && it !in v
}
.also(q::addAll)
}
val rowsCount = ((rowRange.last - rowRange.first) + 1).toLong()
val colsCount = ((colRange.last - colRange.first) + 1)
return rowsCount * colsCount - seen.size
}
@OptIn(ExperimentalStdlibApi::class)
fun part2(input: List<String>): Long = input.solve {
it.substringAfter("#").take(6)
.let {
it.last() to it.take(5).hexToInt()
}
}
fun List<String>.solve(parser: (String) -> Pair<Char, Int>): Long {
var currVertex = LongVertex(0, 0)
var area = 0L
var walkedCount = 1L
for (line in this) {
val (dir, steps) = parser(line)
val newVertex = when (dir) {
'0' -> currVertex.right(steps.toLong())
'1' -> currVertex.down(steps.toLong())
'2' -> currVertex.left(steps.toLong())
'3' -> currVertex.up(steps.toLong())
else -> error("sss")
}
// shoelace area
area += (newVertex.x - currVertex.x) * (newVertex.y + currVertex.y)
walkedCount += steps
currVertex = newVertex
}
return abs(area) / 2 + walkedCount / 2 + 1
}
val input
get() = readInput("Day18", "aoc2023")
val testInput
get() = readInput("Day18_test", "aoc2023")
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 3,548 | Kotlin-AOC-2023 | Apache License 2.0 |
src/Day05.kt | Riari | 574,587,661 | false | {"Kotlin": 83546, "Python": 1054} | import kotlin.collections.ArrayDeque
fun main() {
data class Procedure(val move: Int, val from: Int, val to: Int)
fun parseInitialState(input: List<String>): List<ArrayDeque<Char>> {
val state = mutableListOf<ArrayDeque<Char>>()
val regex = Regex("[A-Z]")
for (line in input) {
if (line == "") break
regex.findAll(line).forEach {
val stack = ((it.range.first - 1) / 4) // get zero-based stack index
while (state.size <= stack) state.add(ArrayDeque()) // grow state as needed
state[stack].addFirst(it.value.toCharArray()[0]) // add crate to bottom of stack
}
}
return state
}
fun parseProcedures(input: List<String>): List<Procedure> {
val procedures = mutableListOf<Procedure>()
for (line in input) {
if (!line.startsWith("move")) continue
val regex = Regex("[0-9]+")
val proc = regex.findAll(line).toList().map { it.value.toInt() }
procedures.add(Procedure(proc[0], proc[1] - 1, proc[2] - 1))
}
return procedures
}
fun solve(state: List<ArrayDeque<Char>>, procedures: List<Procedure>, canMoveMultipleAtOnce: Boolean): String {
for (procedure in procedures) {
val cratesToMove = mutableListOf<Char>()
repeat(procedure.move) {
val crate = state[procedure.from].removeLast()
cratesToMove.add(crate)
}
if (canMoveMultipleAtOnce) cratesToMove.reverse()
for (crate in cratesToMove) {
state[procedure.to].add(crate)
}
}
var message = ""
for (stack in state) {
message += stack.removeLast()
}
return message
}
fun part1(state: List<ArrayDeque<Char>>, procedures: List<Procedure>): String {
return solve(state, procedures, false)
}
fun part2(state: List<ArrayDeque<Char>>, procedures: List<Procedure>): String {
return solve(state, procedures, true)
}
// TODO: find a way of deep-copying a list of ArrayDeque instead of re-parsing the input each time
val testInput = readInput("Day05_test")
val testProcedures = parseProcedures(testInput)
check(part1(parseInitialState(testInput), testProcedures) == "CMZ")
check(part2(parseInitialState(testInput), testProcedures) == "MCD")
val input = readInput("Day05")
val procedures = parseProcedures(input)
println(part1(parseInitialState(input), procedures))
println(part2(parseInitialState(input), procedures))
}
| 0 | Kotlin | 0 | 0 | 8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d | 2,643 | aoc-2022 | Apache License 2.0 |
LeetCode/LongestConsecutiveSequence.kt | MartinWie | 702,541,017 | false | {"Kotlin": 90565} | import org.junit.Test
import kotlin.test.assertEquals
class LongestConsecutiveSequence {
private fun longestConsecutive(nums: IntArray): Int {
val numsSorted = nums.toSortedSet()
var overallHighestCons = 0
var currentHighestCons = if (nums.isEmpty()) 0 else 1
var lastNum: Int? = null
for (num in numsSorted) {
if (lastNum != null && lastNum + 1 == num) {
currentHighestCons++
} else {
currentHighestCons = 1
}
lastNum = num
if (currentHighestCons > overallHighestCons) overallHighestCons = currentHighestCons
}
return overallHighestCons
}
private fun longestConsecutive2(nums: IntArray): Int {
if (nums.isEmpty()) return 0
if (nums.size == 1) return 1
val numsHashSet = nums.toHashSet()
var maxStreak = 1
for (num in numsHashSet) {
if (!numsHashSet.contains(num-1)) {
var currentStreak = 1
var currentNum = num + 1
while (numsHashSet.contains(currentNum)) {
currentStreak++
currentNum++
}
maxStreak = maxOf(maxStreak, currentStreak)
}
}
return maxStreak
}
@Test
fun testLongestConsecutive() {
assertEquals(4, longestConsecutive(intArrayOf(100, 4, 200, 1, 3, 2)))
assertEquals(9, longestConsecutive(intArrayOf(0, 3, 7, 2, 5, 8, 4, 6, 0, 1)))
assertEquals(0, longestConsecutive(intArrayOf()))
assertEquals(7, longestConsecutive(intArrayOf(9, 1, 4, 7, 3, -1, 0, 5, 8, -1, 6)))
}
}
| 0 | Kotlin | 0 | 0 | 47cdda484fabd0add83848e6000c16d52ab68cb0 | 1,694 | KotlinCodeJourney | MIT License |
src/main/kotlin/days/Day2.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.DayInput
class Day2 : Day("2") {
class Line {
var game: Int = 0
var sets: List<BallSet> = mutableListOf()
}
class BallSet {
var red: Int = 0
var blue: Int = 0
var green: Int = 0
}
fun lines(input: List<String>): List<Line> {
return input.map {
val split = it.split(": ")
Line().apply {
game = split[0].replace("Game ", "").toInt()
sets = split[1].split("; ").map {
BallSet().apply {
it.split(", ").forEach { setEelement ->
val elementsSplitted = setEelement.split(" ")
when (elementsSplitted[1]) {
"red" -> red = elementsSplitted[0].toInt()
"blue" -> blue = elementsSplitted[0].toInt()
"green" -> green = elementsSplitted[0].toInt()
}
}
}
}
}
}
}
override fun partOne(dayInput: DayInput): Any {
val template = BallSet().apply {
red = 12
blue = 14
green = 13
}
val lines = lines(dayInput.inputList())
val filter = lines.filter {
it.sets.all {
it.red <= template.red && it.blue <= template.blue && it.green <= template.green
}
}
return filter.map { it.game }.sum()
}
override fun partTwo(dayInput: DayInput): Any {
val lines = lines(dayInput.inputList())
return lines.map {
it.sets.map { it.green }.max() * it.sets.map { it.blue }.max() * it.sets.map { it.red }.max()
}.sum()
}
}
fun main() {
Day2().run()
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 1,859 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-24.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import java.math.BigInteger
fun main() {
val input = readInputLines(2023, "24-input")
val test1 = readInputLines(2023, "24-test1")
println("Part1:")
part1(test1, 7.toLong()..27).println()
part1(input, 200000000000000 .. 400000000000000).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>, testArea: LongRange): Long {
val parsed = input.map { line ->
val (p, v) = line.split(""" @\s+""".toRegex())
val position = p.split(""",\s+""".toRegex()).map(String::toBigInteger)
val velocity = v.split(""",\s+""".toRegex()).map(String::toBigInteger)
position to velocity
}
var result = 0L
for (i in 0..parsed.size - 2) {
for (j in i + 1..<parsed.size) {
val (p1, v1) = parsed[i]
val (p2, v2) = parsed[j]
val intersect = intersectsWithin(p1, v1, p2, v2, testArea)
if (intersect) result++
}
}
return result
}
private fun part2(input: List<String>, print: Boolean = false): BigInteger {
val parsed = input.map { line ->
val (p, v) = line.split(""" @\s+""".toRegex())
val position = p.split(""",\s+""".toRegex()).map(String::toBigInteger)
val velocity = v.split(""",\s+""".toRegex()).map(String::toBigInteger)
position to velocity
}
val equations = parsed.take(5).flatMap { s ->
(0..1).map { i ->
Pair(s.first[i], s.second[i])
}
}
if (print) println("Starting equations")
val vars = listOf('x', 'y')
equations.forEachIndexed { index, item ->
val (p, v) = item
val variable = vars[index % 2]
val num = index / 2 + 1
if (print) println("$p ${v.withSign()} * t${num} = $variable + v$variable * t$num")
}
if (print) println()
if (print) println("Substitution for ts")
val subs = equations.mapIndexed { index, item ->
val (p, v) = item
val qs = listOf(-p, v, (index % 2).toBigInteger(), (index / 2 + 1).toBigInteger())
val variable = vars[qs[2].toInt()]
if (print) println("t${qs[3]} = ($variable ${qs[0].withSign()}) / (${qs[1]} - v$variable)")
qs
}
if (print) println()
if (print) println("Removed ts")
val e2 = (0..4).map { i ->
val s1 = subs[i * 2]
val s2 = subs[i * 2 + 1]
val qs = listOf(s2[1], -s1[1], s2[0], -s1[0], s1[0] * s2[1] - s2[0] * s1[1])
if (print) println("x * vy - y * vx = ${qs[0]} * x ${(qs[1]).withSign()} * y ${(qs[2]).withSign()} * vx ${(qs[3]).withSign()} * vy ${(qs[4]).withSign()}")
qs
}
if (print) println()
if (print) println("Linearize")
val s1 = e2.first()
val e3 = e2.drop(1).map { s2 ->
val qs = listOf(s1[0] - s2[0], s1[1] - s2[1], s1[2] - s2[2], s1[3] - s2[3], s1[4] - s2[4])
if (print) println("${qs[0]} * x ${(qs[1]).withSign()} * y ${(qs[2]).withSign()} * vx ${(qs[3]).withSign()} * vy ${qs[4].withSign()} = 0")
qs.toMutableList()
}.toMutableList()
val svy = e3.first()
if (print) println()
if (print) println("Eliminate vy = (${svy[0]} * x ${(svy[1]).withSign()} * y ${(svy[2]).withSign()} * vx ${svy[4].withSign()}) / ${(-svy[3])}")
val e4 = e3.drop(1).map { s ->
val qs = listOf(s[0] * -svy[3] + svy[0] * s[3], s[1] * -svy[3] + svy[1] * s[3], s[2] * -svy[3] + svy[2] * s[3], svy[4] * s[3] + s[4] * -svy[3])
if (print) println("${qs[0]} * x ${(qs[1]).withSign()} * y ${(qs[2]).withSign()} * vx ${(qs[3]).withSign()} = 0")
qs
}
val svx = e4.first()
if (print) println()
if (print) println("Eliminate vx = (${svx[0]} * x ${(svx[1]).withSign()} * y ${(svx[3]).withSign()}) / ${(-svx[2])}")
val e5 = e4.drop(1).map { s ->
val qs = listOf(s[0] * -svx[2] + svx[0] * s[2], s[1] * -svx[2] + svx[1] * s[2], svx[3] * s[2] + s[3] * -svx[2])
if (print) println("${qs[0]} * x ${(qs[1]).withSign()} * y ${(qs[2]).withSign()} = 0")
qs
}
if (print) println()
val (sy, sx) = e5
if (print) println("Eliminate y = (${sy[0]} * x ${(sy[2]).withSign()}) / ${-sy[1]}")
val x = -(sy[2] * sx[1] + sx[2] * -sy[1]) / (sx[0] * -sy[1] + sy[0] * sx[1])
if (print) println("x = $x")
val y = (sy[0] * x + sy[2]) / -sy[1]
if (print) println("y = $y")
val vx = (svx[0] * x + svx[1] * y + svx[3]) / -svx[2]
if (print) println("vx = $vx")
val vy = (svy[0] * x + svy[1] * y + svy[2] * vx + svy[4]) / -svy[3]
if (print) println("vy = $vy")
val t1 = (x + subs[0][0]) / (subs[0][1] - vx)
if (print) println("t1 = $t1")
val t2 = (x + subs[2][0]) / (subs[2][1] - vx)
if (print) println("t2 = $t2")
val vz = (parsed[0].first[2] + parsed[0].second[2] * t1 - parsed[1].first[2] - parsed[1].second[2] * t2) / (t1 - t2)
if (print) println("vz = $vz")
val z = parsed[0].first[2] + parsed[0].second[2] * t1 - vz * t1
if (print) println("z = $z")
return x + y + z
}
private fun intersectsWithin(
p1: List<BigInteger>,
v1: List<BigInteger>,
p2: List<BigInteger>,
v2: List<BigInteger>,
range: LongRange
): Boolean {
val (vx1, vy1) = v1
val (vx2, vy2) = v2
val (x1, y1) = p1
val (x3, y3) = p2
val x2 = x1 + vx1
val y2 = y1 + vy1
val x4 = x3 + vx2
val y4 = y3 + vy2
val d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if (d == BigInteger.ZERO) {
return false
}
val x = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)
val y = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)
val extendedRange = if (BigInteger.ZERO < d) range.first.toBigInteger() * d .. range.last.toBigInteger() * d else range.last.toBigInteger() * d .. range.first.toBigInteger() * d
val inRange = x in extendedRange && y in extendedRange
val futureA = if (BigInteger.ZERO < d) BigInteger.ZERO <= (x - x1 * d) * vx1 else BigInteger.ZERO > (x - x1 * d) * vx1
val futureB = if (BigInteger.ZERO < d) BigInteger.ZERO <= (x - x3 * d) * vx2 else BigInteger.ZERO > (x - x3 * d) * vx2
val inFuture = futureA && futureB
return inRange && inFuture
}
private fun BigInteger.withSign() = if (BigInteger.ZERO <= this) "+ $this" else "- ${this.abs()}"
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 6,471 | advent-of-code | MIT License |
src/Day07.kt | roxanapirlea | 572,665,040 | false | {"Kotlin": 27613} | private data class File(
val name: String,
var fileSize: Long = 0,
val children: MutableList<File> = mutableListOf()
)
private sealed class Instruction {
data class MoveIn(val name: String) : Instruction()
object MoveOut : Instruction()
object MoveToRoot : Instruction()
object List : Instruction()
}
fun main() {
fun String.getInstruction(): Instruction {
val trimmedInstr = substring(2)
if (trimmedInstr == "ls") return Instruction.List
val (_, direction) = substring(2).split(' ')
return when (direction) {
".." -> Instruction.MoveOut
"/" -> Instruction.MoveToRoot
else -> Instruction.MoveIn(direction)
}
}
fun buildFileSystem(input: List<String>): File {
val root = File("/")
val fileStack = ArrayDeque<File>()
input.forEach { line ->
if (line.startsWith('$')) {
when (val instr = line.getInstruction()) {
is Instruction.MoveIn -> {
val nextFile = fileStack.last().children.first { it.name == instr.name }
fileStack.addLast(nextFile)
}
Instruction.MoveOut -> {
val previousDirectory = fileStack.removeLast()
fileStack.last().fileSize += previousDirectory.fileSize
}
Instruction.MoveToRoot -> {
if (fileStack.isNotEmpty()) {
var previousDirectory = fileStack.removeLast()
while (fileStack.isNotEmpty()) {
fileStack.last().fileSize += previousDirectory.fileSize
previousDirectory = fileStack.removeLast()
}
}
fileStack.add(root)
}
Instruction.List -> {
// Do nothing, the files will be added in the next lines
}
}
} else {
val (sizeOrType, name) = line.split(" ")
val file = File(name, sizeOrType.toLongOrNull() ?: 0)
fileStack.last().apply {
children.add(file)
fileSize += file.fileSize
}
}
}
if (fileStack.isNotEmpty()) {
var previousDirectory = fileStack.removeLast()
while (fileStack.isNotEmpty()) {
fileStack.last().fileSize += previousDirectory.fileSize
previousDirectory = fileStack.removeLast()
}
}
return root
}
fun getSmallDirectories(file: File, maxSize: Long, files: MutableSet<File>): Set<File> {
if (file.fileSize <= maxSize && file.children.isNotEmpty()) files.add(file)
file.children.forEach { child ->
files.addAll(getSmallDirectories(child, maxSize, files))
}
return files
}
fun getDirectoryToDeleteSize(file: File, minSize: Long, prevMaxSize: Long): Long {
var maxSize = prevMaxSize
if (file.fileSize in minSize until maxSize && file.children.isNotEmpty()) {
maxSize = file.fileSize
}
file.children.forEach { child ->
val size = getDirectoryToDeleteSize(child, minSize, maxSize)
if (size < maxSize) maxSize = size
}
return maxSize
}
fun part1(input: List<String>): Long {
val root = buildFileSystem(input)
return getSmallDirectories(root, 100000, mutableSetOf())
.sumOf { it.fileSize }
}
fun part2(input: List<String>): Long {
val root = buildFileSystem(input)
val minDeleteSize = root.fileSize - 40000000
return getDirectoryToDeleteSize(root, minDeleteSize, root.fileSize)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 6c4ae6a70678ca361404edabd1e7d1ed11accf32 | 4,221 | aoc-2022 | Apache License 2.0 |
src/year2021/Day7.kt | drademacher | 725,945,859 | false | {"Kotlin": 76037} | package year2021
import readLines
import kotlin.math.abs
fun main() {
val input = readLines("2021", "day7").map { it.toInt() }
val testInput = readLines("2021", "day7_test").map { it.toInt() }
check(part1(testInput) == 37)
println("Part 1:" + part1(input))
check(part2(testInput) == 168)
println("Part 2:" + part2(input))
}
private fun part1(input: List<Int>): Int {
return (input.min()..input.max())
.map { goal -> Pair(goal, input.sumOf { abs(it - goal) }) }
.minByOrNull { it.second }!!
.second
}
private fun part2(input: List<Int>): Int {
return (input.min()..input.max())
.map { goal -> Pair(goal, input.sumOf { gauss(abs(it - goal)) }) }
.minByOrNull { it.second }!!
.second
}
private fun gauss(n: Int): Int = n * (n + 1) / 2
| 0 | Kotlin | 0 | 0 | 4c4cbf677d97cfe96264b922af6ae332b9044ba8 | 819 | advent_of_code | MIT License |
src/main/kotlin/Monkeys.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | import java.math.BigInteger
fun main() = Monkeys.solve()
object Monkeys {
private var inspectedBy = mutableListOf<Int>()
fun solve() {
val input = readInput()
for (monkey in input) {
inspectedBy.add(monkey.id, 0)
}
for (turn in 1..10000) {
runTurn(input)
// println("After turn $turn, items by monkey ${input.map { it.items }}")
}
val inspected = inspectedBy.sorted().takeLast(2)
println("Inspected: $inspected, score: ${inspected.first().toBigInteger() * inspected.last().toBigInteger()}")
}
private fun readInput(): List<Monkey> {
var id = 0
var items = mutableListOf<BigInteger>()
var operation: Operation? = null
var testDiv = 0
var ifTrue = 0
var ifFalse = 0
val result = mutableListOf<Monkey>()
fun addMonkey() {
if (operation == null) {
throw Error("Invalid input, no operation before empty line")
} else {
val test = Test(testDiv, ifTrue, ifFalse)
result.add(id, Monkey(id, items, operation!!, test))
}
}
generateSequence(::readLine).forEach {
when {
it.startsWith(monkeyPrefix) -> {
id = it.substringAfter(monkeyPrefix).substringBefore(":").toInt(10)
items = mutableListOf<BigInteger>()
testDiv = 0
ifTrue = 0
ifFalse = 0
}
it.startsWith(itemsPrefix) -> {
items = it.substringAfter(itemsPrefix).split(", ").map { it.toBigInteger(10) }.toMutableList()
}
it.startsWith(operationPrefix) -> {
operation = parseOperation(it)
}
it.startsWith(testPrefix) -> {
testDiv = it.substringAfter(testPrefix).toInt(10)
}
it.startsWith(ifTruePrefix) -> {
ifTrue = it.substringAfter(ifTruePrefix).toInt(10)
}
it.startsWith(ifFalsePrefix) -> {
ifFalse = it.substringAfter(ifFalsePrefix).toInt(10)
}
(it == "") -> {
addMonkey()
}
}
}
addMonkey()
return result
}
private fun runTurn(input: List<Monkey>) {
for (monkey in input) {
runRound(input, monkey)
// println("round ${monkey.id} ends")
}
}
private fun runRound(input: List<Monkey>, monkey: Monkey) {
val base = input.map { it.test.testDiv }.reduce {acc, x -> x * acc}.toBigInteger()
for (item in monkey.items) {
val worry = monkey.operation.exec(item).mod(base)
inspectedBy[monkey.id] += 1
// println("Item $item, worry after inspection $worry")
val target = if (worry.mod(monkey.test.testDiv.toBigInteger()) == BigInteger.ZERO) {
input[monkey.test.ifTrue]
} else {
input[monkey.test.ifFalse]
}
target.items.add(worry)
// println("Passing to monkey ${target.id}")
}
monkey.items.clear()
}
}
val monkeyPrefix = "Monkey "
val itemsPrefix = " Starting items: "
val operationPrefix = " Operation: new = "
val testPrefix = " Test: divisible by "
val ifTruePrefix = " If true: throw to monkey "
val ifFalsePrefix = " If false: throw to monkey "
private data class Monkey(val id: Int, val items: MutableList<BigInteger>, val operation: Operation, val test: Test)
sealed interface OpInput
object Old : OpInput
data class Just(val value: BigInteger): OpInput
enum class Op {
Plus,
Mul
}
data class Operation(val a: OpInput, val b: OpInput, val op: Op) {
fun exec(input: BigInteger): BigInteger {
val x = when (a) {
Old -> input
is Just -> a.value
}
val y = when (b) {
Old -> input
is Just -> b.value
}
return when (op) {
Op.Plus -> x + y
Op.Mul -> x * y
}
}
}
private fun parseOperation(line: String): Operation {
val match = "(\\w+) ([+*]) (\\w+)".toRegex().matchEntire(line.substringAfter(operationPrefix))
val op = when (match!!.groupValues[2]) {
"*" -> Op.Mul
"+" -> Op.Plus
else -> throw Error("Unexpected op")
}
val a = parseOpInput(match.groupValues[1])
val b = parseOpInput(match.groupValues[3])
return Operation(a, b, op)
}
private fun parseOpInput(string: String): OpInput = when (string) {
"old" -> Old
else -> Just(string.toBigInteger(10))
}
private data class Test(val testDiv: Int, val ifTrue: Int, val ifFalse: Int) | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 4,863 | aoc2022 | MIT License |
src/main/kotlin/q1_50/q21_30/Solution23.kt | korilin | 348,462,546 | false | null | package q1_50.q21_30
import java.util.*
/**
* https://leetcode-cn.com/problems/merge-k-sorted-lists
*/
class Solution23 {
/**
* 优先队列
* 时间复杂度:与分治合并算法一样都是 O(kn×log(k))
*/
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
val nodePriorityQueue = PriorityQueue<ListNode> { a, b -> a.`val` - b.`val`}
for (node in lists) {
node?.let { nodePriorityQueue.add(node) }
}
val head = ListNode(0)
var tail = head
while (nodePriorityQueue.isNotEmpty()) {
tail.next = nodePriorityQueue.poll()
tail = tail.next!!
tail.next?.let { nodePriorityQueue.add(it) }
}
return head.next
}
/*
* 分治合并算法
*/
fun mergeKLists0(lists: Array<ListNode?>): ListNode? {
fun mergeTwoLinked(n1:ListNode?, n2:ListNode?): ListNode? {
val head = ListNode(0)
var tail = head
var node1 = n1
var node2 = n2
while (node1!=null || node2!=null) {
if (node2 == null || (node1!=null && node1.`val` <= node2.`val`)) {
tail.next = node1
node1 = node1!!.next
}else{
tail.next = node2
node2 = node2.next
}
tail = tail.next!!
}
return head.next
}
fun merging(ls: Array<ListNode?>): ListNode? {
if (ls.size == 1) return ls[0]
val mergeArray = arrayOfNulls<ListNode>(if (ls.size % 2 == 0) ls.size / 2 else ls.size / 2 + 1)
var i = 0
while (i < ls.size) {
if (i == ls.size - 1) mergeArray[i / 2] = ls[i]
else {
mergeTwoLinked(ls[i], ls[i+1])?.let { mergeArray[i / 2] = it }
}
i += 2
}
return merging(mergeArray)
}
if (lists.isEmpty()) return null
return merging(lists)
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
} | 0 | Kotlin | 0 | 1 | 1ce05efeaf34536fff5fa6226bdcfd28247b2660 | 2,153 | leetcode_kt_solution | MIT License |
src/Day04.kt | pydaoc | 573,843,750 | false | {"Kotlin": 8484} | fun main() {
fun checkMinusLists(list1: IntRange, list2: IntRange): Boolean {
return !list1.minus(list2).any() || !list2.minus(list1).any()
}
fun checkIntersectLists(list1: IntRange, list2: IntRange): Boolean {
return list1.intersect(list2).any() || list2.intersect(list1).any()
}
fun determineAssignmentPairs(input: List<String>, checkLists: (list1: IntRange, list2: IntRange) -> Boolean): Int {
var numberOfFullyContainsPairs = 0
for (line in input) {
val lineParts = line.split(',')
val linePart1 = lineParts[0]
val linePart2 = lineParts[1]
val valuesForLinePart1 = linePart1.split('-').map { it.toInt() }
val valuesForLinePart2 = linePart2.split('-').map { it.toInt() }
val value1ForLinePart1 = valuesForLinePart1[0]
val value2ForLinePart1 = valuesForLinePart1[1]
val value1ForLinePart2 = valuesForLinePart2[0]
val value2ForLinePart2 = valuesForLinePart2[1]
val list1 = IntRange(value1ForLinePart1, value2ForLinePart1)
val list2 = IntRange(value1ForLinePart2, value2ForLinePart2)
if (checkLists(list1, list2)) {
numberOfFullyContainsPairs++
}
}
return numberOfFullyContainsPairs
}
fun part1(input: List<String>): Int {
return determineAssignmentPairs(input, ::checkMinusLists)
}
fun part2(input: List<String>): Int {
return determineAssignmentPairs(input, ::checkIntersectLists)
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 970dedbfaf09d12a29315c6b8631fa66eb394054 | 1,661 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/demonwav/mcdev/util/SemanticVersion.kt | robertizotov-zz | 101,105,621 | false | {"Kotlin": 979869, "Lex": 10506, "HTML": 7115, "Groovy": 4245, "Java": 1290} | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import com.demonwav.mcdev.util.SemanticVersion.Companion.VersionPart.PreReleasePart
import com.demonwav.mcdev.util.SemanticVersion.Companion.VersionPart.ReleasePart
/**
* Represents a comparable and generalised "semantic version".
* Each constituent part (delimited by periods in a version string) contributes
* to the version ranking with decreasing priority from left to right.
*/
class SemanticVersion(val parts: List<VersionPart>) : Comparable<SemanticVersion> {
val versionString = parts.map { it.versionString }.joinToString(".");
override fun compareTo(other: SemanticVersion): Int {
// Zipping limits the compared parts to the shorter version, then we perform a component-wise comparison
// Short-circuits if any component of this version is smaller/older
val result = parts.zip(other.parts).fold(0) { acc, (a, b) -> if (acc == -1) acc else a.compareTo(b) }
// When all the parts are equal, the longer version wins
// Generally speaking, 1.0 is considered older than 1.0.1 (see MC 1.12 vs 1.12.1)
if (parts.size != other.parts.size && result == 0) {
return parts.size - other.parts.size
}
return result
}
override fun equals(other: Any?) =
when (other) {
is SemanticVersion -> parts.size == other.parts.size && parts.zip(other.parts).all { (a, b) -> a == b }
else -> false
}
override fun hashCode() = parts.hashCode()
companion object {
/**
* Parses a version string into a comparable representation.
* @throws IllegalArgumentException if any part of the version string cannot be parsed as integer or split into pre-release parts.
*/
fun parse(value: String): SemanticVersion {
fun parseInt(part: String): Int =
if (part.all { it.isDigit() })
part.toInt()
else
throw IllegalArgumentException("Failed to parse version part as integer: $part")
val parts = value.split('.').map {
if (it.contains("_pre")) {
// There have been cases of Forge builds for MC pre-releases (1.7.10_pre4)
// We're consuming the 10_pre4 and extracting 10 and 4 from it
val subParts = it.split("_pre")
if (subParts.size == 2) {
PreReleasePart(parseInt(subParts[0]), parseInt(subParts[1]))
} else {
throw IllegalArgumentException("Failed to split pre-release version part into two numbers: $it")
}
} else {
ReleasePart(parseInt(it))
}
}
return SemanticVersion(parts)
}
sealed class VersionPart : Comparable<VersionPart> {
abstract val versionString: String
data class ReleasePart(val version: Int) : VersionPart() {
override val versionString = version.toString()
override fun compareTo(other: VersionPart) =
when (other) {
is PreReleasePart -> if (version != other.version) version - other.version else 1
is ReleasePart -> version - other.version
}
}
data class PreReleasePart(val version: Int, val pre: Int) : VersionPart() {
override val versionString = "${version}_pre$pre"
override fun compareTo(other: VersionPart) =
when (other) {
is PreReleasePart -> if (version != other.version) version - other.version else pre - other.pre
is ReleasePart -> if (version != other.version) version - other.version else -1
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | 9b91deed668fce98cd21474b9135ec9b92212c2b | 4,044 | Minecraft-dev_JetBrains-plugin | MIT License |
src/main/kotlin/com/nibado/projects/advent/y2017/Day22.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.Direction
import com.nibado.projects.advent.Point
import com.nibado.projects.advent.resourceLines
object Day22 : Day {
private val input = resourceLines(2017, 22).mapIndexed { y, s -> s.trim().toCharArray().mapIndexed { x, c -> Point(x, y) to (if (c == '#') State.INFECTED else State.CLEAN) } }.flatMap { it }.toMap()
private enum class State { CLEAN, WEAKENED, INFECTED, FLAGGED }
override fun part1() = solve(10000,
{ s, d ->
when (s) {
State.INFECTED -> d.cw()
else -> d.ccw()
}
},
{
when (it) {
State.CLEAN -> State.INFECTED
else -> State.CLEAN
}
})
override fun part2() = solve(10000000,
{ s, d ->
when (s) {
State.CLEAN -> d.ccw()
State.INFECTED -> d.cw()
State.FLAGGED -> d.cw().cw()
State.WEAKENED -> d
}
},
{
when (it) {
State.CLEAN -> State.WEAKENED
State.WEAKENED -> State.INFECTED
State.INFECTED -> State.FLAGGED
State.FLAGGED -> State.CLEAN
}
})
private fun solve(iterations: Int, dir: (State, Direction) -> Direction, state: (State) -> State): String {
val points = input.toMutableMap()
val min = Point(points.keys.minByOrNull { it.x }!!.x, points.keys.minByOrNull { it.y }!!.y)
val max = Point(points.keys.maxByOrNull { it.x }!!.x, points.keys.maxByOrNull { it.y }!!.y)
var current = Point(min.x + (max.x - min.x) / 2, min.y + (max.y - min.y) / 2)
var direction = Direction.NORTH
var count = 0
(1..iterations).forEach {
direction = dir(points[current] ?: State.CLEAN, direction)
points[current] = state(points[current] ?: State.CLEAN)
if (points[current] == State.INFECTED) {
count++
}
current = current.plus(direction)
}
return count.toString()
}
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 2,325 | adventofcode | MIT License |
difficultycalc/src/main/kotlin/com/stehno/dmt/difficulty/DifficultyCalculation.kt | cjstehno | 143,009,387 | false | null | package com.stehno.dmt.difficulty
import com.stehno.dmt.difficulty.model.Challenger
object DifficultyCalculation {
private val xpForCr = mapOf(
Pair("0", 10), Pair("1/8", 25), Pair("1/4", 50), Pair("1/2", 100),
Pair("1", 200), Pair("2", 450), Pair("3", 700), Pair("4", 1100),
Pair("5", 1800), Pair("6", 2300), Pair("7", 2900), Pair("8", 3900),
Pair("9", 5000), Pair("10", 5900), Pair("11", 7200), Pair("12", 8400),
Pair("13", 10000), Pair("14", 11500), Pair("15", 11500), Pair("16", 15000),
Pair("17", 18000), Pair("18", 20000), Pair("19", 22000), Pair("20", 25000),
Pair("21", 33000), Pair("22", 41000), Pair("23", 50000), Pair("24", 62000),
Pair("25", 75000), Pair("26", 90000), Pair("27", 105000), Pair("28", 120000),
Pair("29", 135000), Pair("30", 155000)
)
private var multipliers = mapOf(
Pair(1, 1.0), Pair(2, 1.5), Pair(3, 2.0), Pair(4, 2.0),
Pair(5, 2.0), Pair(6, 2.0), Pair(7, 2.5), Pair(8, 2.5),
Pair(9, 2.5), Pair(10, 2.5), Pair(11, 3.0), Pair(12, 3.0),
Pair(13, 3.0), Pair(14, 3.0), Pair(15, 4.0)
)
private fun calculateEffectiveXp(challengers: List<Challenger>): Int {
var totalXp = 0
challengers.forEach { c ->
totalXp += (xpForCr[c.challenge]!! * c.count)
}
val multiplier = multipliers[challengers.sumBy { it.count }] ?: 4.0
return (totalXp * multiplier).toInt()
}
fun difficulty(level: Int, challengers: List<Challenger>): DifficultyRating {
val diffs = DifficultyRating.values().toMutableList()
diffs.reverse()
val xp = calculateEffectiveXp(challengers)
val dr = diffs.find { d -> d.xps[level - 1] < xp }
return when (dr != null) {
true -> dr!!
else -> DifficultyRating.EASY
}
}
}
enum class DifficultyRating(val xps: List<Int>) {
EASY(listOf(100, 200, 300, 500, 1000, 1200, 1400, 1800, 2200, 2400, 3200, 4000, 4400, 5000, 5600, 6400, 8000, 8400, 9600, 11200, 12000)),
MEDIUM(listOf(200, 400, 600, 1000, 2000, 2400, 3000, 3600, 4400, 4800, 6400, 8000, 8800, 10000, 11200, 12800, 15600, 16800, 19600, 22800, 24000)),
HARD(listOf(300, 636, 900, 1500, 3000, 3600, 4400, 5600, 6400, 7600, 9600, 12000, 13600, 15200, 17200, 19200, 23600, 25200, 29200, 34400, 36000)),
DEADLY(listOf(400, 800, 1600, 2000, 4400, 5600, 6800, 8400, 9600, 11200, 14400, 18000, 20400, 22800, 25600, 28800, 35200, 38000, 43600, 50800, 54000))
} | 1 | Kotlin | 0 | 1 | 5bfedc56ad901db11ac77a5a1a45a998ba979668 | 2,520 | dmtools | The Unlicense |
src/day01/Day01.kt | scottpeterson | 573,109,888 | false | {"Kotlin": 15611} | fun main() {
fun part1(input: List<String>): Int {
val testInput = readInput("/day01/Day01_test")
var map: MutableMap<Int, Int> = mutableMapOf()
var key = 1
testInput.forEach {
if (it == "") {
++key
return@forEach
}
map[key] = map[key]?.plus(it.toInt()) ?: 0.plus(it.toInt())
}
return map.values.maxOrNull()!!
}
fun part2(input: List<String>): Int {
val testInput = readInput("/day01/Day01_test")
var map: MutableMap<Int, Int> = mutableMapOf()
var key = 1
testInput.forEach {
if (it == "") {
++key
return@forEach
}
map[key] = map[key]?.plus(it.toInt()) ?: 0.plus(it.toInt())
}
val sortedValues = map.toList().sortedByDescending { (key, value) -> value }.toMap().values
print(sortedValues.take(3).sum())
return sortedValues.take(3).sum()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// check(part1(testInput) == 72240)
//
val input = readInput("/day01/Day01_test")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0d86213c5e0cd5403349366d0f71e0c09588ca70 | 1,274 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day18/Day18.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day18
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day18/Day18.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 18 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Point(
val x: Int,
val y: Int,
val z: Int,
)
@Suppress("SameParameterValue")
private fun parse(path: String): Set<Point> =
File(path).readLines().mapTo(HashSet()) { line ->
line.split(",")
.map { it.toInt() }
.let { (x, y, z) -> Point(x, y, z) }
}
private fun Point.neighbors(): Set<Point> {
return setOf(
Point(x + 1, y + 0, z + 0),
Point(x - 1, y + 0, z + 0),
Point(x + 0, y + 1, z + 0),
Point(x + 0, y - 1, z + 0),
Point(x + 0, y + 0, z + 1),
Point(x + 0, y + 0, z - 1),
)
}
private fun part1(data: Set<Point>): Int =
data.flatMap { it.neighbors() }
.count { it !in data }
private fun part2(data: Set<Point>): Int {
val xRange = (data.minOf { it.x } - 1)..(data.maxOf { it.x } + 1)
val yRange = (data.minOf { it.y } - 1)..(data.maxOf { it.y } + 1)
val zRange = (data.minOf { it.z } - 1)..(data.maxOf { it.z } + 1)
val start = Point(
xRange.first,
yRange.first,
zRange.first,
)
val queue = ArrayDeque<Point>().apply { add(start) }
val visited = mutableSetOf<Point>()
var area = 0
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
if (point in visited) {
continue
}
visited += point
for (neighbor in point.neighbors()) {
val (x, y, z) = neighbor
if (x in xRange && y in yRange && z in zRange) {
if (neighbor in data) {
area += 1
} else if (neighbor !in visited) {
queue += neighbor
}
}
}
}
return area
}
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 2,062 | advent-of-code-2022 | MIT License |
src/main/kotlin/y2021/Day04.kt | jforatier | 432,712,749 | false | {"Kotlin": 44692} | package y2021
// Considering a grid as full-line of Int
typealias Grid = List<Int>
class Day04(private val data: List<String>) {
private fun getDrew(input: List<String>): List<Int> {
return input[0] // <= Get the first line
.split(",") // <= Split values with "," separator
.map { it.toInt() } // <= Values are int, convert them
}
private fun getGrids(input: List<String>): List<Grid> {
return input
.drop(2) // <= Skip drew lines (used in getDrew)
.chunked(6) // <= Split into lists of blocs of 6 lines
.map { boardLines -> // <= For each chunk/bloc (of 6 lines), treat them as grid
boardLines
.take(5) // <= Take a bloc of 5 lines
.flatMap { it.split(" ") } // <= Split values with " " separator
.filter { it.isNotBlank() } // <= Remove remaining spaces
.map { it.toInt() } // <= Remaining values are int, convert them
}
.toList()
}
private fun isBingo(board: List<Int>, numbers: Set<Int>): Boolean {
// Browse grid values in two dimensions with 5 iterations
for (i in 0..4) {
// Check rows
val start = i * 5
// In a one-line grid, values in a row is index multiple of 5
val row = listOf(board[start], board[start + 1], board[start + 2], board[start + 3], board[start + 4])
if (numbers.containsAll(row)) return true
// Check columns
// In a one-line grid, values in a column is index addin a multiple of 5
val column = listOf(board[i], board[i + 5], board[i + 10], board[i + 15], board[i + 20])
if (numbers.containsAll(column)) return true
}
return false
}
private fun calculateResult(board: List<Int>, numbersChecked: Set<Int>): Int {
return (board - numbersChecked).sum() * numbersChecked.last()
}
fun part1(): Int {
val bingoDraw: List<Int> = getDrew(data)
val grids: List<Grid> = getGrids(data)
val numbersChecked = mutableSetOf<Int>()
bingoDraw.forEach {
numbersChecked.add(it)
grids.firstOrNull { grid -> isBingo(grid, numbersChecked) }?.let { winningGrid ->
return calculateResult(winningGrid, numbersChecked)
}
}
return 0
}
fun part2(): Int {
val bingoDraw: List<Int> = getDrew(data)
var grids: List<Grid> = getGrids(data)
val numbersChecked = mutableSetOf<Int>()
bingoDraw.forEach {
numbersChecked.add(it)
if (grids.size != 1) {
grids = grids.filter { grid -> !isBingo(grid, numbersChecked) }.toList()
} else {
if (isBingo(grids.first(), numbersChecked))
return calculateResult(grids.first(), numbersChecked)
}
}
return 0
}
//region
} | 0 | Kotlin | 0 | 0 | 2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae | 3,171 | advent-of-code-kotlin | MIT License |
src/day03/Day03.kt | henrikrtfm | 570,719,195 | false | {"Kotlin": 31473} | package day03
import utils.Resources.resourceAsListOfString
fun main() {
fun parseInput(line: String): Rucksack{
val firstCompartment = mutableSetOf<Char>()
val secondCompartment = mutableSetOf<Char>()
line.chunked(line.length/2)
.first()
.forEach {
firstCompartment.add(it)
}
line.chunked(line.length/2)
.last()
.forEach {
secondCompartment.add(it)
}
return Rucksack(firstCompartment,secondCompartment)
}
fun part1(rucksacks: List<Rucksack>): Int {
return rucksacks
.flatMap { it.firstCompartment.intersect(it.secondCompartment) }
.sumOf { Rucksack.priority(it) }
}
fun part2(rucksacks: List<Set<Char>>): Int {
return rucksacks
.windowed(3,3)
.flatMap { rucksacksGrouped ->
rucksacksGrouped
.reduce(){first, next -> first.intersect(next)} }
.sumOf { Rucksack.priority(it) }
}
val input = resourceAsListOfString("src/day03/Day03.txt")
val rucksacks = input.map { parseInput(it) }
val rucksacks2 = input.map { it.toSet() }
println(part1(rucksacks))
println(part2(rucksacks2))
}
data class Rucksack(
val firstCompartment: Set<Char>,
val secondCompartment : Set<Char>
){
companion object{
private val priorities = ('a'..'z').union('A'..'Z')
.mapIndexed{ index, value -> value to index + 1}
.toMap()
fun priority(type: Char): Int{
return priorities.getOrDefault(type, 0)
}
}
} | 0 | Kotlin | 0 | 0 | 20c5112594141788c9839061cb0de259f242fb1c | 1,657 | aoc2022 | Apache License 2.0 |
day-13/src/main/kotlin/TransparentOrigami.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | fun main() {
println("Part One Solution: ${partOne()}")
println("Part Two Solution: ${partTwo()}")
}
private fun partOne(): Int {
val folds = mutableListOf<String>()
val map = Array(1400) { Array(1400) { "." } }
var readingFolds = false
readInputLines().forEach {
if (it.isBlank()) {
readingFolds = true
return@forEach
}
if (readingFolds) {
folds.add(it)
} else {
val (x, y) = it.split(",")
map[y.toInt()][x.toInt()] = "#"
}
}
val (coordinate, value) = folds[0].split(" ")[2].split("=")
val horizontal = coordinate == "y"
fold(map, horizontal, value.toInt())
return map.flatMap { it.asIterable() }
.count { it == "#" }
}
private fun fold(map: Array<Array<String>>, horizontal: Boolean, value: Int) {
if (horizontal) {
for (i in 0 until value) {
for (j in map[i].indices) {
if (map[i][j] == "#" || map[value * 2 - i][j] == "#") {
map[i][j] = "#"
map[value * 2 - i][j] = "."
}
}
}
} else {
for (j in 0 until value) {
for (i in map.indices) {
if (map[i][j] == "#" || map[i][value * 2 - j] == "#") {
map[i][j] = "#"
map[i][value * 2 - j] = "."
}
}
}
}
}
private fun partTwo(): Int {
val folds = mutableListOf<String>()
val map = Array(2000) { Array(2000) { "." } }
var readingFolds = false
readInputLines().forEach {
if (it.isBlank()) {
readingFolds = true
return@forEach
}
if (readingFolds) {
folds.add(it)
} else {
val (x, y) = it.split(",")
map[y.toInt()][x.toInt()] = "#"
}
}
folds.forEach {
val (coordinate, value) = it.split(" ")[2].split("=")
val horizontal = coordinate == "y"
fold(map, horizontal, value.toInt())
}
map.forEach {
if (it.contains("#")) {
println(it.joinToString(" "))
}
}
return -1
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 2,346 | aoc-2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountUnreachablePairs.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
/**
* 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
* @see <a href="https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph">
* Source</a>
*/
fun interface CountUnreachablePairs {
fun countPairs(n: Int, edges: Array<IntArray>): Long
}
class CountUnreachablePairsDFS : CountUnreachablePairs {
private val x: MutableList<MutableList<Int>> = ArrayList()
override fun countPairs(n: Int, edges: Array<IntArray>): Long {
for (i in 0 until n) x.add(ArrayList())
for (edge in edges) {
x[edge[0]].add(edge[1]) // make graph
x[edge[1]].add(edge[0])
}
var res: Long = 0
var sum = n.toLong()
val visited = BooleanArray(n)
for (i in 0 until n) if (!visited[i]) {
val curr = dfs(i, visited, IntArray(1)) // find size of connected component
sum -= curr
res += curr * sum
}
return res
}
private fun dfs(node: Int, visited: BooleanArray, count: IntArray): Int {
if (visited[node]) return count[0]
visited[node] = true
count[0]++
for (curr in x[node]) dfs(curr, visited, count)
return count[0]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,877 | kotlab | Apache License 2.0 |
2021/app/src/main/kotlin/net/sympower/aok2021/tonis/Day07.kt | tonisojandu | 573,036,346 | false | {"Rust": 158858, "Kotlin": 15806, "Shell": 1265} | package net.sympower.aok2021.tonis
import kotlin.math.abs
fun main() {
println("1st: ${day07Part01("/Day07.in")}")
println("2nd: ${day07Part02("/Day07.in")}")
}
fun day07Part01(fileIn: String): Int {
return calculateOptimalFuel(fileIn)
}
fun day07Part02(fileIn: String): Int {
return calculateOptimalFuel(fileIn, progressiveFuelUsage = true)
}
fun calculateOptimalFuel(fileIn: String, progressiveFuelUsage: Boolean = false): Int {
val crabPositions = readLineFromResource(fileIn) { line ->
line.split(",")
.map { it.toInt() }
}.flatten()
.sorted()
.toIntArray()
return findLocalMinimum(crabPositions.size / 2, crabPositions, progressiveFuelUsage)
}
fun findLocalMinimum(from: Int, crabPositions: IntArray, progressiveFuelUsage: Boolean): Int {
val midFuelRequirement = calculateFuelRequirement(from, crabPositions, progressiveFuelUsage)
if (from == 0 || from == crabPositions.size - 1) {
return midFuelRequirement
}
if (midFuelRequirement > calculateFuelRequirement(from - 1, crabPositions, progressiveFuelUsage)) {
return findLocalMinimum(from - 1, crabPositions, progressiveFuelUsage)
} else if (midFuelRequirement > calculateFuelRequirement(from + 1, crabPositions, progressiveFuelUsage)) {
return findLocalMinimum(from + 1, crabPositions, progressiveFuelUsage)
}
return midFuelRequirement
}
fun calculateFuelRequirement(position: Int, crabPositions: IntArray, progressiveFuelUsage: Boolean): Int {
return crabPositions.sumOf { calculatePositionFuelUsage(it, position, progressiveFuelUsage) }
}
fun calculatePositionFuelUsage(position: Int, crabPosition: Int, progressiveFuelUsage: Boolean): Int =
if (progressiveFuelUsage) {
val diff = abs(crabPosition - position)
(diff * (diff + 1)) / 2
} else {
abs(crabPosition - position)
} | 0 | Rust | 0 | 0 | 5ee0c3fb2e461dcfd4a3bdd7db3efae9a4d5aabd | 1,819 | to-advent-of-code | MIT License |
src/main/kotlin/days/Day16.kt | andilau | 429,557,457 | false | {"Kotlin": 103829} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2015/day/16",
date = Date(day = 16, year = 2015)
)
class Day16(input: List<String>) : Puzzle {
private val aunts = input.map(AuntSueDescription::from).toSet()
private val signature = AuntSueSignature
override fun partOne(): Int =
aunts.toMutableSet()
.apply { removeIf { !signature.matchesButOutdated(it) } }
.single().id
override fun partTwo(): Int =
aunts.toMutableSet()
.apply { removeIf { !signature.matchesWithRanges(it) } }
.single().id
data class AuntSueDescription(val id: Int, val properties: Map<String, Int>) {
companion object {
fun from(line: String): AuntSueDescription {
val id = line.substringBefore(':').substringAfter("Sue ").toInt()
val properties = line.substringAfter(": ")
.split(", ")
.associate { property ->
property
.split(": ", limit = 2)
.let { it.first() to it.last().toInt() }
}
return AuntSueDescription(id, properties)
}
}
}
object AuntSueSignature {
private val properties: Map<String, Int> = """
children: 3
cats: 7
samoyeds: 2
pomeranians: 3
akitas: 0
vizslas: 0
goldfish: 5
trees: 3
cars: 2
perfumes: 1
""".trimIndent().lines()
.associate { it.substringBefore(": ") to it.substringAfter(": ").toInt() }
fun matchesButOutdated(description: AuntSueDescription): Boolean =
description.properties.all { (key, value) ->
properties.containsKey(key) && properties[key] == value
}
fun matchesWithRanges(description: AuntSueDescription) =
description.properties.all { (key, value) ->
properties.containsKey(key) &&
when (key) {
"cats", "trees" -> properties[key]!! < value
"pomeranians", "goldfish" -> properties[key]!! > value
else -> properties[key] == value
}
}
}
}
| 0 | Kotlin | 0 | 0 | 55932fb63d6a13a1aa8c8df127593d38b760a34c | 2,416 | advent-of-code-2015 | Creative Commons Zero v1.0 Universal |
src/Day04.kt | eps90 | 574,098,235 | false | {"Kotlin": 9738} | fun <T> List<T>.destructed() = Pair(first(), last())
fun main() {
fun prepareSections(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map { line ->
line.split(",")
.map { s -> s.split("-").let { IntRange(it[0].toInt(), it[1].toInt()) } }
.destructed()
}
}
fun part1(input: List<String>): Int {
return prepareSections(input).count { (firstGroup, secondGroup) ->
firstGroup.all { it in secondGroup } || secondGroup.all { it in firstGroup }
}
}
fun part2(input: List<String>): Int {
return prepareSections(input).count { (firstGroup, secondGroup) ->
firstGroup.any { it in secondGroup }
}
}
val testInput = readInput("Day04_test")
println(part1(testInput))
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bbf58c512fddc0ef1112c3bee5e5c6d43f5aabc0 | 981 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/io/riko/Calculator.kt | laguiar | 278,205,629 | false | null | package io.riko
import io.riko.Strategy.*
import java.math.RoundingMode
private val DEFAULT_WEIGHT_FACTOR = 0.65 to 0.35
private const val MINIMAL_WEIGHT = 0.50
fun calculatePie(input: CalculationInput): List<Slice> =
when (input.strategy) {
YIELD -> calculateByDividendYield(input.stocks)
RATING -> calculateByRating(input.stocks)
else -> calculateByRatingAndYield(input.stocks, input.strategy)
}
private fun calculateByDividendYield(stocks: Set<Stock>): List<Slice> {
val sum = stocks.sumByDouble { it.dividendYield }
return stocks.map { stock ->
val weight = stock.dividendYield.div(sum) * 100
buildSlice(stock.ticker, weight)
}.sortedByDescending { it.weight }
}
private fun calculateByRating(stocks: Set<Stock>): List<Slice> {
val sum = stocks.sumByDouble { it.rating.toDouble() }
return stocks.map { stock ->
val weight = stock.rating.div(sum) * 100
buildSlice(stock.ticker, weight)
}.sortedByDescending { it.weight }
}
private fun calculateByRatingAndYield(stocks: Set<Stock>, strategy: Strategy): List<Slice> {
val (ratingFactor, yieldFactor) = when (strategy) {
RATING_YIELD_64 -> 0.60 to 0.40
RATING_YIELD_73 -> 0.70 to 0.30
RATING_YIELD_82 -> 0.80 to 0.20
YIELD_RATING_64 -> 0.40 to 0.60
YIELD_RATING_73 -> 0.30 to 0.70
YIELD_RATING_82 -> 0.20 to 0.80
else -> DEFAULT_WEIGHT_FACTOR
}
val sumRating = stocks.sumByDouble { it.rating.toDouble() }
val sumYield = stocks.sumByDouble { it.dividendYield }
return stocks.map { stock ->
val ratingWeight = stock.rating.div(sumRating) * ratingFactor
val yieldWeight = stock.dividendYield.div(sumYield) * yieldFactor
val weight = (ratingWeight + yieldWeight) * 100
buildSlice(stock.ticker, weight)
}.sortedByDescending { it.weight }
}
private fun buildSlice(ticker: String, weight: Double): Slice =
Slice(ticker, weight.toBigDecimal().setScale(2, RoundingMode.HALF_EVEN).toDouble())
| 4 | Kotlin | 0 | 3 | 185c277fa39f1fcfd7bcab5a535a88986676395a | 2,055 | riko | MIT License |
src/Day25.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | import kotlin.math.pow
object Day25 {
fun part1(input: List<String>) {
val number = input.sumOf { snafu ->
snafu.fromSNAFU()
}.log("from")
number.toSNAFU().log("part1")
// Not so elegant first solution below
// var snafu = "20=022=200=========-"
// var i = snafu.fromSNAFU().log("from")
// (number - i).log("missing")
// while (i < number) {
// snafu = snafu.plus1SNAFU()
// i++
// }
// snafu.log()
}
private fun String.fromSNAFU(): Long = reversed()
.mapIndexed { i, n -> 5.0.pow(i) * n.fromSNAFU() }
.sum()
.toLong()
private fun Long.toSNAFU() = generateSequence(this) {
(it + 2) / 5
}.takeWhile { it != 0L }
.map { "012=-"[(it % 5).toInt()] }
.joinToString("")
.reversed()
private fun String.plus1SNAFU(): String {
return if (length == 1) {
first().plus1SNAFU().let { c -> if (c == '=') "1$c" else c.toString() }
} else {
last().plus1SNAFU().let { c ->
if (c == '=') {
dropLast(1).let { it.plus1SNAFU() } + c
} else {
dropLast(1) + c
}
}
}
}
private fun Char.plus1SNAFU(): Char {
return when (this) {
'0' -> '1'
'1' -> '2'
'2' -> '='
'=' -> '-'
'-' -> '0'
else -> error("unknown")
}
}
private fun Char.fromSNAFU(): Int {
return when (this) {
'=' -> -2
'-' -> -1
else -> this.digitToInt()
}
}
fun part2(input: List<String>) {
}
@JvmStatic
fun main(args: Array<String>) {
val input = downloadAndReadInput("Day25").filter { it.isNotBlank() }
part1(input)
}
}
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 1,929 | advent-of-code-2022 | Apache License 2.0 |
leetcode2/src/leetcode/letter-case-permutation.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* 784. 字母大小写全排列
* https://leetcode-cn.com/problems/letter-case-permutation/
* Created by test
* Date 2019/10/7 22:08
* Description
* 给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例:
输入: S = "a1b2"
输出: ["a1b2", "a1B2", "A1b2", "A1B2"]
输入: S = "3z4"
输出: ["3z4", "3Z4"]
输入: S = "12345"
输出: ["12345"]
注意:
S 的长度不超过12。
S 仅由数字和字母组成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-case-permutation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object LetterCasePermutation {
@JvmStatic
fun main(args: Array<String>) {
Solution().letterCasePermutation2("a1b2").forEach {
println(it)
}
}
class Solution {
fun letterCasePermutation(S: String): List<String> {
val letters = mutableListOf<String>()
letter(S, 0, "", letters)
return letters
}
fun letter(s: String, i: Int, target: String, list: MutableList<String>) {
var res = target
if (i == s.length) {
list.add(res)
}
if (i > s.length - 1) {
return
}
if (isValid(s[i])) {
if (isLetter(s[i])) {
if (s[i] in 'A'..'Z') {
res += s[i] + 32
letter(s, i + 1, res, list)
letter(s, i + 1, res + s[i], list)
} else {
res += s[i] - 32
letter(s, i + 1, res, list)
letter(s, i + 1, res + s[i], list)
}
} else {
res += s[i]
letter(s, i + 1, res, list)
}
}
}
fun isValid(s: Char): Boolean {
return s in '0'..'9' ||
s in 'a'..'z' ||
s in 'A'..'Z'
}
fun isLetter(s: Char): Boolean {
return s in 'a'..'z' ||
s in 'A'..'Z'
}
fun letterCasePermutation2(S: String): List<String> {
val ans = mutableListOf<String>()
dg(S.toCharArray(), 0, ans)
return ans;
}
fun dg(s: CharArray, i: Int, ans: MutableList<String>) {
if (i == s.size) {
ans.add(String(s));
return;
}
dg(s, i + 1, ans);
if (s[i] < '0' || s[i] > '9') {
if (s[i] in 'A' .. 'Z') {
s[i] = s[i] + 32
} else {
s[i] = s[i] - 32
}
dg(s, i + 1, ans);
}
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,986 | leetcode | MIT License |
src/main/kotlin/com/briarshore/aoc2022/day04/CampCleanupPuzzle.kt | steveswing | 579,243,154 | false | {"Kotlin": 47151} | package com.briarshore.aoc2022.day04
import println
import readInput
fun main() {
fun asRange(rangeParts: List<String>): IntRange {
return IntRange(rangeParts.first().toInt(), rangeParts.last().toInt())
}
fun prepareInput(input: List<String>) = input
.map { it.split(",") }
.map { Pair(asRange(it.first().split("-")), asRange(it.last().split("-"))) }
fun part1(input: List<String>): Int {
return prepareInput(input)
.count {
(it.first.contains(it.second.first) && it.first.contains(it.second.last))
|| (it.second.contains(it.first.first) && it.second.contains(it.first.last))
}
}
fun part2(input: List<String>): Int {
return prepareInput(input)
.count {
it.first.contains(it.second.first)
|| it.first.contains(it.second.last)
|| it.second.contains(it.first.first)
|| it.second.contains(it.first.last)
}
}
val sampleInput = readInput("d4p1-sample")
check(part1(sampleInput) == 2)
check(part2(sampleInput) == 4)
val input = readInput("d4p1-input")
val part1 = part1(input)
"part1 $part1".println()
val part2 = part2(input)
"part2 $part2".println()
}
| 0 | Kotlin | 0 | 0 | a0d19d38dae3e0a24bb163f5f98a6a31caae6c05 | 1,331 | 2022-AoC-Kotlin | Apache License 2.0 |
src/Year2022Day09.kt | zhangt2333 | 575,260,256 | false | {"Kotlin": 34993} | import kotlin.math.abs
import kotlin.math.sign
internal fun Point.move(char: Char) {
when (char) {
'U' -> y++
'D' -> y--
'L' -> x--
'R' -> x++
}
}
internal fun Point.follow(head: Point) {
val dx = head.x - x
val dy = head.y - y
if (abs(dx) > 1) {
x += dx - dx.sign
if (abs(dy) == 1) y += dy.sign
}
if (abs(dy) > 1) {
y += dy - dy.sign
if (abs(dx) == 1) x += dx.sign
}
}
fun main() {
fun solve(input: List<String>, ropeSize: Int): Int {
val visited = mutableSetOf<Point>()
val ropes = Array(ropeSize) { Point(0, 0) }
visited += ropes.last().copy()
for (line in input) {
val direction = line[0]
val step = line.substring(2).toInt()
repeat(step) {
for ((i, rope) in ropes.withIndex()) {
if (i == 0) rope.move(direction)
else rope.follow(ropes[i - 1])
}
visited += ropes.last().copy()
}
}
return visited.size
}
fun part1(input: List<String>): Int {
return solve(input, 2)
}
fun part2(input: List<String>): Int {
return solve(input, 10)
}
check(part1(readLines(true)) == 13)
check(part2(readLines(true)) == 1)
check(part2(readLines(true, "_test2")) == 36)
val lines = readLines()
println(part1(lines))
println(part2(lines))
}
| 0 | Kotlin | 0 | 0 | cdba887c4df3a63c224d5a80073bcad12786ac71 | 1,473 | aoc-2022-in-kotlin | Apache License 2.0 |
src/me/bytebeats/algo/kt/Solution4.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt
import me.bytebeats.algo.kt.design.BinaryMatrix
import me.bytebeats.algo.kt.design.MountainArray
import me.bytebeats.algs.ds.ListNode
import me.bytebeats.algs.ds.TreeNode
class Solution4 {
fun minPathSum(grid: Array<IntArray>): Int {
if (grid.isEmpty() || grid[0].isEmpty()) {
return 0
}
return minPathSum(grid, grid.lastIndex, grid[0].lastIndex)
}
fun minPathSum(grid: Array<IntArray>, x: Int, y: Int): Int {
if (x < 0 || y < 0) {
return 0
} else if (y == 0) {
return grid[x][y] + minPathSum(grid, x - 1, y)
} else if (x == 0) {
return grid[x][y] + minPathSum(grid, x, y - 1)
} else {
return grid[x][y] + Math.min(minPathSum(grid, x - 1, y), minPathSum(grid, x, y - 1))
}
}
fun minPathSum1(grid: Array<IntArray>): Int {
if (grid.isEmpty() || grid[0].isEmpty()) {
return 0
}
val row = grid.size
val column = grid[0].size
for (i in 1 until row) {
grid[i][0] += grid[i - 1][0]
}
for (j in 1 until column) {
grid[0][j] += grid[0][j - 1]
}
for (i in 1 until row) {
for (j in 1 until column) {
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1])
}
}
return grid[row - 1][column - 1]
}
fun sumSubarrayMins(A: IntArray): Int {//907
var count = 0L
for (i in 1..A.size) {
val sub = mutableListOf<Int>()
for (j in 0 until i - 1) {
sub.add(A[j])
}
for (j in i - 1 until A.size) {
sub.add(A[j])
sub.forEach { print(", $it") }
count += sub.minOfOrNull { it } ?: 0
count %= Int.MAX_VALUE
sub.removeAt(0)
}
}
return count.toInt()
}
fun minStartValue(nums: IntArray): Int {//5372, 1413
var min = Int.MAX_VALUE
var sum = 0
nums.forEach {
sum += it
if (sum < min) {
min = sum
}
}
if (min > 0) {
return 1
} else {
return 1 - min
}
}
fun findMinFibonacciNumbers(k: Int): Int {//5373
var ans = 0
var c = k
while (c > 0) {
c -= find1stFLessOrEqualK(c)
ans++
}
return ans
}
private fun find1stFLessOrEqualK(k: Int): Int {
if (k < 3) {
return 1
}
var f1 = 1
var f2 = 1
var tmp = 0
while (true) {
tmp = f1
f1 = f2
f2 = tmp + f1
if (f2 > k) {
break
}
}
return f1
}
fun getHappyString(n: Int, k: Int): String {//5374
var count = 3
var newN = n - 1
while (newN-- > 0) {
count *= 2
}
if (count < k) {
return ""
}
val ans = StringBuilder()
newN = n
while (newN-- > 0) {
if (ans.isEmpty()) {
ans.append('a')
} else {
if (ans.endsWith('a')) {
ans.append('b')
} else {
ans.append('a')
}
}
}
newN = k
while (newN-- > 1) {
}
return ans.toString()
}
fun findMin(nums: IntArray): Int {//153
if (nums.isEmpty()) {
return -1
}
if (nums.first() <= nums.last()) {//in ascending order, not rotated at some pivot, or only one element
return nums.first()
}
var pivot = -1
var s = 0
var e = nums.lastIndex
while (s <= e) {
pivot = s + (e - s) / 2
if (pivot > 0 && nums[pivot - 1] > nums[pivot]) {
return nums[pivot]
} else if (nums.first() <= nums[pivot]) {// "=" means pivoted element is the first one
s = pivot + 1
} else if (nums[pivot] <= nums.last()) {// "=" means pivoted element is the last one
e = pivot - 1
}
}
return -1
}
fun findMin2(nums: IntArray): Int {//153
var left = 0
var right = nums.lastIndex
var mid = 0
while (left < right) {
mid = left + (right - left) / 2
if (nums[mid] < nums[right]) {
right = mid
} else {
left = mid + 1
}
}
return nums[left]
}
fun findMin1(nums: IntArray): Int {//154
var low = 0
var high = nums.lastIndex
var pivot = 0
while (low < high) {
pivot = low + (high - low) / 2
if (nums[pivot] < nums[high]) {
high = pivot
} else if (nums[pivot] > nums[high]) {
low = pivot + 1
} else {
high--
}
}
return nums[low]
}
fun search(nums: IntArray, target: Int): Int {//33
if (nums.isEmpty()) {
return -1
}
var pivot = -1
var s = 0
var e = nums.lastIndex
if (nums.first() > nums.last()) {//ascending array is rotated
while (s <= e) {
pivot = s + (e - s) / 2
if (pivot > 0 && nums[pivot - 1] > nums[pivot]) {//find the rotated index, e.g.: [2,3,1] -> nums[2] = 1, find 2
break
} else if (nums.first() <= nums[pivot]) {
s = pivot + 1
} else if (nums[pivot] <= nums.last()) {
e = pivot - 1
}
}
if (target <= nums.last()) {
s = pivot
e = nums.lastIndex
} else if (target >= nums.first()) {
s = 0
e = pivot - 1
} else {
return -1
}
}
while (s <= e) {
pivot = s + (e - s) / 2
if (nums[pivot] < target) {
s = pivot + 1
} else if (nums[pivot] > target) {
e = pivot - 1
} else {
return pivot//binary search
}
}
return -1
}
fun search1(nums: IntArray, target: Int): Boolean {//81
if (nums.isEmpty()) {
return false
}
var low = 0
var high = nums.lastIndex
var mid = 0
while (low < high) {
mid = low + (high - low) / 2
if (nums[mid] > nums[high]) {
low = high + 1
} else if (nums[mid] < nums[high]) {
high = mid
} else {
high--
}
}
val pivot = low
low = 0
high = pivot - 1
while (low <= high) {
mid = low + (high - low) / 2
if (nums[mid] > target) {
high = mid - 1
} else if (nums[mid] < target) {
low = mid + 1
} else {
return true
}
}
low = pivot
high = nums.lastIndex
while (low <= high) {
mid = low + (high - low) / 2
if (nums[mid] > target) {
high = mid - 1
} else if (nums[mid] < target) {
low = mid + 1
} else {
return true
}
}
return false
}
fun searchRange(nums: IntArray, target: Int): IntArray {//34
var ans = IntArray(2) { -1 }
var low = 0
var high = nums.lastIndex
var mid = 0
while (low <= high) {
mid = low + (high - low) / 2
if (nums[mid] > target) {
high = mid - 1
} else if (nums[mid] < target) {
low = mid + 1
} else {
var start = mid
while (start - 1 > -1 && nums[mid] == nums[start - 1]) {
start--
}
var end = mid
while (end + 1 < nums.size && nums[mid] == nums[end + 1]) {
end++
}
ans[0] = start
ans[1] = end
break
}
}
return ans
}
fun numPairsDivisibleBy60(time: IntArray): Int {//1010
var ans = 0
val seconds = IntArray(60)
time.forEach { seconds[it % 60] += 1 }
ans += combination(seconds[30], 2)
ans += combination(seconds[0], 2)
var i = 1
var j = 59
while (i < j) {
ans += seconds[i++] * seconds[j--]
}
return ans
}
private fun combination(n: Int, k: Int): Int {
var ans = 1L
for (i in 1..k) {
ans = ans * (n - i + 1) / i
}
return ans.toInt()
}
fun rankTeams(votes: Array<String>): String {//1366
val map = sortedMapOf<Char, IntArray>()
votes[0].forEach {
map[it] = IntArray(votes[0].length)
}
votes.forEach { vote ->
vote.forEachIndexed { index, c ->
map[c]!![index]++
}
}
return String(map.entries.sortedWith(Comparator { t1, t2 ->//sorting really matters
for (i in votes[0].indices) {
if (t1.value[i] != t2.value[i]) {
return@Comparator t2.value[i] - t1.value[i]
}
}
return@Comparator t1.key - t2.key
}).map { it.key }.toCharArray())
}
fun bstFromPreorder(preorder: IntArray): TreeNode? {//1008
if (preorder.isNotEmpty()) {
return bstFromPreorder(preorder, 0, preorder.lastIndex)
}
return null
}
fun bstFromPreorder(preorder: IntArray, start: Int, end: Int): TreeNode? {//
if (start > end || start < 0 || end > preorder.lastIndex) {
return null
}
val root = TreeNode(preorder[start])
var pivot = -1
for (i in start + 1..end) {
if (preorder[i] > preorder[start]) {
pivot = i
break
}
}
if (pivot == -1) {
root.left = bstFromPreorder(preorder, start + 1, end)
} else {
if (pivot - 1 >= start + 1) {
root.left = bstFromPreorder(preorder, start + 1, pivot - 1)
}
if (pivot <= end) {
root.right = bstFromPreorder(preorder, pivot, end)
}
}
return root
}
var trees: MutableMap<String, Int>? = null
var count: MutableMap<Int, Int>? = null
var ans: MutableList<TreeNode>? = null
var t = 0
fun findDuplicateSubtrees(root: TreeNode?): List<TreeNode?> {//652
t = 1
trees = mutableMapOf()
count = mutableMapOf()
ans = mutableListOf()
lookup(root)
return ans!!
}
private fun lookup(node: TreeNode?): Int {
if (node == null) {
return 0
}
val serial = "${node.`val`}${lookup(node.left)}${lookup(node.right)}"
val uid = trees!!.computeIfAbsent(serial) { t++ }
count!![uid] = (count!![uid] ?: 0) + 1
if (count!![uid] == 2) {
ans!!.add(node)
}
return uid
}
fun numberOfSubarrays(nums: IntArray, k: Int): Int {//1248
var ans = 0
val oddIndexes = mutableListOf<Int>()
for (i in nums.indices) {
if (nums[i] and 1 == 1) {
oddIndexes.add(i)
}
}
oddIndexes.add(0, -1)
oddIndexes.add(nums.size)
for (i in 1 until oddIndexes.size - k) {
ans += (oddIndexes[i] - oddIndexes[i - 1]) * (oddIndexes[i + k] - oddIndexes[i + k - 1])
}
return ans
}
fun isLongPressedName(name: String, typed: String): Boolean {//925
if (name.length > typed.length) {
return false
}
if (name == typed) {
return true
}
return true
}
fun leftMostColumnWithOne(binaryMatrix: BinaryMatrix): Int {
val row = binaryMatrix.dimensions()[0]
val column = binaryMatrix.dimensions()[1]
println("$row, $column")
var x = 0
var y = column - 1
while (x < row && y > -1) {
if (binaryMatrix.get(x, y) == 1) {
y--
} else {
x++
}
}
return if (y == column - 1) -1 else y + 1
}
fun findMaxConsecutiveOnes(nums: IntArray): Int {//485
var ans = Int.MIN_VALUE
val zeros = mutableListOf<Int>()
nums.forEachIndexed { index, i ->
if (i == 0) {
zeros.add(index)
}
}
zeros.add(0, -1)
zeros.add(nums.size)
for (i in 1..zeros.lastIndex) {
ans = Math.max(zeros[i] - zeros[i - 1] - 1, ans)
}
return ans
}
fun findNumbers(nums: IntArray): Int {//1295
var ans = 0
nums.forEach {
if (getBitCount(it) and 1 == 0) {
ans++
}
}
return ans
}
private fun getBitCount(num: Int): Int {
var ans = 0
var k = num
while (k != 0) {
ans++
k /= 10
}
return ans
}
fun findLengthOfLCIS(nums: IntArray): Int {//674
var max = 0
if (nums.isNotEmpty()) {
var count = 1
max = 1
var num = nums[0]
for (i in 1..nums.lastIndex) {
if (nums[i] > num) {
num = nums[i]
count++
if (count > max) {
max = count
}
} else {
num = nums[i]
count = 1
}
}
}
return max
}
fun findMaxConsecutiveOnes1(nums: IntArray): Int {//487
var ans = 0
val zeros = mutableListOf<Int>()
nums.forEachIndexed { index, i ->
if (i and 1 == 0) {
zeros.add(index)//records all index of 0
}
}
if (zeros.isEmpty()) {
return nums.size
}
zeros.forEach {
var k = it + 1
while (k < nums.size && nums[k] == 1) {//count 0s in left of current 0
k++
}
var j = it - 1
while (j > -1 && nums[j] == 1) {//count 0s in right of current 0
j--
}
ans = Math.max(ans, k - j - 1)//count 1s, and get the max
}
return ans
}
fun longestOnes(A: IntArray, K: Int): Int {//1004
var ans = 0
val zeros = mutableListOf<Int>()
A.forEachIndexed { index, i ->
if (i and 1 == 0) {
zeros.add(index)//records all index of 0
}
}
if (zeros.size <= K) {
return A.size
}
var pre = -1
for (i in K..zeros.size) {
if (i == K) {
if (A[i - K] > 0) {
}
} else if (i == zeros.size) {
} else {
}
}
return ans
}
fun subarraySum(nums: IntArray, k: Int): Int {//560
var count = 0
var sum = 0
val map = mutableMapOf<Int, Int>()
map[0] = 1
nums.forEach {
sum += it
if (map.containsKey(sum - k)) {
count += map[sum - k] ?: 0
}
map.compute(sum) { _, v -> if (v == null) 1 else v + 1 }
}
return count
}
fun numSubmatrixSumTarget(matrix: Array<IntArray>, target: Int): Int {//1074
var count = 0
if (matrix.isNotEmpty() && matrix[0].isNotEmpty()) {
}
return count
}
fun checkSubarraySum(nums: IntArray, k: Int): Boolean {//523
for (i in 0 until nums.lastIndex) {
var sum = nums[i]
for (j in i + 1 until nums.size) {
sum += nums[j]
if (k == 0) {
if (sum == 0) {
return true
}
} else if (sum % k == 0) {
return true
}
}
}
return false
}
fun checkSubarraySum1(nums: IntArray, k: Int): Boolean {//523
var sum = 0
val map = mutableMapOf<Int, Int>()
map[0] = -1
for (i in nums.indices) {
sum += nums[i]
if (k != 0) {
sum %= k
}
if (map.containsKey(sum)) {
if (i - map[sum]!! > 1) {
return true
}
} else {
map[sum] = i
}
}
return false
}
fun superPow(a: Int, b: IntArray): Int {//372
return superPow(a, b, b.lastIndex)
}
fun superPow(a: Int, b: IntArray, index: Int): Int {//372
if (index < 0) {
return 1
}
val part1 = myPow(a, b[index])
val part2 = myPow(superPow(a, b, index - 1), 10)
return part1 * part2 % 1337
}
private fun myPow(a: Int, b: Int): Int {
var ans = 1
var aa = a % 1337
for (i in 0 until b) {
ans *= aa
ans %= 1337
}
return ans
}
fun waysToChange(n: Int): Int {//面试题 08.11
val coins = arrayOf(25, 10, 5, 1)
val mod = 1_000_000_007
val ans = IntArray(n + 1)
ans[0] = 1
for (i in coins.indices) {
for (j in coins[i]..n) {
ans[j] = (ans[j] + ans[j - coins[i]]) % mod
}
}
return ans[n]
}
fun numWays(n: Int, k: Int): Int {//276
if (n == 0 || k == 0) {
return 0
}
if (n == 1) {
return k
}
var diffColor = k * (k - 1)
var sameColor = k
var tmp = 0
for (i in 2 until n) {
tmp = diffColor
diffColor = (diffColor + sameColor) * (k - 1)
sameColor = tmp
}
return diffColor + sameColor
}
fun minCost(costs: Array<IntArray>): Int {//256
var preR = 0
var preG = 0
var preB = 0
var curR = 0
var curG = 0
var curB = 0
for (i in costs.indices) {
curR = Math.min(preG, preB) + costs[i][0]
curG = Math.min(preR, preB) + costs[i][1]
curB = Math.min(preG, preR) + costs[i][2]
preR = curR
preG = curG
preB = curB
}
return Math.min(Math.min(curR, curG), curB)
}
fun minCostII(costs: Array<IntArray>): Int {//265
if (costs.isEmpty()) {
return 0
} else if (costs[0].size == 1) {
return costs[0][0]
}
var minColor = -1
var minCost = 0
var secondMinCost = 0
costs.forEach { cost ->
var tmpMinColor = -1
var tmpMinCost = Int.MAX_VALUE
var tmpSecondMinCost = Int.MAX_VALUE
for (i in cost.indices) {
val thisMinCost = (if (i == minColor) secondMinCost else minCost) + cost[i]
if (thisMinCost < tmpMinCost) {
tmpSecondMinCost = tmpMinCost
tmpMinCost = thisMinCost
tmpMinColor = i
} else if (thisMinCost < tmpSecondMinCost) {
tmpSecondMinCost = thisMinCost
}
}
minCost = tmpMinCost
minColor = tmpMinColor
secondMinCost = tmpSecondMinCost
}
return minCost
}
fun duplicateZeros(arr: IntArray): Unit {//1089
var i = 0
while (i < arr.size) {
if (arr[i] == 0) {
for (j in arr.lastIndex - 1 downTo i) {
arr[j + 1] = arr[j]
}
i += 2
} else {
i++
}
}
}
fun removeElement(nums: IntArray, `val`: Int): Int {//27
var size = nums.size
var i = 0
while (i < size) {
if (nums[i] != `val`) {
i++
} else {
for (j in i until size - 1) {
nums[j] = nums[j + 1]
}
size--
}
}
return size
}
fun removeDuplicates(nums: IntArray): Int {//26
if (nums.size < 2) {
return nums.size
}
var size = nums.size
var i = -1
var j = 1
while (j < nums.size) {
if (nums[j] == nums[j - 1]) {
if (i < 0) {
i = j
}
j++
size--
} else {
if (i > -1) {
nums[i++] = nums[j++]
} else {
j++
}
}
}
return size
}
fun reversePairs(nums: IntArray): Int {//面试题51
var ans = 0
if (nums.size > 1) {
for (i in 0 until nums.lastIndex) {
for (j in i + 1 until nums.size) {
if (nums[i] > nums[j]) {
ans++
}
}
}
}
return ans
}
fun reversePairs1(nums: IntArray): Int {//面试题51
val size = nums.size
val tmp = IntArray(size)
return reversePairs(nums, tmp, 0, size - 1)
}
private fun reversePairs(nums: IntArray, tmp: IntArray, l: Int, r: Int): Int {//面试题51
if (l >= r) {
return 0
}
val mid = l + (r - l) / 2
var pairCount = reversePairs(nums, tmp, l, mid) + reversePairs(nums, tmp, mid + 1, r)
var i = l
var j = mid + 1
var pos = l
while (i <= mid && j <= r) {
if (nums[i] <= nums[j]) {
tmp[pos++] = nums[i++]
pairCount += (j - (mid + 1))
} else {
tmp[pos++] = nums[j++]
}
}
for (k in i..mid) {
tmp[pos++] = nums[k]
pairCount += (j - (mid + 1))
}
for (k in j..r) {
tmp[pos++] = nums[k]
}
for (i in l..r) {
nums[i] = tmp[i]
}
return pairCount
}
fun fib(n: Int): Int {//面试题10-I
if (n < 2) {
return n
} else {
var fib1 = 0
var fib2 = 1
var tmp = 0
var N = n
while (N-- > 1) {
tmp = fib2
fib2 = (fib1 + fib2) % 1_000_000_007
fib1 = tmp
}
return fib2
}
}
fun singleNumbers(nums: IntArray): IntArray {//面试题56-I
var xorVal = 0
nums.forEach {
xorVal = xorVal xor it
}
var bigEnd = 1
while (bigEnd and xorVal == 0) {
bigEnd = bigEnd shl 1
}
var a = 0
var b = 0
nums.forEach {
if (it and bigEnd == 0) {
a = a xor it
} else {
b = b xor it
}
}
return intArrayOf(a, b)
}
fun sortArrayByParity(A: IntArray): IntArray {//905
var i = 0
var j = A.lastIndex
var tmp = 0
while (i < j) {
while (i < j && A[i] and 1 == 0) {
i++
}
while (i < j && A[j] and 1 == 1) {
j--
}
tmp = A[i]
A[i] = A[j]
A[j] = tmp
i++
j--
}
return A
}
fun replaceElements(arr: IntArray): IntArray {//1299
for (i in 0 until arr.lastIndex) {
var max = Int.MIN_VALUE
for (j in i + 1 until arr.size) {
if (arr[j] > max) {
max = arr[j]
}
}
arr[i] = max
}
arr[arr.size - 1] = -1
return arr
}
fun mergeKLists(lists: Array<ListNode?>): ListNode? {//23
var ans: ListNode? = null
if (lists.isNotEmpty()) {
ans = lists[0]
for (i in 1 until lists.size) {
ans = merge(lists[i], ans)
}
}
return ans
}
private fun merge(list1: ListNode?, list2: ListNode?): ListNode? {
var dummy = ListNode(-1)
val p = dummy
var p1 = list1
var p2 = list2
while (p1 != null && p2 != null) {
if (p1.`val` < p2.`val`) {
dummy.next = p1
p1 = p1.next
} else {
dummy.next = p2
p2 = p2.next
}
dummy = dummy.next
}
while (p1 != null) {
dummy.next = p1
dummy = dummy.next
p1 = p1.next
}
while (p2 != null) {
dummy.next = p2
dummy = dummy.next
p2 = p2.next
}
return p.next
}
fun longestCommonSubsequence(text1: String, text2: String): Int {//1143
if (text1 == text2) {
return text1.length
}
val row = text1.length
val column = text2.length
val matrix = Array(row + 1) { IntArray(column + 1) }//loop
for (i in 1 until row + 1) {
for (j in 1 until column + 1) {
if (text1[i - 1] == text2[j - 1]) {
matrix[i][j] = 1 + matrix[i - 1][j - 1]
} else {
matrix[i][j] = Math.max(matrix[i - 1][j], matrix[i][j - 1])
}
}
}
return matrix[row][column]
}
fun longestCommonSubsequence(text1: String, m: Int, text2: String, n: Int): Int {//dp
if (m < 0 || n < 0) {
return 0
} else if (text1[m] == text2[n]) {
return 1 + longestCommonSubsequence(text1, m - 1, text2, n - 1)
} else {
return Math.max(
longestCommonSubsequence(text1, m, text2, n - 1),
longestCommonSubsequence(text1, m - 1, text2, n)
)
}
}
fun heightChecker(heights: IntArray): Int {//1051
val arr = IntArray(101)
heights.forEach { arr[it]++ }
var j = 0
var count = 0
for (i in 1..arr.lastIndex) {
while (arr[i]-- > 0) {
if (heights[j++] != i) {
count++
}
}
}
return count
}
fun findDisappearedNumbers(nums: IntArray): List<Int> {//448
val set = mutableSetOf<Int>()
nums.forEach { set.add(it) }
val ans = mutableListOf<Int>()
for (i in 1..nums.size) {
if (!set.contains(i)) {
ans.add(i)
}
}
return ans
}
fun hammingDistance(x: Int, y: Int): Int {//461
var xorVal = x xor y
var count = 0
while (xorVal != 0) {
if (xorVal and 1 == 1) {
count++
}
xorVal = xorVal shr 1
}
return count
}
fun totalHammingDistance(nums: IntArray): Int {//477
var sum = 0
val kHD = IntArray(32)
var num = 0
var index = 0
nums.forEach {
index = 0
num = it
while (num > 0) {
kHD[index++] += num and 1
num = num ushr 1
}
}
kHD.forEach { sum += it * (nums.size - it) }
return sum
}
fun repeatedSubstringPattern(s: String): Boolean {//459
val str = "$s$s"
return str.substring(1, str.length - 1).contains(s)
}
fun maximalSquare(matrix: Array<CharArray>): Int {//221
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return 0
}
val row = matrix.size
val column = matrix[0].size
val dp = Array(row + 1) { IntArray(column + 1) { 0 } }
var max = Int.MIN_VALUE
for (i in 1..row) {
for (j in 1..column) {
if (matrix[i - 1][j - 1] == '1') {
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1
if (dp[i][j] > max) {
max = dp[i][j]
}
}
}
}
return max * max
}
fun exchange(nums: IntArray): IntArray {//面试题21
var i = 0
var j = nums.lastIndex
var tmp = 0
while (i < j) {
while (j > i && nums[j] and 1 == 0) {
j--
}
while (i < j && nums[i] and 1 == 1) {
i++
}
if (i < j) {
tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
}
}
return nums
}
fun spiralOrder(matrix: Array<IntArray>): IntArray {//面试题29
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return IntArray(0)
}
val row = matrix.size
val column = matrix[0].size
val seen = Array(row) { BooleanArray(column) { false } }
val dr = intArrayOf(0, 1, 0, -1)
val dc = intArrayOf(1, 0, -1, 0)
var r = 0
var c = 0
var di = 0
var cr = 0
var cc = 0
val ans = IntArray(row * column)
for (i in 0 until row * column) {
ans[i] = matrix[r][c]
seen[r][c] = true
cr = r + dr[di]
cc = c + dc[di]
if (cr > -1 && cr < row && cc > -1 && cc < column && !seen[cr][cc]) {
r = cr
c = cc
} else {
di = (di + 1) % 4
r += dr[di]
c += dc[di]
}
}
return ans
}
fun spiralOrder1(matrix: Array<IntArray>): List<Int> {//54
val ans = mutableListOf<Int>()
if (matrix.isNotEmpty() && matrix[0].isNotEmpty()) {
val row = matrix.size
val column = matrix[0].size
val seen = Array(row) { BooleanArray(column) { false } }
val dr = arrayOf(0, 1, 0, -1)
val dc = arrayOf(1, 0, -1, 0)
var di = 0
var r = 0
var c = 0
var cr = 0
var cc = 0
for (i in 0 until row * column) {
ans.add(matrix[r][c])
seen[r][c] = true
cr = r + dr[di]
cc = c + dc[di]
if (cr > -1 && cr < row && cc > -1 && cc < column && !seen[cr][cc]) {
r = cr
c = cc
} else {
di = (di + 1) % 4
r += dr[di]
c += dc[di]
}
}
}
return ans
}
fun minJump(jump: IntArray): Int {//LCP 09
var count = 1000000000
val f = IntArray(10_000_000 + 7)
val maxDistance = IntArray(10_000_000 + 7)
var w = 0
for (i in 1..jump.size) {
f[i] = 1000000000
maxDistance[i] = 0
}
f[1] = 0
maxDistance[0] = 1
for (i in 1..jump.size) {
if (i > maxDistance[w]) {
w++
}
f[i] = Math.min(f[i], w + 1)
val next = i + jump[i - 1]
if (next > jump.size) {
count = Math.min(count, f[i] + 1)
} else if (f[next] > f[i] + 1) {
f[next] = f[i] + 1
maxDistance[f[next]] = Math.max(maxDistance[f[next]], next)
}
}
return count
}
fun expectNumber(scores: IntArray): Int {//LCP 11
var count = scores.size
if (scores.isNotEmpty()) {
scores.sort()
for (i in 1 until scores.size) {
if (scores[i] == scores[i - 1]) {
count--
}
}
}
return count
}
fun expectNumber1(scores: IntArray): Int {//LCP 11
val set = mutableSetOf<Int>()
scores.forEach { set.add(it) }
return set.size
}
fun largestUniqueNumber(A: IntArray): Int {//1133
val unrepeated = linkedSetOf<Int>()
val repeated = linkedSetOf<Int>()
for (i in A.indices) {
if (repeated.contains(A[i])) {
continue
} else if (unrepeated.contains(A[i])) {
unrepeated.remove(A[i])
repeated.add(A[i])
} else {
unrepeated.add(A[i])
}
}
if (unrepeated.isEmpty()) {
return -1
} else {
return unrepeated.maxOfOrNull { it } ?: 0
}
}
fun firstUniqChar(s: String): Int {//387
val unrepeated = linkedSetOf<Char>()
val repeated = linkedSetOf<Char>()
for (i in s.indices) {
if (repeated.contains(s[i])) {
continue
} else if (unrepeated.contains(s[i])) {
unrepeated.remove(s[i])
repeated.add(s[i])
} else {
unrepeated.add(s[i])
}
}
for (i in s.indices) {
if (unrepeated.contains(s[i])) {
return i
}
}
return -1
}
fun minNumberOfFrogs(croakOfFrogs: String): Int {//1419
if (croakOfFrogs.isEmpty()) {
return 0
}
if (croakOfFrogs.length % 5 != 0) {
return -1
}
val croak = mapOf('c' to 0, 'r' to 1, 'o' to 2, 'a' to 3, 'k' to 4)
val croaks = IntArray(5)
var ans = 0
croakOfFrogs.forEach {
val idx = croak[it] ?: 0
croaks[idx]++
ans = Math.max(ans, croaks[idx])
for (i in 0 until idx) {
if (croaks[i] < croaks[idx]) {
return -1
}
}
if (idx == 4) {
for (i in croaks.indices) {
croaks[i]--
}
}
}
return ans
}
fun findInMountainArray(target: Int, mountainArr: MountainArray): Int {//1095
val length = mountainArr.length()
if (length < 3) {
return -1
}
var low = 0
var high = length - 1
var mid = 0
while (low < high) {//find peak
mid = low + (high - low) / 2
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
low = mid + 1
} else {
high = mid
}
}
var peak = low
if (peak != -1) {
low = 0
high = peak
while (low <= high) {
mid = low + (high - low) / 2
val midVal = mountainArr.get(mid)
if (midVal < target) {
low = mid + 1
} else if (midVal > target) {
high = mid - 1
} else {
return mid
}
}
low = peak + 1
high = length - 1
while (low <= high) {
mid = low + (high - low) / 2
val midVal = mountainArr.get(mid)
if (midVal < target) {
high = mid - 1
} else if (midVal > target) {
low = mid + 1
} else {
return mid
}
}
}
return -1
}
fun countNegatives(grid: Array<IntArray>): Int {//1531
val row = grid.size
val column = grid[0].size
var pos = column - 1
var k = 0
var count = 0
for (i in 0 until row) {
if (grid[i][column - 1] >= 0) {
continue
} else {
k = -1
for (j in pos downTo 0) {
if (grid[i][j] >= 0) {
k = j
break
}
}
if (k != -1) {
count += (column - k - 1)
pos = k
} else {
count += column
}
}
}
return count
}
fun sumOfDigits(A: IntArray): Int {//1085
var min = A.minOfOrNull { it } ?: 0
var sum = 0
while (min != 0) {
sum += min % 10
min /= 10
}
return if (sum and 1 == 0) 1 else 0
}
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {//74
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return false
}
val row = matrix.size
val column = matrix[0].size
var low = 0
var high = row * column - 1
var mid = 0
var x = 0
var y = 0
while (low <= high) {
mid = low + (high - low) / 2
x = mid / column
y = mid % column
if (matrix[x][y] > target) {
high = mid - 1
} else if (matrix[x][y] < target) {
low = mid + 1
} else {
return true
}
}
return false
}
fun searchMatrix1(matrix: Array<IntArray>, target: Int): Boolean {//240
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return false
}
val row = matrix.size
val column = matrix[0].size
var x = 0
var y = column - 1
while (x < row && y > -1) {
if (matrix[x][y] < target) {
x++
} else if (matrix[x][y] > target) {
y--
} else {
return true
}
}
return false
}
fun bitwiseComplement(N: Int): Int {//1009
if (N == 0) {
return 1
}
var ans = 1L
while (ans <= N) {
ans = ans shl 1
}
return (ans - 1 - N).toInt()
}
fun toHex(num: Int): String {//405
if (num == 0) {
return "0"
}
val hexChars = "0123456789abcdef"
var n = num
val ans = StringBuilder()
while (ans.length < 8 || n != 0) {
ans.append(hexChars[n and 0xf])
n = n shr 4
}
return ans.reverse().toString()
}
fun sortByBits(arr: IntArray): IntArray {//1356
return arr.groupBy { count1s(it) }.toSortedMap().flatMap { it.value.sorted() }.toIntArray()
}
private fun count1s(num: Int): Int {
var count = 0
var n = num
while (n != 0) {
if (n and 1 == 1) {
count++
}
n = n shr 1
}
return count
}
fun countBits(num: Int): IntArray {//338
val ans = IntArray(num + 1)
for (i in 0..num) {
ans[i] = bitCount(i)
}
return ans
}
private fun bitCount(num: Int): Int {
var i = num
i -= i ushr 1 and 1431655765
i = (i and 858993459) + (i ushr 2 and 858993459)
i = i + (i ushr 4) and 252645135
i += i ushr 8
i += i ushr 16
return i and 63
}
fun getDecimalValue(head: ListNode?): Int {//1290
var ans = 0
var p = head
while (p != null) {
ans *= 2
ans += p.`val`
p = p.next
}
return ans
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 40,003 | Algorithms | MIT License |
src/day02/Day02.kt | Dr4kn | 575,092,295 | false | {"Kotlin": 12652} | package day02
import readInput
import java.lang.Exception
fun main() {
fun convertToValue(letter: String): Int {
return when (letter) {
"A", "X" -> 1 // Rock
"B", "Y" -> 2 // Paper
"C", "Z" -> 3 // Scissors
else -> throw Exception("Not a valid Symbol")
}
}
fun scoring(elf: Int, you: Int): Int {
if (you == elf) { // draw
return you + 3
}
if (you == 1 && elf == 3) { // Rock defeats Scissors
return you + 6
}
if (you == 2 && elf == 1) { // Paper defeats Rock
return you + 6
}
if (you == 3 && elf == 2) { // Scissors defeats Paper
return you + 6
}
return you // loss
}
fun decideValue(elf: Int, you: Int): Int {
if (you == 1) { // loss
return when (elf) {
1 -> 3
2 -> 1
3 -> 2
else -> throw Exception("Not a valid number")
}
}
if (you == 2) { // draw
return when (elf) {
1 -> 1
2 -> 2
3 -> 3
else -> throw Exception("Not a valid number")
}
}
if (you == 3) { // win
return when (elf) {
1 -> 2
2 -> 3
3 -> 1
else -> throw Exception("Not a valid number")
}
}
throw Exception("Not a valid decision")
}
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {
val players = it.split(" ")
sum += scoring(convertToValue(players[0]), convertToValue(players[1]))
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach {
val players = it.split(" ")
val elf = convertToValue(players[0])
val you = convertToValue(players[1])
sum += scoring(elf, decideValue(elf, you))
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6de396cb4eeb27ff0dd9a98b56e68a13c2c90cd5 | 2,376 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2022/Day07.kt | Playacem | 573,606,418 | false | {"Kotlin": 44779} | package aoc2022
import utils.createDebug
import utils.readInput
import java.util.*
object Day07 {
sealed class ElfPath(val name: String, val size: Long, val children: MutableMap<String, ElfPath>) {
abstract fun recursiveSize(): Long
abstract fun recursiveDirectories(): List<ElfDirectory>
}
class ElfDirectory(name: String, children: MutableMap<String, ElfPath>) : ElfPath(name, 0L, children) {
override fun recursiveSize(): Long {
return children.values.sumOf { it.recursiveSize() }
}
override fun recursiveDirectories(): List<ElfDirectory> {
return listOf(this) + children.values.filterIsInstance<ElfDirectory>().flatMap { it.recursiveDirectories() }
}
override fun toString(): String {
return "$name (dir)"
}
}
class ElfFile(name: String, size: Long) : ElfPath(name, size, mutableMapOf()) {
override fun recursiveSize(): Long {
return size
}
override fun recursiveDirectories(): List<ElfDirectory> {
return emptyList()
}
override fun toString(): String {
return "$name (file) $size"
}
}
class Parser {
val rootDir: ElfPath = ElfDirectory("/", mutableMapOf())
private val stack: Deque<ElfDirectory> = ArrayDeque()
fun loadInput(list: List<String>): Parser {
list.forEach { readLine(it) }
return this
}
fun readLine(line: String) {
if (line.startsWith("$ ")) {
handleCommand(line.removePrefix("$ "))
return
}
val (sizeOrDir, pathName) = line.split(' ', limit = 2)
stack.peekLast().children[pathName] = if (sizeOrDir == "dir") {
ElfDirectory(pathName, mutableMapOf())
} else {
ElfFile(pathName, sizeOrDir.toLong())
}
}
private fun handleCommand(command: String) {
if (command == "ls") {
return
}
val (_, dir) = command.split(' ', limit = 2)
when (dir) {
".." -> {
stack.removeLast()
}
"/" -> {
stack.addLast(rootDir as ElfDirectory)
}
else -> {
val currentDir = stack.peekLast()
stack.addLast(currentDir.children[dir] as? ElfDirectory ?: error("not a directory: $dir"))
}
}
}
}
}
fun main() {
val (year, day) = 2022 to "Day07"
fun part1(input: List<String>, debugActive: Boolean = false): Long {
val debug = createDebug(debugActive)
val parser = Day07.Parser().loadInput(input)
val recursiveDirectories = parser.rootDir.recursiveDirectories()
recursiveDirectories.forEach {
debug {
"$it: ${it.recursiveSize()}"
}
}
return recursiveDirectories.filter { it.recursiveSize() <= 100_000L }.sumOf { it.recursiveSize() }
}
fun part2(input: List<String>, debugActive: Boolean = false): Long {
val debug = createDebug(debugActive)
val parser = Day07.Parser().loadInput(input)
val diskSize = 70_000_000L
val requiredUnusedSpace = 30_000_000L
val usedSpace = parser.rootDir.recursiveSize()
val currentlyFree = diskSize - usedSpace
val sizeToDelete = requiredUnusedSpace - currentlyFree
val res = parser.rootDir.recursiveDirectories().filter { it.recursiveSize() >= sizeToDelete }.minOf { it.recursiveSize() }
debug { "Result: $res" }
return res
}
val testInput = readInput(year, "${day}_test")
val input = readInput(year, day)
// test if implementation meets criteria from the description, like:
check(part1(testInput, debugActive = true) == 95_437L)
println(part1(input))
check(part2(testInput, debugActive = true) == 24_933_642L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4ec3831b3d4f576e905076ff80aca035307ed522 | 4,078 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | davedupplaw | 573,042,501 | false | {"Kotlin": 29190} | fun main() {
fun executeOperation(it: List<String>, value: Int): Int {
val (operation, argument) = it
return if (operation == "addx") value + argument.toInt() else value
}
fun runProgram(input: List<String>, hook: (Int, Int) -> Unit) {
var value = 1
val allInstructions = input.map { it.split(" ") }
val opsToComplete = mutableMapOf<Int, MutableList<List<String>>>()
val nThreads = 1
var cycle = 1
var programCounter = 0
do {
if (opsToComplete.size < nThreads) {
val instruction = allInstructions[programCounter++]
val (operation, _) = instruction
if (operation == "addx") opsToComplete.getOrPut(cycle + 1) { mutableListOf() }.add(instruction)
}
hook(cycle, value)
val completeThisCycle = opsToComplete.remove(cycle)
completeThisCycle?.forEach {
value = executeOperation(it, value)
}
cycle++
} while (opsToComplete.isNotEmpty() || programCounter < input.size)
}
fun part1(input: List<String>): Int {
val readingPoints = listOf(20, 60, 100, 140, 180, 220)
val readings = mutableMapOf<Int, Int>()
runProgram(input) { cycle: Int, value: Int ->
if (cycle in readingPoints) {
readings[cycle] = cycle * value
}
}
return readings.values.sum()
}
data class CRT(val w: Int, val h: Int) {
private val crt = List(h) { MutableList(w) { 0 } }
fun set(x: Int, y: Int, v: Int) {
crt[y][x] = v
}
override fun toString(): String {
return crt.joinToString("\n") {
it.joinToString("") { x ->
when (x) {
1 -> "#"
else -> "."
}
}
}
}
}
fun part2(input: List<String>): String {
val crt = CRT(40, 6)
runProgram(input) { cycleOneBased, value ->
val cycle = cycleOneBased - 1
val x = cycle % 40
val y = cycle / 40
if (x in value - 1..value + 1) {
crt.set(x, y, 1)
}
}
return crt.toString()
}
val test = readInput("Day10.test")
val part1test = part1(test)
println("part1 test: $part1test")
val test2 = readInput("Day10.test-2")
val part12test = part1(test2)
println("part1 test: $part12test")
check(part12test == 13140)
val part2test = part2(test2)
println("part2 test: \n$part2test")
check(
part2test == """##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######....."""
)
val input = readInput("Day10")
val part1 = part1(input)
println("Part1: $part1")
val part2 = part2(input)
println("Part2:\n$part2")
}
| 0 | Kotlin | 0 | 0 | 3b3efb1fb45bd7311565bcb284614e2604b75794 | 3,109 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/tw/gasol/aoc/aoc2022/Day11.kt | Gasol | 574,784,477 | false | {"Kotlin": 70912, "Shell": 1291, "Makefile": 59} | package tw.gasol.aoc.aoc2022
import java.math.BigInteger
import java.util.*
typealias WorryLevel = BigInteger
data class MonkeySpec(
val id: Int,
val items: MutableList<WorryLevel>,
val operation: (WorryLevel) -> WorryLevel,
val testDivider: Int,
val ifTrue: Int,
val ifFalse: Int
) {
override fun toString(): String {
return "MonkeySpec(id=$id, items=$items)"
}
companion object {
fun fromInput(input: String): MutableMap<Int, MonkeySpec> {
val specs = mutableMapOf<Int, MonkeySpec>()
val scanner = Scanner(input)
while (scanner.hasNextLine()) {
val spec = parseMonkeySpec(scanner)
specs[spec.id] = spec
}
return specs
}
private fun parseMonkeySpec(scanner: Scanner): MonkeySpec {
var id: Int? = null
var items: List<WorryLevel>? = null
var operation: ((WorryLevel) -> WorryLevel)? = null
var testDivider: Int? = null
var ifTrue: Int? = null
var ifFalse: Int? = null
while (scanner.hasNextLine()) {
val line = scanner.nextLine().trim()
when {
line.startsWith("Monkey") -> {
id = line.substringAfter("Monkey ").substringBefore(":").toInt()
}
line.startsWith("Starting items") -> {
items = line.substringAfter(": ").split(", ").map { it.toBigInteger() }
}
line.startsWith("Operation") -> {
val operationLine = line.substringAfter(":")
operation = { old ->
val (lval, op, rval) = operationLine.substringAfter("= ")
.trim()
.split(" ")
val lint = if (lval == "old") old else lval.toBigInteger()
val rint = if (rval == "old") old else rval.toBigInteger()
when (op) {
"+" -> lint + rint
"-" -> lint - rint
"*" -> lint * rint
"/" -> lint / rint
else -> throw IllegalArgumentException("Unknown operation: $op")
}
}
}
line.startsWith("Test") -> {
val testLine = line.substringAfter(": ")
val (_, value) = testLine.split(" by ")
testDivider = value.toInt()
repeat(2) {
val ifLine = scanner.nextLine().trim()
val (beforeLine, afterLine) = ifLine.split(": ")
when (beforeLine) {
"If true" -> {
ifTrue = afterLine.substringAfter("monkey ").toInt()
}
"If false" -> {
ifFalse = afterLine.substringAfter("monkey ").toInt()
}
else -> error("Unexpected line: $ifLine")
}
}
}
line.isBlank() -> break
}
}
return MonkeySpec(id!!, items!!.toMutableList(), operation!!, testDivider!!, ifTrue!!, ifFalse!!)
}
}
}
fun gcd(a: Int, b: Int): Int {
if (b == 0) return a
return gcd(b, a % b)
}
fun lcm(a: Int, b: Int): Int {
return a * b / gcd(a, b)
}
class Day11 {
private val debug = false
fun part1(input: String): Int {
val specs = MonkeySpec.fromInput(input)
val monkeyIds = specs.keys.sorted()
val monkeyInspectionCounts = mutableMapOf(*monkeyIds.map { it to 0 }.toTypedArray())
val three = BigInteger.valueOf(3)
for (round in 1..20) {
println("Round $round")
monkeyIds.forEach { id ->
val spec = specs[id]!!
monkeyInspectionCounts[id] = monkeyInspectionCounts[id]!! + spec.items.count()
with(spec.items.iterator()) {
forEach { item ->
val newItem = spec.operation(item) / three
val toMonkeyId =
if (newItem % spec.testDivider.toBigInteger() == BigInteger.ZERO) spec.ifTrue else spec.ifFalse
specs[toMonkeyId]!!.items += newItem
remove()
}
}
}
specs.forEach(::println)
}
return monkeyInspectionCounts.values
.sorted()
.takeLast(2)
.also { println(it) }
.reduce { acc, i -> acc * i }
}
fun part2(input: String): Long {
val specs = MonkeySpec.fromInput(input)
val monkeyIds = specs.keys.sorted()
val monkeyInspectionCounts = mutableMapOf(*monkeyIds.map { it to 0 }.toTypedArray())
val lcm = specs.values.map { it.testDivider }.reduce(::lcm)
println("LCM: $lcm")
for (round in 1..10_000) {
println("Round $round")
monkeyIds.forEach { id ->
val spec = specs[id]!!
monkeyInspectionCounts[id] = monkeyInspectionCounts[id]!! + spec.items.count()
with(spec.items.iterator()) {
forEach { item ->
val newItem = spec.operation(item) % lcm.toBigInteger()
val toMonkeyId = if (newItem % spec.testDivider.toBigInteger() == BigInteger.ZERO) {
spec.ifTrue
} else spec.ifFalse
specs[toMonkeyId]!!.items += newItem
remove()
}
}
}
specs.forEach(::println)
}
return monkeyInspectionCounts.values
.sorted()
.takeLast(2)
.also { println(it) }
.map { it.toLong() }
.reduce(Long::times)
}
private fun println(any: Any) {
if (debug) {
System.err.println(any)
}
}
} | 0 | Kotlin | 0 | 0 | a14582ea15f1554803e63e5ba12e303be2879b8a | 6,468 | aoc2022 | MIT License |
src/Day05.kt | jamie23 | 573,156,415 | false | {"Kotlin": 19195} | import java.lang.Integer.*
import java.util.Stack
fun main() {
data class Instruction(
val num: Int,
val from: Int,
val to: Int
)
fun processInitialState(rawState: String): List<Stack<Char>> {
val stackNum = rawState[rawState.lastIndex - 1].digitToInt()
val state = List(stackNum) { Stack<Char>() }
rawState
.chunked(size = 4) // Separate into single entries in a stack
.map { it[1] } // Extract out letter or empty whitespace
.dropLast(stackNum) // Remove the labels below stacks
.chunked(stackNum) // Level order the entries
.reversed() // Start at the bottom of the stack levels
.forEach { level ->
level.forEachIndexed { i, c ->
if (c == ' ') return@forEachIndexed
state[i].push(c)
}
}
return state
}
fun String.parseInstructions() = split("\n")
.map { it.split(' ') }
.map { rawInstruction ->
Instruction(parseInt(rawInstruction[1]), parseInt(rawInstruction[3]) - 1, parseInt(rawInstruction[5]) - 1)
}
fun List<Stack<Char>>.process9000(instruction: Instruction) {
val (num, from, to) = instruction
repeat(num) { get(to).push(get(from).pop()) }
}
fun List<Stack<Char>>.process9001(instruction: Instruction) {
val (num, from, to) = instruction
val stack = Stack<Char>()
repeat(num) { stack.push(get(from).pop()) }
repeat(num) { get(to).push(stack.pop()) }
}
fun List<Stack<Char>>.peekTop() = map { it.peek() }.joinToString("")
fun part1(input: String): String {
val (rawState, rawInstructions) = input.split("\n\n")
val state = processInitialState(rawState)
rawInstructions.parseInstructions().forEach { state.process9000(it) }
return state.peekTop()
}
fun part2(input: String): String {
val (rawState, rawInstructions) = input.split("\n\n")
val state = processInitialState(rawState)
rawInstructions.parseInstructions().forEach { state.process9001(it) }
return state.peekTop()
}
val testInput = readInputText("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInputText("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | cfd08064654baabea03f8bf31c3133214827289c | 2,426 | Aoc22 | Apache License 2.0 |
src/Day01.kt | mr-kaffee | 575,129,713 | false | {"Kotlin": 1828} | import java.io.File
fun main() {
fun part1(elves: List<Int>): Int {
return elves.fold(0) { mx, calories -> maxOf(mx, calories) }
}
fun part2(elves: List<Int>): Int {
return elves.fold(mutableListOf(0, 0, 0)) { mx, calories ->
if (calories > mx[0]) {
mx[2] = mx[1]
mx[1] = mx[0]
mx[0] = calories
} else if (calories > mx[1]) {
mx[2] = mx[1]
mx[1] = calories
} else if (calories > mx[2]) {
mx[2] = calories
}
mx
}.sum()
}
val t0 = System.currentTimeMillis()
// input parsing
val input = File("src", "Day01.txt").readText()
val elves = input
.trim().split("\n\n")
.map { elf -> elf.lines().sumOf { line -> line.toInt() } }
.toList()
val tParse = System.currentTimeMillis()
// part 1
val exp1 = 67658
val sol1 = part1(elves)
val t1 = System.currentTimeMillis()
check(sol1 == exp1) { "Expected solution for part 1: $exp1, found $sol1" }
// part 2
val exp2 = 200158
val sol2 = part2(elves)
val t2 = System.currentTimeMillis()
check(sol2 == exp2) { "Expected solution for part 1: $exp2, found $sol2" }
// results
println("Solved puzzle 2022/01")
println(" parsed input in ${tParse - t0}ms")
println(" solved part 1 in ${t1 - tParse}ms => $sol1")
println(" solved part 2 in ${t2 - t1}ms => $sol2")
println(" ---")
println(" total time: ${t2 - t0}ms")
}
| 0 | Kotlin | 0 | 0 | 313432b49b73da22c55efb6e2b5b8177599c0921 | 1,565 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/minhiew/translation/Analyzer.kt | mhiew | 431,932,268 | false | {"Kotlin": 41977} | package com.minhiew.translation
object Analyzer {
fun compare(androidStrings: Map<String, String>, iosStrings: Map<String, String>): LocalizationReport {
return LocalizationReport(
uniqueAndroidStrings = androidStrings.filterForKeysNotPresentIn(iosStrings),
uniqueIosStrings = iosStrings.filterForKeysNotPresentIn(androidStrings),
commonAndroidStrings = androidStrings.filterForMatchingKeysIn(iosStrings),
commonIosStrings = iosStrings.filterForMatchingKeysIn(androidStrings)
)
}
}
data class LocalizationReport(
val uniqueAndroidStrings: Map<String, String>,
val uniqueIosStrings: Map<String, String>,
val commonAndroidStrings: Map<String, String>,
val commonIosStrings: Map<String, String>,
) {
//returns the common key to string comparison between ios and android
val stringComparisons: Map<String, StringComparison> = commonAndroidStrings.entries.associate {
val key = it.key
val androidValue: String = it.value
val iosValue: String = commonIosStrings[key] ?: ""
key to StringComparison(
key = key,
androidValue = androidValue,
iosValue = iosValue
)
}
val differences: List<StringComparison> = stringComparisons.values.filterNot { it.isExactMatch }
val exactMatches: List<StringComparison> = stringComparisons.values.filter { it.isExactMatch }
val caseInsensitiveMatches: List<StringComparison> = stringComparisons.values.filter { it.isCaseInsensitiveMatch }
val mismatchedPlaceholders: List<StringComparison> = differences.filter { it.hasMismatchedPlaceholders }
}
data class StringComparison(
val key: String,
val androidValue: String,
val iosValue: String,
) {
val isExactMatch: Boolean = androidValue == iosValue
val isCaseInsensitiveMatch = !isExactMatch && androidValue.lowercase() == iosValue.lowercase()
val iosPlaceholderCount: Int = iosValue.placeholderCount()
val androidPlaceholderCount: Int = androidValue.placeholderCount()
val hasMismatchedPlaceholders = iosPlaceholderCount != androidPlaceholderCount
}
//returns the keys within this map that do not belong to the other map
fun Map<String, String>.filterForKeysNotPresentIn(other: Map<String, String>): Map<String, String> =
this.filterKeys { !other.containsKey(it) }
fun Map<String, String>.filterForMatchingKeysIn(other: Map<String, String>): Map<String, String> =
this.filterKeys { other.containsKey(it) }
//calculates the total number of occurrences of placeholders
fun String.placeholderCount(): Int = totalOccurrence(input = this, placeholders = setOf("%@", "%d", "%s", "%f", "\$@", "\$d", "\$s", "\$f"))
private fun totalOccurrence(input: String, placeholders: Set<String>): Int {
return placeholders.fold(initial = 0) { acc, placeholder ->
acc + input.numberOfOccurrence(placeholder)
}
}
private fun String.numberOfOccurrence(substring: String): Int {
var count = 0
var index = this.indexOf(substring, startIndex = 0, ignoreCase = true)
while (index > -1) {
count += 1
index = this.indexOf(substring, startIndex = index + 1, ignoreCase = true)
}
return count
}
| 0 | Kotlin | 0 | 1 | 8261d9e94cd0a69bb04d5e5cb018bf5d16f95e89 | 3,238 | translation-tool | MIT License |
year2017/src/main/kotlin/net/olegg/aoc/year2017/day14/Day14.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2017.day14
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_4
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.get
import net.olegg.aoc.utils.set
import net.olegg.aoc.year2017.DayOf2017
/**
* See [Year 2017, Day 14](https://adventofcode.com/2017/day/14)
*/
object Day14 : DayOf2017(14) {
override fun first(): Any? {
return (0..127)
.map { "$data-$it" }
.sumOf { line ->
line
.map { it.code }
.let { it + listOf(17, 31, 73, 47, 23) }
.let { list ->
buildList(list.size * 64) {
repeat(64) {
addAll(list)
}
}
}
.foldIndexed(List(256) { it } to 0) { index, acc, value ->
val prev = acc.first + acc.first
val curr = prev.subList(0, acc.second) +
prev.subList(acc.second, acc.second + value).reversed() +
prev.subList(acc.second + value, prev.size)
val next = curr.subList(acc.first.size, acc.first.size + acc.second) +
curr.subList(acc.second, acc.first.size)
return@foldIndexed next to ((acc.second + value + index) % acc.first.size)
}
.first
.chunked(16) { chunk -> chunk.reduce { acc, value -> acc xor value } }
.sumOf { Integer.bitCount(it) }
}
}
override fun second(): Any? {
val result = (0..127)
.map { "$data-$it" }
.map { line ->
line
.map { it.code }
.let { it + listOf(17, 31, 73, 47, 23) }
.let { list ->
buildList(list.size * 64) {
repeat(64) {
addAll(list)
}
}
}
.foldIndexed(List(256) { it } to 0) { index, acc, value ->
val prev = acc.first + acc.first
val curr = prev.subList(0, acc.second) +
prev.subList(acc.second, acc.second + value).reversed() +
prev.subList(acc.second + value, prev.size)
val next = curr.subList(acc.first.size, acc.first.size + acc.second) +
curr.subList(acc.second, acc.first.size)
return@foldIndexed next to ((acc.second + value + index) % acc.first.size)
}
.first
.chunked(16) { chunk -> chunk.reduce { acc, value -> acc xor value } }
.flatMap { Integer.toBinaryString(it).padStart(8, '0').toList() }
.toMutableList()
}
.toMutableList()
var regions = 0
while (result.any { '1' in it }) {
regions++
val row = result.indexOfFirst { '1' in it }
val position = Vector2D(result[row].indexOfFirst { it == '1' }, row)
val toVisit = ArrayDeque(listOf(position))
while (toVisit.isNotEmpty()) {
val curr = toVisit.removeFirst()
result[curr] = '0'
NEXT_4
.map { curr + it.step }
.filter { result[it] == '1' }
.forEach { point ->
result[point] = '0'
toVisit += point
}
}
}
return regions
}
}
fun main() = SomeDay.mainify(Day14)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 3,166 | adventofcode | MIT License |
src/main/kotlin/com/leetcode/P167.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
// https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
class P167 {
fun twoSum(numbers: IntArray, target: Int): IntArray {
// target 보다 작은 수의 조합만 찾으면 된다.
var endOfSearch = numbers.lastIndex - 1
for (i in numbers.indices) {
if (numbers[i] > target) {
endOfSearch = i - 1
break
}
}
// Binary Search
for (i in 0..endOfSearch) {
val j = binarySearch(numbers, i + 1, numbers.lastIndex, target - numbers[i])
if (j > -1) return intArrayOf(i + 1, j + 1)
}
// You may assume that each input would have exactly one solution and you may not use the same element twice.
return IntArray(0)
}
private fun binarySearch(numbers: IntArray, s: Int, e: Int, target: Int): Int {
if (s > e) return -1
val m = (s + e) / 2
return with(numbers[m]) {
when {
target < this -> binarySearch(numbers, s, m - 1, target)
target > this -> binarySearch(numbers, m + 1, e, target)
else -> m
}
}
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,200 | algorithm | MIT License |
src/main/kotlin/hu/advent/of/code/year2022/day12/Puzzle12A.kt | sztojkatamas | 568,512,275 | false | {"Kotlin": 157914} | package hu.advent.of.code.year2022.day12
import hu.advent.of.code.AdventOfCodePuzzle
import hu.advent.of.code.BaseChallenge
import java.util.PriorityQueue
@AdventOfCodePuzzle
class Puzzle12A: BaseChallenge(2022) {
override fun run() {
printPuzzleName()
loadDataFromFile("data12.txt")
val world = generateWorld(data)
val navigationMap = createNavigationMap(world)
val states = PriorityQueue<GameState>()
states.add(GameState(world.start, emptyList()))
val steps = calculatePath(states, world.end, navigationMap)
println("Fewest steps: $steps")
}
}
fun calculatePath(
states: PriorityQueue<GameState>,
end: Pos2D,
navigationMap: Map<Pos2D, CellWithOther>
): Int {
val visitedPositions = mutableSetOf<Pos2D>()
val costs: Int
while (true) {
val first = states.first()
if (first.pos == end) {
costs = first.path.size
break
}
states.remove(first)
for ((k, n) in navigationMap.getValue(first.pos).directionToOthers) {
if (!visitedPositions.contains(n.pos)) {
states.add(GameState(n.pos, first.path + k))
visitedPositions.add(n.pos)
}
}
}
return costs
}
fun createNavigationMap(world: World): Map<Pos2D, CellWithOther> {
val navigationMap = mutableMapOf<Pos2D, CellWithOther>()
world.cellMap.forEach { (_, cell) ->
val directions = Direction.ALL.mapNotNull {
val next = world.cellMap[cell.pos + it]
if (next == null || next.elevation > (cell.elevation + 1)) {
null
} else {
it to next
}
}.toMap()
navigationMap[cell.pos] = CellWithOther(cell, directions)
}
return navigationMap
}
fun generateWorld(lines: List<String>): World {
val map = mutableMapOf<Pos2D, Cell>()
var startPos = Pos2D(0,0)
var endPos = Pos2D(0,0)
lines.forEachIndexed { y, line ->
line.forEachIndexed { x, column ->
val currentPos = Pos2D(x, y)
val elevation = when (column) {
'S' -> {
startPos = currentPos
'a'
}
'E' -> {
endPos = currentPos
'z'
}
else -> { column }
}
map[currentPos] = Cell(currentPos, elevation)
}
}
return World(startPos, endPos, map)
}
class GameState(val pos: Pos2D, val path: List<Pos2D>): Comparable<GameState> {
override fun compareTo(other: GameState): Int {
return path.size - other.path.size
}
}
data class World(val start: Pos2D, val end: Pos2D, val cellMap: Map<Pos2D, Cell>)
data class CellWithOther(val cell: Cell, val directionToOthers: Map<Pos2D, Cell>)
data class Cell(val pos: Pos2D, val elevation: Char)
data class Pos2D(val x: Int, val y: Int) {
operator fun plus(other: Pos2D): Pos2D {
return Pos2D(this.x + other.x, this.y + other.y)
}
}
object Direction {
private val UP = Pos2D(0, -1)
private val DOWN = Pos2D(0, 1)
private val LEFT = Pos2D(-1, 0)
private val RIGHT = Pos2D(1, 0)
val ALL = listOf(LEFT, UP, RIGHT, DOWN)
} | 0 | Kotlin | 0 | 0 | 6aa9e53d06f8cd01d9bb2fcfb2dc14b7418368c9 | 3,291 | advent-of-code-universe | MIT License |
src/Day08.kt | CrazyBene | 573,111,401 | false | {"Kotlin": 50149} | fun main() {
fun List<Int>.toVisibilityList(): List<Boolean> {
return this.mapIndexed { index, numberToCheck ->
for (i in index + 1 until this.size) {
if (this[i] >= numberToCheck)
return@mapIndexed false
}
true
}
}
infix fun List<List<Boolean>>.combine(otherGrid: List<List<Boolean>>): List<List<Boolean>> {
return this.mapIndexed { y, line ->
line.mapIndexed { x, boolean ->
boolean || otherGrid[y][x]
}
}
}
fun visibleFromTopAndBottom(grid: List<List<Int>>): Pair<List<List<Boolean>>, List<List<Boolean>>> {
val visibleFromTop = mutableListOf<MutableList<Boolean>>()
val visibleFromBottom = mutableListOf<MutableList<Boolean>>()
val width = grid[0].size
for (currentX in 0 until width) {
visibleFromTop.add(mutableListOf())
visibleFromBottom.add(mutableListOf())
}
for (currentX in 0 until width) {
val numbersToCheck = grid.flatMapIndexed { y, line ->
line.filterIndexed { x: Int, _: Int ->
x == currentX
}
}
numbersToCheck.reversed().toVisibilityList().reversed().forEachIndexed { index, b ->
visibleFromTop[index].add(b)
}
numbersToCheck.toVisibilityList().forEachIndexed { index, b ->
visibleFromBottom[index].add(b)
}
}
return visibleFromTop to visibleFromBottom
}
fun visibleFromSides(grid: List<List<Int>>): Pair<List<List<Boolean>>, List<List<Boolean>>> {
val visibleFromLeft = mutableListOf<List<Boolean>>()
val visibleFromRight = mutableListOf<List<Boolean>>()
val height = grid.size
for (currentY in 0 until height) {
val numbersToCheck = grid[currentY]
visibleFromLeft.add(numbersToCheck.reversed().toVisibilityList().reversed())
visibleFromRight.add(numbersToCheck.toVisibilityList())
}
return visibleFromLeft to visibleFromRight
}
fun part1(input: List<String>): Int {
val grid = input.map { line ->
line.toList().map { it.digitToInt() }
}
val (visibleFromTop, visibleFromBottom) = visibleFromTopAndBottom(grid)
val (visibleFromLeft, visibleFromRight) = visibleFromSides(grid)
val visible = visibleFromTop combine visibleFromBottom combine visibleFromLeft combine visibleFromRight
return visible.flatMap { line ->
line.map {
if (it)
1
else
0
}
}.sum()
}
fun part2(input: List<String>): Int {
val grid = input.map { line ->
line.toList().map { it.digitToInt() }
}
val gridResult = grid.mapIndexed { currentY, line ->
List(line.size) { currentX ->
val treeToCheck = grid[currentY][currentX]
val treesToCheckDownwards = grid.flatMapIndexed { y, line ->
line.filterIndexed { x: Int, _: Int ->
x == currentX && y > currentY
}
}
var treesVisibleDownwards = 0
for (tree in treesToCheckDownwards) {
treesVisibleDownwards++
if (tree >= treeToCheck)
break
}
val treesToCheckUpwards = grid.flatMapIndexed { y, line ->
line.filterIndexed { x: Int, _: Int ->
x == currentX && y < currentY
}
}.reversed()
var treesVisibleUpwards = 0
for (tree in treesToCheckUpwards) {
treesVisibleUpwards++
if (tree >= treeToCheck)
break
}
val treesToCheckLeft = grid.flatMapIndexed { y, line ->
line.filterIndexed { x: Int, _: Int ->
x < currentX && y == currentY
}
}.reversed()
var treesVisibleLeft = 0
for (tree in treesToCheckLeft) {
treesVisibleLeft++
if (tree >= treeToCheck)
break
}
val treesToCheckRight = grid.flatMapIndexed { y, line ->
line.filterIndexed { x: Int, _: Int ->
x > currentX && y == currentY
}
}
var treesVisibleRight = 0
for (tree in treesToCheckRight) {
treesVisibleRight++
if (tree >= treeToCheck)
break
}
treesVisibleDownwards * treesVisibleUpwards * treesVisibleLeft * treesVisibleRight
}
}
return gridResult.maxOf {
it.max()
}
}
val testInput = readInput("Day08Test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println("Question 1 - Answer: ${part1(input)}")
println("Question 2 - Answer: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26 | 5,367 | AdventOfCode2022 | Apache License 2.0 |
kotlin/0474-ones-and-zeroes.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} | /*
* Recursion with memoization solution
*/
class Solution {
fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
val dp = Array(m + 1){ Array(n + 1){ IntArray(strs.size){ -1 } } }
fun dfs(i: Int, m: Int, n: Int): Int {
if(i == strs.size) return 0
if(dp[m][n][i] != -1) return dp[m][n][i]
val zeros = strs[i].count{ it == '0' }
val ones = strs[i].count{ it == '1' }
dp[m][n][i] = dfs(i + 1, m, n)
if(zeros <= m && ones <= n) {
dp[m][n][i] = maxOf(
dp[m][n][i],
1 + dfs(i + 1, m - zeros, n - ones)
)
}
return dp[m][n][i]
}
return dfs(0, m, n)
}
}
/*
* DP solution
*/
class Solution {
fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
val dp = Array(m + 1){ IntArray(n + 1) }
for(str in strs) {
val zeros = str.count{ it == '0'}
val ones = str.count{ it == '1'}
for(i in m downTo zeros) {
for(j in n downTo ones) {
dp[i][j] = maxOf(
1 + dp[i - zeros][j - ones],
dp[i][j]
)
}
}
}
return dp[m][n]
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,348 | leetcode | MIT License |
src/day20/Day20.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day20
import Runner
fun main() {
Day20Runner().solve()
}
class Day20Runner : Runner<Long>(
day = 20,
expectedPartOneTestAnswer = 3,
expectedPartTwoTestAnswer = 1623178306
) {
override fun partOne(input: List<String>, test: Boolean): Long {
val mutable = mix(input = input, key = 1, times = 1)
.map { indexLong -> indexLong.long }
val startIndex = mutable.indexOfFirst { long -> long == 0L }
return mutable[(1000 + startIndex).mod(mutable.size)] +
mutable[(2000 + startIndex).mod(mutable.size)] +
mutable[(3000 + startIndex).mod(mutable.size)]
}
override fun partTwo(input: List<String>, test: Boolean): Long {
val mutable = mix(input = input, key = 811589153, times = 10)
.map { indexLong -> indexLong.long }
val startIndex = mutable.indexOfFirst { long -> long == 0L }
return mutable[(1000 + startIndex).mod(mutable.size)] +
mutable[(2000 + startIndex).mod(mutable.size)] +
mutable[(3000 + startIndex).mod(mutable.size)]
}
private fun mix(input: List<String>, key: Int = 1, times: Int = 1) : List<IndexLong> {
val longs = getLongs(input = input, key = key)
val mixed = longs.toMutableList()
repeat(times) {
longs.forEach { int ->
val currentIndex = mixed.indexOf(int)
val newIndex = (currentIndex + int.long).mod(mixed.size - 1)
mixed.removeAt(currentIndex)
mixed.add(newIndex, int)
}
}
return mixed
}
private fun getLongs(input: List<String>, key: Int = 1) : List<IndexLong> {
return input.mapIndexed { index, line ->
IndexLong(
index = index,
long = line.toLong() * key
)
}
}
}
data class IndexLong(
val index: Int,
val long: Long
)
| 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 1,945 | advent-of-code | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/odd_even_jump/OddEvenJump.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.odd_even_jump
import datsok.shouldEqual
import org.junit.Test
/**
* ✅ https://leetcode.com/problems/odd-even-jump/
*/
class OddEvenJumpTests {
@Test fun `find number of starting indices that can reach the end of array`() {
oddEvenJumps(intArrayOf()) shouldEqual 0
oddEvenJumps(intArrayOf(1)) shouldEqual 1
oddEvenJumps(intArrayOf(1, 1)) shouldEqual 2
oddEvenJumps(intArrayOf(1, 2)) shouldEqual 2
oddEvenJumps(intArrayOf(1, 0)) shouldEqual 1
oddEvenJumps(intArrayOf(1, 0, 1)) shouldEqual 3
oddEvenJumps(intArrayOf(1, 0, 0)) shouldEqual 2
oddEvenJumps(intArrayOf(10, 13, 12, 14, 15)) shouldEqual 2
oddEvenJumps(intArrayOf(2, 3, 1, 1, 4)) shouldEqual 3
oddEvenJumps(intArrayOf(5, 1, 3, 4, 2)) shouldEqual 3
}
}
private fun oddEvenJumps(a: IntArray): Int {
return a.indices.count { canReachEnd(it, a) }
}
private fun canReachEnd(index: Int, a: IntArray): Boolean {
var oddJump = true
var i = index
while (i < a.size - 1) {
val j = if (oddJump) doOddJump(i, a) else doEvenJump(i, a)
if (i == j) return false
i = j
oddJump = !oddJump
}
return true
}
private fun doOddJump(i: Int, a: IntArray): Int {
var j = i + 1
var min = Int.MAX_VALUE
var minIndex = i
while (j < a.size) {
if (a[i] <= a[j] && a[j] < min) {
min = a[j]
minIndex = j
}
j++
}
return minIndex
}
private fun doEvenJump(i: Int, a: IntArray): Int {
var j = i + 1
var max = Int.MIN_VALUE
var maxIndex = i
while (j < a.size) {
if (a[i] >= a[j] && a[j] > max) {
max = a[j]
maxIndex = j
}
j++
}
return maxIndex
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,795 | katas | The Unlicense |
src/Day02.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private enum class Shape(val score: Int) {
Rock(1), Paper(2), Scissors(3)
}
private enum class Result(val score: Int) {
Win(6), Draw(3), Lose(0)
}
private fun toOpponentShape(shape: String): Shape {
return when (shape) {
"A" -> Shape.Rock
"B" -> Shape.Paper
"C" -> Shape.Scissors
else -> throw IllegalArgumentException("Unknown shape $shape")
}
}
private fun toPlayerShape(shape: String): Shape {
return when (shape) {
"X" -> Shape.Rock
"Y" -> Shape.Paper
"Z" -> Shape.Scissors
else -> throw IllegalArgumentException("Unknown shape $shape")
}
}
private fun toResult(result: String): Result {
return when (result) {
"X" -> Result.Lose
"Y" -> Result.Draw
"Z" -> Result.Win
else -> throw IllegalArgumentException("Unknown result $result")
}
}
private fun play(playerShape: Shape, opponentShape: Shape): Result {
return if (playerShape == opponentShape) {
Result.Draw
} else if (
(playerShape == Shape.Rock && opponentShape == Shape.Scissors)
|| (playerShape == Shape.Scissors && opponentShape == Shape.Paper)
|| (playerShape == Shape.Paper && opponentShape == Shape.Rock)
) {
Result.Win
} else {
Result.Lose
}
}
private fun iShouldPlayWhen(opponentShape: Shape, result: Result): Shape {
return when (result) {
Result.Draw -> opponentShape
Result.Win -> {
when (opponentShape) {
Shape.Rock -> Shape.Paper
Shape.Paper -> Shape.Scissors
Shape.Scissors -> Shape.Rock
}
}
else -> {
when (opponentShape) {
Shape.Rock -> Shape.Scissors
Shape.Paper -> Shape.Rock
Shape.Scissors -> Shape.Paper
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
var totalScore = 0
for (line in input) {
val shapes = line.split(" ")
val opponentShape = toOpponentShape(shapes[0])
val playerShape = toPlayerShape(shapes[1])
totalScore += playerShape.score + play(playerShape, opponentShape).score
}
return totalScore
}
fun part2(input: List<String>): Int {
var totalScore = 0
for (line in input) {
val shapes = line.split(" ")
val opponentShape = toOpponentShape(shapes[0])
val result = toResult(shapes[1])
val playerShape = iShouldPlayWhen(opponentShape, result)
totalScore += playerShape.score + result.score
}
return totalScore
}
val input = readInput("Day02")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 2,853 | advent-of-code-2022 | Apache License 2.0 |
aoc-2023/src/main/kotlin/aoc/aoc14.kts | triathematician | 576,590,518 | false | {"Kotlin": 615974} | import aoc.AocParser.Companion.parselines
import aoc.*
import aoc.util.getDayInput
val testInput = """
O....#....
O.OO#....#
.....##...
OO.#O....O
.O.....O#.
O.#..O.#.#
..O..#O..O
.......O..
#....###..
#OO..#....
""".parselines
class Rocks(val initLines: List<String>) {
var curLines: MutableList<MutableList<Char>> = initLines.map { it.toMutableList() }.toMutableList()
val rows
get() = curLines.indices
val cols
get() = curLines[0].indices
fun roll1() {
initLines.indices.drop(1).forEach {
curLines[it].forEachIndexed { r, ch ->
if (ch == 'O' && curLines[it-1][r] == '.') {
curLines[it-1][r] = 'O'
curLines[it][r] = '.'
}
}
}
}
fun nRoll(): Rocks {
repeat(initLines.size) { roll1() }
return this
}
fun score(): Int {
var score = 0
curLines.forEachIndexed { r, line ->
line.forEachIndexed { c, ch ->
if (ch == 'O') score += curLines.size - r
}
}
return score
}
/** Rotate so that the left column is now the first row. */
fun rotate() {
val newLines = mutableListOf<MutableList<Char>>()
cols.forEach { c ->
newLines += rows.reversed().map { curLines[it][c] }.toMutableList()
}
curLines = newLines
}
fun print() {
curLines.forEach { println(it.joinToString("")) }
}
fun str() = curLines.joinToString("") { it.joinToString("") }
}
// part 1
fun List<String>.part1(): Int {
return Rocks(this).nRoll().score()
}
// part 2
fun List<String>.part2(): Int {
val cycles = 1000000000
var cycleSize = 7
var rocks = Rocks(this)
val scores = mutableListOf<Int>()
(1..cycles).forEach {
if (it % 1000 == 0) print(".")
repeat(4) {
rocks = rocks.nRoll()
rocks.rotate()
}
scores += rocks.score()
// look for a cycle after a number of runs
if (it % 1000 == 0) {
(7..1000).forEach { cs ->
val last7 = scores.takeLast(cs)
val previous7 = scores.takeLast(2*cs).dropLast(cs)
if (last7 == previous7) {
cycleSize = cs
println(".. found a cycle of $cycleSize after $it iterations")
println(" Cycle: $last7")
println(" Iterations remaining: ${cycles - it}")
val scoreEnd = last7[(cycles - 1 - it) % cs]
println(" Score at end: $scoreEnd")
return scoreEnd
}
}
println(".. unable to find a cycle after $it iterations")
}
}
println()
return rocks.score()
}
// calculate answers
val day = 14
val input = getDayInput(day, 2023)
val testResult = testInput.part1()
val testResult2 = testInput.part2()
val answer1 = input.part1().also { it.print }
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 3,203 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/hopkins/aoc/day1/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day1
import java.io.File
const val debug = true
const val part = 2
val digits = listOf("1", "2", "3", "4", "5", "6" ,"7", "8", "9")
val digitNames = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val valueMap: Map<String, Int> = buildMap {
digits.mapIndexed { index, digit -> put(digit, index + 1)}
digitNames.mapIndexed { index, digit -> put(digit, index + 1)}
}
/** Advent of Code 2023: Day 1 */
fun main() {
// Read the lines into a list
val inputFile = File("input/input1.txt")
val lines: List<String> = inputFile.readLines()
if (debug) {
println("Value map: $valueMap")
}
if (debug) {
println("Value | Line")
lines.take(5).forEach { line ->
val value = extractCalibrationValue(line)
println("$value | $line")
}
}
// Calculate the sum of calibration values extracted from each line
val output = lines.sumOf { extractCalibrationValue(it) }
println("Output: $output") // 54990
}
/** Returns the calibration value from the line. Concatenates the first and last digit in the line. */
fun extractCalibrationValue(line: String): Int {
return findDigit(line, true) * 10 + findDigit(line, false)
}
fun findDigit(line: String, isFirst: Boolean): Int {
val list = buildList {
add(digits)
if (part == 2) {
add(digitNames)
}
}
val firstDigit = list.flatMap { container ->
container
.filter { digit -> line.contains(digit) }
.map { digit -> Pair(digit, if (isFirst) { line.indexOf(digit) } else { line.lastIndexOf(digit)})}
}.minBy { if (isFirst) { it.second } else { line.length - it.second } }.first
return valueMap[firstDigit]!!
} | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 1,784 | aoc2023 | MIT License |
classroom/src/main/kotlin/com/radix2/algorithms/extras/RunningMedian.kt | rupeshsasne | 190,130,318 | false | {"Java": 66279, "Kotlin": 50290} | package com.radix2.algorithms.extras
import java.util.PriorityQueue
fun runningMedian(a: Array<Int>): Array<Double> {
val minPQ = PriorityQueue<Int> { o1, o2 -> o2.compareTo(o1) }
val maxPQ = PriorityQueue<Int>()
val medians = Array(a.size) { 0.0 }
for (i in 0..a.lastIndex) {
add(a[i], minPQ, maxPQ)
rebalance(minPQ, maxPQ)
medians[i] = getMedian(minPQ, maxPQ)
}
return medians
}
fun getMedian(minPQ: PriorityQueue<Int>, maxPQ: PriorityQueue<Int>): Double {
val maxHeap = if (minPQ.size > maxPQ.size) minPQ else maxPQ
val minHeap = if (minPQ.size > maxPQ.size) maxPQ else minPQ
return if (maxHeap.size == minHeap.size) {
(maxHeap.peek() + minHeap.peek()).toDouble() / 2
} else {
maxHeap.peek().toDouble()
}
}
fun rebalance(minPQ: PriorityQueue<Int>, maxPQ: PriorityQueue<Int>) {
val biggerHeap = if (minPQ.size > maxPQ.size) minPQ else maxPQ
val smallerHeap = if (minPQ.size > maxPQ.size) maxPQ else minPQ
if (biggerHeap.size - smallerHeap.size >= 2) {
smallerHeap.add(biggerHeap.poll())
}
}
fun add(num: Int, minPQ: PriorityQueue<Int>, maxPQ: PriorityQueue<Int>) {
if (minPQ.isEmpty() || num < minPQ.peek()) {
minPQ.add(num)
} else {
maxPQ.add(num)
}
}
fun main(args: Array<String>) {
val reader = System.`in`.bufferedReader()
val aCount = reader.readLine().trim().toInt()
val a = Array(aCount) { 0 }
for (aItr in 0 until aCount) {
val aItem = reader.readLine().trim().toInt()
a[aItr] = aItem
}
reader.close()
val result = runningMedian(a)
println(result.joinToString("\n"))
}
| 0 | Java | 0 | 1 | 341634c0da22e578d36f6b5c5f87443ba6e6b7bc | 1,681 | coursera-algorithms-part1 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SearchInRotatedSortedArray2.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
/**
* 81. Search in Rotated Sorted Array II
* @see <a href="https://leetcode.com/problems/search-in-rotated-sorted-array-ii/">Source</a>
*/
fun interface SearchInRotatedSortedArray2 {
fun search(nums: IntArray, target: Int): Boolean
}
class SearchInRotatedSortedArray2BS : SearchInRotatedSortedArray2 {
override fun search(nums: IntArray, target: Int): Boolean {
val n: Int = nums.size
if (n == 0) return false
var end = n - 1
var start = 0
while (start <= end) {
val mid = start + (end - start) / 2
if (nums[mid] == target) {
return true
}
if (!isBinarySearchHelpful(nums, start, nums[mid])) {
start++
continue
}
// which array does pivot belong to.
val pivotArray = existsInFirst(nums, start, nums[mid])
// which array does target belong to.
val targetArray = existsInFirst(nums, start, target)
// if pivot and target exist in different sorted arrays, recall that xor is true
// when both operands are distinct
if (pivotArray xor targetArray) {
if (pivotArray) {
start = mid + 1 // pivot in the first, target in the second
} else {
end = mid - 1 // target in the first, pivot in the second
}
} else { // If pivot and target exist in same sorted array
if (nums[mid] < target) {
start = mid + 1
} else {
end = mid - 1
}
}
}
return false
}
// returns true if we can reduce the search space in current binary search space
private fun isBinarySearchHelpful(arr: IntArray, start: Int, element: Int): Boolean {
return arr[start] != element
}
// returns true if element exists in first array, false if it exists in second
private fun existsInFirst(arr: IntArray, start: Int, element: Int): Boolean {
return arr[start] <= element
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,777 | kotlab | Apache License 2.0 |
src/Day04.kt | bromhagen | 572,988,081 | false | {"Kotlin": 3615} | import kotlin.math.min
fun main() {
fun splitToIntRanges(pair: String): Pair<IntRange, IntRange> {
val ranges = pair.split(",").map {
val start = it.split("-")[0]
val end = it.split("-")[1]
IntRange(start.toInt(), end.toInt())
}
val first = ranges[0]
val second = ranges[1]
return Pair(first, second)
}
fun part1(input: List<String>): Int {
return input.count { pair ->
val (first, second) = splitToIntRanges(pair)
first.intersect(second).size >= min(first.count(), second.count())
}
}
fun part2(input: List<String>): Int {
return input.count { pair ->
val (first, second) = splitToIntRanges(pair)
first.intersect(second).isNotEmpty()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0ee6d96e790d9ebfab882351b3949c9ba372cb3e | 1,064 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day08_seven_segment/SevenSegment.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day08_seven_segment
import kotlin.experimental.and
import kotlin.experimental.or
import kotlin.experimental.xor
/**
* Well this is easy, just grab the stuff after the pipe and count how many
* strings have length 1, 4, 7, or 8. Done! Smells like a trap...
*
* Part two is about picking structures based on problem analysis. As well as
* ignoring "garbage" information from the business problem. The segment mapping
* doesn't matter; all that matters is the set-of-segments to digit mapping.
* Which is a clue; it has "set" right there. Analysis (to build the decision
* tree) also shows that you need "overlaps" and "difference" type operations
* to dissect which set-of-segments is which. Those are set operations!
*
* As a bonus, while `Set<Char>` is sufficient for correctness, there are only
* seven segments. A bitmap stored as a single Byte is equivalent, and has
* significantly less overhead. Set's "intersect" is bitwise `and`, and
* "difference" is `xor`.
*/
fun main() {
util.solve(390, ::partOne)
util.solve(1011785, ::partTwo)
// ~1.24ms w/ SortedSet<Char>
// ~800μs w/ Int
// ~750μs w/ Byte
}
fun partOne(input: String) =
input
.lineSequence()
.map { it.substring(61) }
.flatMap { it.split(' ') }
.map(String::length)
.count { it == 2 || it == 3 || it == 4 || it == 7 }
typealias Segments = Byte
private fun String.toSegments(): Segments =
fold(0) { agg, c ->
when (c) {
'a' -> agg or 0b1
'b' -> agg or 0b10
'c' -> agg or 0b100
'd' -> agg or 0b1000
'e' -> agg or 0b10000
'f' -> agg or 0b100000
'g' -> agg or 0b1000000
else -> throw IllegalArgumentException("unknown segment '$c'")
}
}
fun partTwo(input: String) =
input
.lineSequence()
.map { line ->
line.split('|')
.map {
it.trim()
.split(' ')
.map(String::toSegments)
}
}
.map { decipherOutput(it.first(), it.last()) }
.sum()
private infix fun Segments.overlaps(other: Segments) =
this and other == other
private fun <K, E> Map<K, Collection<E>>.pull(key: K): E {
val items = get(key)!!
if (items.size == 1) return items.first()
throw IllegalStateException("Multiple items exist for key")
}
private fun <K, E> Map<K, Collection<E>>.pull(
key: K,
predicate: (E) -> Boolean
): E {
val items = get(key)!!
if (items.size == 1 && predicate(items.first())) return items.first()
val matches = items.filter(predicate)
if (matches.size == 1) return matches.first()
if (matches.isEmpty()) throw NoSuchElementException()
throw IllegalStateException("Multiple items match predicate")
}
fun decipherOutput(
observations: List<Segments>,
output: List<Segments>
): Int {
val segToValue = mutableMapOf<Segments, Int>()
val valueToSeg = mutableMapOf<Int, Segments>()
val byLen = observations.groupBy(Segments::countOneBits)
fun Segments.means(value: Int): Segments {
segToValue[this] = value
valueToSeg[value] = this
(byLen[countOneBits()] as MutableList).remove(this)
return this
}
// simple ones
val one = byLen.pull(2).means(1)
val four = byLen.pull(4).means(4)
byLen.pull(3).means(7)
byLen.pull(7).means(8)
// five-segment ones
val fourSubOne = four xor one
byLen.pull(5) { it overlaps fourSubOne }.means(5)
byLen.pull(5) { it overlaps one }.means(3)
byLen.pull(5).means(2)
// six segment ones
byLen.pull(6) { it overlaps four }.means(9)
byLen.pull(6) { it overlaps one }.means(0)
byLen.pull(6).means(6)
return output.fold(0) { n, seg ->
n * 10 + segToValue[seg]!!
}
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 3,885 | aoc-2021 | MIT License |
src/Day08.kt | uekemp | 575,483,293 | false | {"Kotlin": 69253} |
fun parseInput(input: List<String>): Array<IntArray> {
val cols = input[0].length
val rows = input.size
val grid = Array(rows) { IntArray(cols) }
input.forEachIndexed { y, line ->
val row = grid[y]
line.toCharArray().forEachIndexed { x, char ->
row[x] = char.digitToInt()
}
}
// grid.forEach { row ->
// println(row.joinToString())
// }
return grid
}
class NoProgression(val value: Int): Iterable<Int> {
private val iterator = object : Iterator<Int> {
override fun hasNext() = true
override fun next() = value
}
override fun iterator() = iterator
}
fun Array<IntArray>.isVisible(x0: Int, y0: Int): Boolean {
val cols = this[0].size
val rows = this.size
val treeSize = this[y0][x0]
var vLeft = true
for (x in x0 - 1 downTo 0) {
if (this[y0][x] >= treeSize) {
vLeft = false
break
}
}
var vRight = true
for (x in x0 + 1 until cols) {
if (this[y0][x] >= treeSize) {
vRight = false
break
}
}
var vTop = true
for (y in y0 - 1 downTo 0) {
if (this[y][x0] >= treeSize) {
vTop = false
break
}
}
var vBottom = true
for (y in y0 + 1 until rows) {
if (this[y][x0] >= treeSize) {
vBottom = false
break
}
}
return vLeft || vRight || vTop || vBottom
}
fun main() {
val r1 = IntProgression.fromClosedRange(1, 1, 0)
r1.forEach {
println(it)
}
fun part1(input: List<String>): Int {
val grid = parseInput(input)
var count = 0
grid.forEachIndexed { y, row ->
row.forEachIndexed { x, tree ->
if (grid.isVisible(x, y)) {
count++
}
}
}
return count
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
val input = readInput("Day08")
check(part1(input) == 1798)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bc32522d49516f561fb8484c8958107c50819f49 | 2,231 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day20/Day20.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day20
import readInput
import java.util.UUID
data class Node(
var uuid: UUID,
var value: Long,
var next: Node? = null,
var prev: Node? = null
) {
override fun toString(): String {
return value.toString()
}
}
class CircularLinkedList {
private val listOfPointers = mutableListOf<Node>()
private var zeroNode: Node? = null
fun initList(input: List<String>, mulBy: Int) {
var head: Node? = null
var tail: Node? = null
var curP: Node? = null
for (idx in input.indices) {
val value = input[idx].trim().toLong() * mulBy
if (idx == 0) {
head = Node(value = value, uuid = UUID.randomUUID())
listOfPointers.add(head)
curP = head
if (head.value == 0L) zeroNode = head
continue
}
val newNode = Node(value = value, uuid = UUID.randomUUID())
curP!!.next = newNode
newNode.prev = curP
curP = newNode
if (idx == input.size - 1) tail = newNode
if (newNode.value == 0L) zeroNode = newNode
listOfPointers.add(newNode)
}
head!!.prev = tail
tail!!.next = head
}
fun mix(times: Int) {
repeat(times) {
listOfPointers.forEach {
val itemToMove = it
if (itemToMove.value == 0L) return@forEach
var positionsToMove = itemToMove.value.mod(listOfPointers.size - 1)
var insertAfter = itemToMove
while (positionsToMove-- > 0) {
insertAfter = insertAfter.next!!
}
// delete
itemToMove.prev!!.next = itemToMove.next
itemToMove.next!!.prev = itemToMove.prev
// insert in between node
itemToMove.prev = insertAfter
itemToMove.next = insertAfter.next
insertAfter.next!!.prev = itemToMove
insertAfter.next = itemToMove
}
}
}
fun answer(): Long {
val list = listOf(1000, 2000, 3000)
var sum = 0L
list.forEach {
var count = 1
var temp = zeroNode
while (count <= it) {
temp = temp!!.next
count++
}
sum += temp!!.value
}
return sum
}
}
fun main() {
fun solve(input: List<String>, part1: Boolean = true): Long {
return CircularLinkedList().let {
it.initList(input, if (part1) 1 else 811589153)
it.mix(if (part1) 1 else 10)
it.answer()
}
}
val input = readInput("/day20/Day20")
println(solve(input, part1 = true))
println(solve(input, part1 = false))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 2,848 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/patbeagan/days/Day09.kt | patbeagan1 | 576,401,502 | false | {"Kotlin": 57404} | package dev.patbeagan.days
import dev.patbeagan.days.Day09.Point.Companion.coord
import java.lang.IllegalArgumentException
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.sqrt
/**
* [Day 9](https://adventofcode.com/2022/day/9)
*/
class Day09 : AdventDay<Int> {
override fun part1(input: String) = parseInput(input).let { commands ->
val rope = Rope()
commands.forEach {
rope.moveBy(it)
}
rope.print()
rope.countPreviousTailPositions()
}
override fun part2(input: String) = 0
fun parseInput(input: String) = input
.trim()
.split("\n")
.map { s ->
s
.split(" ")
.let {
val direction = it[0]
val amount = it[1].toInt()
when (direction) {
"U" -> Command.Up(amount)
"D" -> Command.Down(amount)
"L" -> Command.Left(amount)
"R" -> Command.Right(amount)
else -> throw IllegalArgumentException()
}
}
}
sealed class Command(val amount: Int) {
class Up(amount: Int) : Command(amount)
class Down(amount: Int) : Command(amount)
class Left(amount: Int) : Command(amount)
class Right(amount: Int) : Command(amount)
}
class Rope {
private var positionHead: Point = 0 coord 0
private var positionTail: Point = 0 coord 0
private val previousTailPositions = mutableListOf(positionTail)
fun countPreviousTailPositions() = previousTailPositions.distinct().count()
fun moveTo(dest: Point) {
positionHead = dest
if (positionTail.fartherThan1Cell(dest)) {
val vector = positionTail.vectorTo(positionHead)
positionTail = Point(
positionTail.x + vector.x.compareTo(0),
positionTail.y + vector.y.compareTo(0)
)
previousTailPositions.add(positionTail)
}
}
fun moveBy(command: Command) {
repeat(command.amount) {
when (command) {
is Command.Down -> moveTo(positionHead.x coord positionHead.y + 1)
is Command.Left -> moveTo(positionHead.x - 1 coord positionHead.y)
is Command.Right -> moveTo(positionHead.x + 1 coord positionHead.y)
is Command.Up -> moveTo(positionHead.x coord positionHead.y - 1)
}
}
}
fun print() {
println("$positionHead $positionTail ${positionHead.trueDistanceTo(positionTail)}")
previousTailPositions.distinct().let { points ->
val cols = points.maxBy { it.x }.x - points.minBy { it.x }.x
val rows = points.maxBy { it.y }.y - points.minBy { it.y }.y
for (y in 0 until rows) {
for (x in 0 until cols) {
if (points.contains(Point(x, y))) {
print("#")
} else {
print("-")
}
}
println()
}
}
}
private fun angle(destY: Int, destX: Int) = atan2(destY.toDouble(), destX.toDouble()) * (180 / Math.PI)
}
data class Vector(
val x: Int = 0,
val y: Int = 0,
)
data class Point(
val x: Int = 0,
val y: Int = 0,
) {
fun trueDistanceTo(p: Point) = hypot(x.toDouble() - p.x, y.toDouble() - p.y)
fun fartherThan1Cell(p: Point): Boolean =
trueDistanceTo(p) > sqrt(2.0) // where sqrt(2.0) is the diagonal distance
fun vectorTo(p: Point) = Vector(p.x - x, p.y - y)
companion object {
infix fun Int.coord(y: Int) = Point(this, y)
}
}
} | 0 | Kotlin | 0 | 0 | 4e25b38226bcd0dbd9c2ea18553c876bf2ec1722 | 4,021 | AOC-2022-in-Kotlin | Apache License 2.0 |
src/Day05.kt | gillyobeast | 574,413,213 | false | {"Kotlin": 27372} | import utils.appliedTo
import utils.readInput
import java.util.*
fun main() {
val whitespace = "\\s".toRegex()
fun List<String>.extractIndices(): List<String> {
return last().chunked(4).filter(String::isNotBlank)
}
fun parse(input: List<String>): Pair<List<String>, List<String>> = input
.filter(String::isNotEmpty)
.partition { it.startsWith("move") }
fun String.extractLabel(): Char {
return if (this.length > 1) this[1] else this[0]
}
fun String.stripSpaces(): String = replace(whitespace, "")
fun buildStacks(stackData: List<String>): List<Stack<Char>> {
val numberOfStacks = stackData.extractIndices().last().stripSpaces()
val stacks = mutableListOf<Stack<Char>>()
repeat(numberOfStacks.toInt()) {
stacks.add(Stack())
}
stackData.dropLast(1).forEach {
it.chunked(4).forEachIndexed { idx, item ->
if (item.isNotBlank()) {
stacks[idx].push(item.extractLabel())
}
}
}
return stacks.onEach { it.reverse() }.toList()
}
fun String.triple(stacks: List<Stack<Char>>): Triple<Int, Stack<Char>, Stack<Char>> {
val split = this.split(whitespace)
val count = split[1].toInt()
val source = stacks[split[3].toInt() - 1]
val target = stacks[split[5].toInt() - 1]
return Triple(count, source, target)
}
fun String.applyTo(stacks: List<Stack<Char>>) {
val (count, source, target) = triple(stacks)
repeat(count) {
target.push(source.pop())
}
}
fun String.applyToPart2(stacks: List<Stack<Char>>) {
val (count, source, target) = triple(stacks)
val temp = Stack<Char>()
repeat(count) {
temp.push(source.pop())
}
repeat(count) {
target.push(temp.pop())
}
}
fun List<String>.applyTo(stacks: List<Stack<Char>>) {
forEach { it.applyTo(stacks) }
}
fun List<String>.applyToPart2(stacks: List<Stack<Char>>) {
forEach { it.applyToPart2(stacks) }
}
fun part1(input: List<String>): String {
val (instructions, stackData) = parse(input)
val stacks = buildStacks(stackData)
instructions.applyTo(stacks)
return stacks.map { it.pop() }.joinToString("")
}
fun part2(input: List<String>): String {
val (instructions, stackData) = parse(input)
val stacks = buildStacks(stackData)
instructions.applyToPart2(stacks)
return stacks.map { it.pop() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("input_test")
val input = readInput("input")
// part 1
::part1.appliedTo(testInput, returns = "CMZ")
println("Part 1: ${part1(input)}")
// part 2
::part2.appliedTo(testInput, returns = "MCD")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 8cdbb20c1a544039b0e91101ec3ebd529c2b9062 | 3,021 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/org/deep/quined/main.kt | RedDocMD | 347,395,585 | false | null | package org.deep.quined
import org.deep.quined.algo.Cube
import org.deep.quined.algo.findMinCovers
import org.deep.quined.algo.partitionCubesByOneCount
import org.deep.quined.algo.reduceOneStep
import java.io.BufferedReader
import java.io.InputStreamReader
fun main(args: Array<String>) {
val reader = BufferedReader(InputStreamReader(System.`in`))
println("Please enter the number of variables:")
val termCount = Integer.parseInt(reader.readLine())
println("Please enter the min-terms (space separated):")
val minTerms = reader.readLine().split(" ").map { Cube(Integer.parseInt(it), termCount) }
println("Please enter the don't cares (space separated, none for none):")
val line = reader.readLine()
val dontCares = if (line == "none") listOf() else line.split(" ").map { Cube(Integer.parseInt(it), termCount) }
val allCubes = minTerms.toMutableList()
allCubes.addAll(dontCares)
doQuineMcClusky(allCubes, termCount, minTerms, dontCares)
}
fun doQuineMcClusky(initCubes: List<Cube>, termCount: Int, usefulCubes: List<Cube>, dontCares: List<Cube>) {
var partitions = partitionCubesByOneCount(initCubes)
val primeImplicants = mutableListOf<Cube>()
while (true) {
val (nextCubes, leftovers) = reduceOneStep(partitions, termCount)
primeImplicants.addAll(leftovers)
printPartitions(partitions, leftovers)
println("")
println("")
if (nextCubes.isEmpty()) break
partitions = partitionCubesByOneCount(nextCubes)
}
val distinctPrimeImplicants = primeImplicants.distinct()
val primeImplicantStrings = distinctPrimeImplicants.map { cube -> cube.minTerms.joinToString { it.toString() } }
val maxWidth = primeImplicantStrings.maxOf { it.length }
val paddingString = "".padStart(maxWidth)
val allCubes = usefulCubes.joinToString(" | ") { cube -> "%3s".format(cube.minTerms[0].toString()) }
println("$paddingString | $allCubes")
for ((idx, primeImplicant) in distinctPrimeImplicants.withIndex()) {
val implicantString = "%${maxWidth}s".format(primeImplicantStrings[idx])
val cubeString =
usefulCubes.joinToString(" | ") { if (it.minTerms[0] in primeImplicant.minTerms) " ✓ " else " " }
println("$implicantString | $cubeString")
}
val minCovers =
findMinCovers(distinctPrimeImplicants, usefulCubes.map { it.minTerms[0] }, dontCares.map { it.minTerms[0] })
println("\nMin-covers:")
for (cover in minCovers) println("$cover")
}
fun printPartitions(parts: Map<Int, List<Cube>>, leftovers: List<Cube>) {
for ((oneCount, cubes) in parts) {
val dcCount = cubes.first().dcCount
println("<$oneCount:1, $dcCount:D>")
println("---------------------------")
for (cube in cubes) {
val variables = cube.terms.joinToString(" ") { it.toString() }
val minTerms = cube.minTerms.joinToString { it.toString() }
val tail = if (cube in leftovers) "" else "✓"
println("$variables | ($minTerms) $tail")
}
println("---------------------------")
println()
}
} | 0 | Kotlin | 1 | 3 | 22e0783bcc257ffad15cbf3008ab59b623787920 | 3,145 | QuinedAgain | MIT License |
kotlin/0983-minimum-cost-for-tickets.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} | /*
* DFS solution
*/
class Solution {
fun mincostTicketsRecursive(days: IntArray, costs: IntArray): Int {
val dp = mutableMapOf<Int, Int>()
fun dfs(dayIndex: Int): Int {
if (dayIndex == days.size) return 0
if (dayIndex in dp) return dp[dayIndex]!!
dp[dayIndex] = Int.MAX_VALUE
for ((daysCount, cost) in intArrayOf(1, 7, 30).zip(costs)) {
var nextDayIndex = dayIndex
while (nextDayIndex < days.size && days[nextDayIndex] < days[dayIndex] + daysCount)
nextDayIndex++
dp[dayIndex] = min(dp[dayIndex]!!, cost + dfs(nextDayIndex))
}
return dp[dayIndex]!!
}
return dfs(0)
}
}
/*
* BFS Solution
*/
class Solution {
fun mincostTickets(days: IntArray, costs: IntArray): Int {
val dp = mutableMapOf<Int, Int>()
for (dayIndex in days.indices.reversed()) {
dp[dayIndex] = Int.MAX_VALUE
for ((daysCount, cost) in intArrayOf(1, 7, 30).zip(costs)) {
var nextDayIndex = dayIndex
while (nextDayIndex < days.size && days[nextDayIndex] < days[dayIndex] + daysCount)
nextDayIndex++
dp[dayIndex] = min(dp[dayIndex]!!, cost + dp.getOrDefault(nextDayIndex, 0))
}
}
return dp[0]!!
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,397 | leetcode | MIT License |
src/Day03.kt | manuel-martos | 574,260,226 | false | {"Kotlin": 7235} | fun main() {
println("part01 -> ${solveDay03Part01()}")
println("part02 -> ${solveDay03Part02()}")
}
private fun solveDay03Part01() =
readInput("day03")
.sumOf { line ->
val half1 = line.substring(0 until line.length / 2).toSet()
val half2 = line.substring(line.length / 2 until line.length).toSet()
val result = half1.intersect(half2)
result.sumOf { it.priority() }
}
private fun solveDay03Part02() =
readInput("day03")
.chunked(3)
.sumOf {
it[0].toSet().intersect(it[1].toSet()).intersect(it[2].toSet()).sumOf(Char::priority)
}
private fun Char.priority(): Int =
if (isLowerCase()) {
this - 'a' + 1
} else {
this - 'A' + 27
}
| 0 | Kotlin | 0 | 0 | 5836682fe0cd88b4feb9091d416af183f7f70317 | 777 | advent-of-code-2022 | Apache License 2.0 |
solutions/src/Day06.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | fun main() {
fun part1(input: String): Int = count(input, 4)
fun part2(input: String): Int = count(input, 14)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test").first()
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06").first()
println(part1(input))
println(part2(input))
}
private fun count(input: String, startOfPacketMarkerCount: Int): Int {
val startOfPacketMarkerIndex = startOfPacketMarkerCount - 1
var count = startOfPacketMarkerIndex
var letters: String
while (count < input.length) {
letters = input.substring(count - startOfPacketMarkerIndex, count + 1)
if (!hasDuplicate(letters, startOfPacketMarkerIndex)) {
break
} else {
count++
}
}
return count + 1
}
private fun hasDuplicate(letters: String, untilIndex: Int): Boolean {
val sortedChars = letters.toCharArray().sorted()
for (i in 0 until untilIndex) {
if (sortedChars[i] == sortedChars[i + 1]) {
return true
}
}
return false
}
| 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 1,154 | advent-of-code-22 | Apache License 2.0 |
src/main/day10/Day10.kt | rolf-rosenbaum | 543,501,223 | false | {"Kotlin": 17211} | package day10
import day06.Point
import readInput
fun part1(input: List<String>) {
var stars = input.map { it.toStar() }
var seconds = 0
do {
stars = stars.move()
seconds++
} while(!stars.prettyPrint())
println(seconds)
}
fun main() {
val input = readInput("main/day10/Day10")
part1(input)
}
fun String.toStar(): Star {
val values = this.split(">")
val pos = values[0]
val vel = values[1]
val coordinates = pos.split("<").last().split(",").map { it.trim().toInt() }
val velocity = vel.split("<").last().split(",").map { it.trim().toInt() }
return Star(coordinates.first(), coordinates.last(), Vector(velocity.first(), velocity.last()))
}
data class Vector(val x: Int, val y: Int)
data class Star(val x: Int, val y: Int, val velocity: Vector) {
fun toPoint(): Point = Point(x,y)
}
fun List<Star>.move(): List<Star> = this.map {
Star(it.x + it.velocity.x, it.y + it.velocity.y, it.velocity)
}
fun List<Star>.prettyPrint(): Boolean {
val minY = minOf { it.y }
val maxY = maxOf { it.y }
if (maxY - minY > 15) return false
val points = map{it.toPoint()}
(minY..maxY).forEach { y ->
(minOf { it.x } .. maxOf{it.x}).forEach { x ->
if(points.contains(Point(x,y))) print("#") else print(" ")
}
println()
}
println()
return true
} | 0 | Kotlin | 0 | 0 | dfd7c57afa91dac42362683291c20e0c2784e38e | 1,395 | aoc-2018 | Apache License 2.0 |
src/week-day-1/ContainsDuplicate.kt | luix | 573,258,926 | false | {"Kotlin": 7897, "Java": 232} | package week1
/**
* Contains Duplicate (easy)
* Problem Statement
* Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
*
* Example 1:
*
* Input: nums= [1, 2, 3, 4]
* Output: false
* Explanation: There are no duplicates in the given array.
* Example 2:
*
* Input: nums= [1, 2, 3, 1]
* Output: true
* Explanation: '1' is repeating.
*
*/
class ContainsDuplicate {
// This will solve in O(n log n) time | O(1) space
fun containsDuplicate(nums: List<Int>): Boolean {
val sorted = nums.sorted()
for (i in 1 until sorted.size) {
if (sorted[i - 1] == sorted[i]) return true
}
return false
}
}
fun main() {
val solution = ContainsDuplicate()
val tests = listOf(
listOf(1, 2, 3, 4),
listOf(1, 2, 3, 1),
listOf(),
listOf(1, 1, 1, 1)
)
tests.forEach {
assert(solution.containsDuplicate(it))
println("$it contains duplicate: ${solution.containsDuplicate(it)}")
}
}
| 0 | Kotlin | 0 | 0 | 8e9b605950049cc9a0dced9c7ba99e1e2458e53e | 1,087 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day08/day8.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day08
import biz.koziolek.adventofcode.*
fun main() {
val inputFile = findInput(object {})
val map = parseWastelandMap(inputFile.bufferedReader().readLines())
println("It takes ${map.followInstructions().size - 1} moves to move from $START_ID to $END_ID")
println("It takes ${map.followGhostInstructions()} moves to move from $START_ID to $END_ID")
}
const val START_ID = "AAA"
const val END_ID = "ZZZ"
data class WastelandMap(
val instructions: String,
val nodes: Map<String, WastelandNode>
) {
val ghostStartNodes = nodes.values.filter { it.isGhostStart }.sortedBy { it.id }
val ghostEndNodes = nodes.values.filter { it.isGhostEnd }.sortedBy { it.id }
fun followInstructions(): List<WastelandNode> =
findPath(START_ID) { node -> node.id == END_ID }
private fun findPath(startId: String, isEnd: (WastelandNode) -> Boolean): List<WastelandNode> = buildList {
var movesCount = 0
var currentNode = nodes.values.single { it.id == startId }
add(currentNode)
while (!isEnd(currentNode)) {
val move = instructions[movesCount % instructions.length]
currentNode = findNext(currentNode, move)
add(currentNode)
movesCount++
}
}
@Deprecated("Should work I think, but toList() will eat ALL your memory. will take FOREVER and there's sequence overhead.")
fun followGhostInstructions1(): Sequence<List<WastelandNode>> = sequence {
var movesCount = 0
var currentNodes = ghostStartNodes
yield(currentNodes)
while (!currentNodes.all { it.isGhostEnd }) {
val move = instructions[movesCount % instructions.length]
currentNodes = currentNodes.map { findNext(it, move) }
yield(currentNodes)
movesCount++
}
}
@Deprecated("Should work I think, with no memory issues, but takes FOREVER.")
fun followGhostInstructions2(): Long {
var movesCount = 0L
var currentNodes = ghostStartNodes
val found = mutableSetOf<Int>()
while (!currentNodes.all { it.isGhostEnd }) {
val move = instructions[(movesCount % instructions.length).toInt()]
currentNodes = currentNodes.map { findNext(it, move) }
movesCount++
currentNodes.forEachIndexed { index, node ->
if (node.isGhostEnd) {
found.add(index)
}
}
}
return movesCount
}
fun followGhostInstructions(): Long {
val counts = ghostStartNodes
.map { node ->
findPath(node.id) { possibleEndNode ->
possibleEndNode.isGhostEnd
}.size - 1
}
.map { it.toLong() }
if (counts.any { it % instructions.length != 0L }) {
throw AssertionError("Counts are not multiply of instructions length - I don't know what to do")
}
return lcm(counts)
}
private fun findNext(node: WastelandNode, move: Char) =
when (move) {
'L' -> node.left!!
'R' -> node.right!!
else -> throw IllegalArgumentException("Unknown move: $move")
}
}
data class WastelandNode(val id: String) {
var left: WastelandNode? = null
var right: WastelandNode? = null
val isGhostStart = id[2] == 'A'
val isGhostEnd = id[2] == 'Z'
}
fun parseWastelandMap(lines: List<String>): WastelandMap {
val instructions = lines.first()
val regex = Regex("(?<start>[A-Z0-9]+) = \\((?<left>[A-Z0-9]+), (?<right>[A-Z0-9]+)\\)")
val nodes = lines
.drop(2)
.mapNotNull { regex.find(it) }
.map { WastelandNode(it.groups["start"]!!.value) }
.associateBy { it.id }
lines
.drop(2)
.mapNotNull { regex.find(it) }
.forEach { match ->
val startNode = nodes[match.groups["start"]!!.value]!!
val leftNode = nodes[match.groups["left"]!!.value]!!
val rightNode = nodes[match.groups["right"]!!.value]!!
startNode.left = leftNode
startNode.right = rightNode
}
return WastelandMap(instructions, nodes)
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 4,264 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/TreeAncestor.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 1483. Kth Ancestor of a Tree Node
* @see <a href="https://leetcode.com/problems/kth-ancestor-of-a-tree-node/">Source</a>
*/
class TreeAncestor(n: Int, parent: IntArray) {
private var tree: Array<MutableList<Int>> = Array(n) { ArrayList() }
private var level: MutableList<MutableList<Int>> = ArrayList() // nodes in a level
private var dfn = IntArray(n) // dfs number
private var ndfn = 0 // dfs number starts wih 0
private var depth = IntArray(n) // depth of each node
init {
for (i in 0 until n) {
tree[i] = ArrayList()
}
for (i in 1 until n) { // build tree
tree[parent[i]].add(i)
}
dfs(0, 0)
}
fun getKthAncestor(node: Int, k: Int): Int {
val d = depth[node]
if (d - k < 0) return -1
val list: List<Int> = level[d - k]
var left = 0
var right = list.size
while (left < right) { // binary search
val mid = left + (right - left) / 2
if (dfn[list[mid]] < dfn[node]) { // find the first node larger than or equal to dfn[node]
left = mid + 1
} else {
right = mid
}
}
return list[left - 1] // ancestor is the largest one smaller than dfn[node]
}
private fun dfs(n: Int, dep: Int) {
if (level.size == dep) {
level.add(ArrayList())
}
dfn[n] = ndfn++ // mark dfs number
depth[n] = dep // save the depth
level[dep].add(n) // save nodes into level
for (child in tree[n]) {
dfs(child, dep + 1)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,276 | kotlab | Apache License 2.0 |
src/Day03.kt | jamie23 | 573,156,415 | false | {"Kotlin": 19195} | fun main() {
fun part1(input: List<String>) = input
.map { s ->
listOf(
s.substring(0, s.length / 2),
s.substring(
s.length / 2, s.length
)
)
}
.map { it.commonChar() }
.sumOf { it.calculatePriority() }
fun part2(input: List<String>) = input
.chunked(3)
.map { it[0].toSet().intersect(it[1].toSet().intersect(it[2].toSet())) }
.sumOf { it.single().calculatePriority() }
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
fun List<String>.commonChar(): Char {
return first().toSet().intersect(this[1].toSet()).single()
}
fun Char.calculatePriority() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> error("Unsupported character")
} | 0 | Kotlin | 0 | 0 | cfd08064654baabea03f8bf31c3133214827289c | 994 | Aoc22 | Apache License 2.0 |
src/day01/Day01.kt | banshay | 572,450,866 | false | {"Kotlin": 33644} | fun main() {
fun part1(input: Elves): Int {
return input.maxOf { it.value.sum() }
}
fun part2(input: Elves): Int {
val maxList = input.map { it.value.sum() }.sortedDescending()
return maxList[0] + maxList[1] + maxList[2]
}
fun sanitizeInput(input: String): Elves {
return input.split(System.lineSeparator() + System.lineSeparator())
.foldIndexed(mutableMapOf()) { i, acc, item ->
var inventory = item
//remove trailing newline, prevent it from becoming an inventory position
if (item.lastIndexOf(System.lineSeparator()) == item.lastIndex + 1 - System.lineSeparator().length) {
inventory = item.dropLast(System.lineSeparator().length)
}
acc[i] = inventory.split(System.lineSeparator()).map { it.toInt() }
acc
}
}
// test if implementation meets criteria from the description, like:
val testInput = sanitizeInput(readInputText("Day01_test"))
println("test part1: ${part1(testInput)}")
println("test part2: ${part2(testInput)}")
val input = sanitizeInput(readInputText("Day01"))
println("result part1: ${part1(input)}")
println("result part2: ${part2(input)}")
}
typealias Elves = Map<Int, List<Int>>
| 0 | Kotlin | 0 | 0 | c3de3641c20c8c2598359e7aae3051d6d7582e7e | 1,331 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/com/dmc/advent2022/Day11.kt | dorienmc | 576,916,728 | false | {"Kotlin": 86239} | package com.dmc.advent2022
//--- Day 11: Monkey in the Middle ---
class Day11 : Day<Long> {
override val index = 11
override fun part1(input: List<String>): Long {
val monkeys: List<Monkey> = input.chunked(7).map { Monkey.of(it) }
repeat(20) {
monkeys.play{ it / 3 }
}
monkeys.forEach{ m -> println("$m inspected items ${m.numInspectedItems} times")}
return monkeys.business()
}
override fun part2(input: List<String>): Long {
val monkeys: List<Monkey> = input.chunked(7).map { Monkey.of(it) }
val monkeyMod = monkeys.map { it.test }.product()
repeat(10_000) {
monkeys.play{ it % monkeyMod }
}
monkeys.forEach{ m -> println("$m inspected items ${m.numInspectedItems} times")}
return monkeys.business()
}
}
fun List<Monkey>.business() : Long =
this
.sortedByDescending { it.numInspectedItems }
.take(2)
.map { it.numInspectedItems }
.reduce{ a,b -> a * b }
fun List<Monkey>.play(changeToWorryLevel: (Long) -> Long) {
this.forEach { monkey ->
val thrownItems = monkey.turn(changeToWorryLevel)
for(entry in thrownItems) {
val item = entry.first
val otherMonkey : Monkey = this[entry.second]
otherMonkey.catchItem(item)
}
}
}
class Monkey(
val id: Int,
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val trueMonkey: Int,
val falseMonkey: Int
) {
var numInspectedItems: Long = 0L
companion object {
fun of(input: List<String>): Monkey {
val id = input[0].substringAfter(" ").substringBefore(":").toInt()
val items = input[1].substringAfter(":").split(",").map{ it.trim().toLong() }.toMutableList()
val operationFunction = input[2].substringAfter("new = ")
val operationVal = input[2].substringAfterLast(" ")
val operation: (Long) -> Long = when {
operationFunction == "old * old" -> ({it * it})
"+" in operationFunction -> ({it + operationVal.toLong()})
operationFunction.contains("*") -> ({it * operationVal.toLong()})
else -> ({it})
}
val test = input[3].substringAfter("by ").toLong()
val trueMonkey = input[4].substringAfterLast(" ").toInt()
val falseMonkey = input[5].substringAfterLast(" ").toInt()
return Monkey(id, items, operation, test, trueMonkey, falseMonkey)
}
}
fun turn(changeToWorryLevel: (Long) -> Long): List<Pair<Long,Int>> {
//On a single monkey's turn,
//it inspects and throws all of the items it is holding one at a time and in the order listed.
val thrownItems = mutableListOf<Pair<Long,Int>>()
for(item in items) {
//inspect
val worry = changeToWorryLevel(operation(item))
val targetMonkey = if (worry % test == 0L) trueMonkey else falseMonkey
thrownItems.add(worry to targetMonkey)
}
numInspectedItems += items.size
items.clear()
return thrownItems
}
fun catchItem(item: Long) {
items.add(item)
}
override fun toString(): String {
return "monkey $id: ${items.joinToString(",")}"
}
}
fun main() {
val day = Day11()
// test if implementation meets criteria from the description, like:
val testInput = readInput(day.index, true)
check(day.part1(testInput) == 10605L)
val input = readInput(day.index)
day.part1(input).println()
day.part2(testInput).println()
day.part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 207c47b47e743ec7849aea38ac6aab6c4a7d4e79 | 3,703 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/day1.kt | kevinrobayna | 317,548,264 | false | null | import java.util.stream.Collectors
// https://adventofcode.com/2020/day/1
class Day1(
private val values: List<Int>
) {
fun solve(): Pair<Int, Int> {
val pairs: MutableList<Pair<Int, Int>> = mutableListOf()
for (outLoop in values.indices) {
for (innerLoop in values.indices) {
if (!outLoop.equals(innerLoop)) {
val first = Math.max(values[outLoop], values[innerLoop])
val second = Math.min(values[outLoop], values[innerLoop])
pairs.add(Pair(first, second))
}
}
}
return pairs
.filter { it.first + it.second == 2020 }
.distinct()
.get(0)
}
}
// https://adventofcode.com/2020/day/1
class Day1Part2(
private val values: List<Int>
) {
fun solve(): Triple<Int, Int, Int> {
val tuples: MutableList<Triple<Int, Int, Int>> = mutableListOf()
for (outLoop in values) {
for (innerLoop in values) {
for (innerInnerLoop in values) {
val points = listOf(outLoop, innerLoop, innerInnerLoop).sorted()
tuples.add(Triple(points[0], points[1], points[2]))
}
}
}
return tuples
.filter { it.first.plus(it.second).plus(it.third) == 2020 }
.distinct()
.get(0)
}
}
fun main() {
val problem = Day1::class.java.getResource("day1.txt")
.readText()
.split('\n')
.stream()
.map { it.toInt() }
.collect(Collectors.toList())
val pair = Day1(problem).solve()
println("solution = $pair, x*y = ${pair.first * pair.second}")
val triple = Day1Part2(problem).solve()
println("solution = $triple, x*y*z = ${triple.first * triple.second * triple.third}")
} | 0 | Kotlin | 0 | 0 | 8b1a84dc1fbace0d87866ae57791db3a67bcba70 | 1,857 | adventofcode_2020 | MIT License |
src/Day03/Day03.kt | hectdel | 573,376,349 | false | {"Kotlin": 5426} | package Day03
import java.io.File
fun main() {
val chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun Char.toValue(): Int = chars.indexOf(this) + 1
check('p'.toValue() == 16)
check('L'.toValue() == 38)
fun part1(input: String): Int {
var commonChars = mutableListOf<Char>()
input.lines()
.map { it.substring(0, it.length.div(2)) to it.substring(it.length.div(2), it.length) }
.map {
it.first.iterator().forEach { char ->
if (it.second.contains(char)) {
commonChars.add(char)
return@map
}
}
}
return commonChars.map { it.toValue() }.sum()
}
fun containsChar(c: Char, line:String):Boolean {
return line.contains(c)
}
fun calculateResult(n: Int, input: String) : Int{
val grouped = input
.lines()
.chunked(n)
return grouped.sumOf {
it.first()
.toCharArray()
.first { char -> IntRange(1, n - 1).all { n -> containsChar(char, it[n]) } }
.toValue()
}
}
fun part2(input: String): Int {
return calculateResult(3, input)
}
val testInput = File("src/Day03/test_data.txt").readText()
println(part1(testInput))
check(part1(testInput) == 157)
check(part2(testInput) == 70 )
val input = File("src/Day03/data.txt").readText()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cff5677a654a18ceb199cc52fdd1c865dea46e1e | 1,569 | aco-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxProbability.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 java.util.LinkedList
import java.util.PriorityQueue
import java.util.Queue
/**
* 1514. Path with Maximum Probability
* @see <a href="https://leetcode.com/problems/path-with-maximum-probability/">Source</a>
*/
fun interface MaxProbability {
operator fun invoke(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double
}
fun Array<IntArray>.buildGraph(succProb: DoubleArray): MutableMap<Int, MutableList<Pair<Int, Double>>> {
val graph: MutableMap<Int, MutableList<Pair<Int, Double>>> = HashMap()
for (i in this.indices) {
val u = this[i][0]
val v = this[i][1]
val pathProb = succProb[i]
graph.computeIfAbsent(
u,
) { ArrayList() }.add(Pair(v, pathProb))
graph.computeIfAbsent(
v,
) { ArrayList() }.add(Pair(u, pathProb))
}
return graph
}
/**
* Approach 1: Bellman-Ford Algorithm
*/
class MaxProbabilityBellmanFord : MaxProbability {
override operator fun invoke(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double {
val maxProb = DoubleArray(n)
maxProb[start] = 1.0
for (i in 0 until n - 1) {
var hasUpdate = false
for (j in edges.indices) {
val u = edges[j][0]
val v = edges[j][1]
val pathProb = succProb[j]
if (maxProb[u] * pathProb > maxProb[v]) {
maxProb[v] = maxProb[u] * pathProb
hasUpdate = true
}
if (maxProb[v] * pathProb > maxProb[u]) {
maxProb[u] = maxProb[v] * pathProb
hasUpdate = true
}
}
if (!hasUpdate) {
break
}
}
return maxProb[end]
}
}
/**
* Approach 2: Shortest Path Faster Algorithm
*/
class MaxProbabilityShortestPath : MaxProbability {
override operator fun invoke(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double {
val graph = edges.buildGraph(succProb)
val maxProb = DoubleArray(n)
maxProb[start] = 1.0
val queue: Queue<Int> = LinkedList()
queue.offer(start)
while (queue.isNotEmpty()) {
val curNode: Int = queue.poll()
for (neighbor in graph.getOrDefault(curNode, ArrayList())) {
val nxtNode: Int = neighbor.first
val pathProb: Double = neighbor.second
// Only update maxProb[nxtNode] if the current path increases
// the probability of reach nxtNode.
if (maxProb[curNode] * pathProb > maxProb[nxtNode]) {
maxProb[nxtNode] = maxProb[curNode] * pathProb
queue.offer(nxtNode)
}
}
}
return maxProb[end]
}
}
/**
* Approach 3: Dijkstra's Algorithm
*/
class MaxProbabilityDijkstra : MaxProbability {
override operator fun invoke(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double {
val graph = edges.buildGraph(succProb)
val maxProb = DoubleArray(n)
maxProb[start] = 1.0
val pq: PriorityQueue<Pair<Double, Int>> = PriorityQueue { a, b ->
-a.first.compareTo(b.first)
}
pq.add(Pair(1.0, start))
while (pq.isNotEmpty()) {
val cur: Pair<Double, Int> = pq.poll()
val curProb: Double = cur.first
val curNode: Int = cur.second
if (curNode == end) {
return curProb
}
for (nxt in graph.getOrDefault(curNode, ArrayList())) {
val nxtNode: Int = nxt.first
val pathProb: Double = nxt.second
if (curProb * pathProb > maxProb[nxtNode]) {
maxProb[nxtNode] = curProb * pathProb
pq.add(Pair(maxProb[nxtNode], nxtNode))
}
}
}
return 0.0
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,699 | kotlab | Apache License 2.0 |
codeforces/src/main/kotlin/contest1911/e.kt | austin226 | 729,634,548 | false | {"Kotlin": 23837} | import java.util.*
private fun String.splitWhitespace() = split("\\s+".toRegex())
fun greatestPowerUpTo(n: Int): Int? {
if (n < 1) {
return null
}
var p = 1
while (p < n) {
if (p * 2 > n) {
return p
}
p *= 2
}
return p
}
fun asPower2Sum(n: Int, k: Int): List<Int>? {
// First, find the smallest list of powers of 2 we can use to write n. If it's longer than k, return null.
val powers = LinkedList<Int>()
var remainder = n
var powersUsed = 0
while (remainder > 0) {
val p = greatestPowerUpTo(remainder)!!
remainder -= p
powers.add(p)
powersUsed++
if (powersUsed > k) {
// return null if not possible
return null
}
}
// Next, break up any powers we can until we can reach k, or we get all 1's.
while (powers.size < k) {
val f = powers.first
if (f == 1) {
// first value is a 1 - we can't reach k
return null
}
powers.removeFirst()
if (f == 2) {
powers.add(1)
powers.add(1)
} else {
powers.add(0, f / 2)
powers.add(0, f / 2)
}
}
return powers.sorted()
}
fun main() {
// Can we write n as a sum of exactly k powers of 2?
// n in 1..=1e9
// k in 1..=2e5
val (n, k) = readln().splitWhitespace().map { it.toInt() }
asPower2Sum(n, k)?.let {
println("YES")
println(it.joinToString(" "))
return
}
println("NO")
}
| 0 | Kotlin | 0 | 0 | 4377021827ffcf8e920343adf61a93c88c56d8aa | 1,569 | codeforces-kt | MIT License |
src/main/kotlin/de/dikodam/calendar/Day04.kt | dikodam | 433,719,746 | false | {"Kotlin": 51383} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.executeTasks
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day04().executeTasks()
}
private const val lineBreak = "\r\n"
class Day04 : AbstractDay() {
val rawInput = readInputRaw()
override fun task1(): String {
val (bingoNumers: List<Int>, bingoBoards: List<BingoBoard>) = parseInput(rawInput)
return bingoBoards.map { it.processUntilWin(bingoNumers) }
.minByOrNull { winningState -> winningState.index }
?.score.toString()
}
private fun parseInput(rawInput: String): Pair<List<Int>, List<BingoBoard>> {
val splitInput = rawInput.split("$lineBreak$lineBreak")
val bingoNumbers = splitInput[0].split(",")
.map { it.toInt() }
val bingoBoards = splitInput.drop(1)
.map { BingoBoard.from(it) }
return bingoNumbers to bingoBoards
}
override fun task2(): String {
val (bingoNumers: List<Int>, bingoBoards: List<BingoBoard>) = parseInput(rawInput)
return bingoBoards.map { it.processUntilWin(bingoNumers) }
.maxByOrNull { winningState -> winningState.index }
?.score.toString()
}
}
class BingoBoard(val bingoCells: List<BingoCell>) {
class BingoCell(val number: Int, var marked: Boolean = false) {
fun mark() {
marked = true
}
}
companion object {
fun from(rawString: String): BingoBoard {
val bingoCells = rawString.replace(lineBreak, " ")
.split(" ")
.filter { it.isNotBlank() }
.map { it.toInt() }
.map { BingoCell(it) }
return BingoBoard(bingoCells)
}
}
val winningLines = listOf(
listOf(0, 1, 2, 3, 4),
listOf(5, 6, 7, 8, 9),
listOf(10, 11, 12, 13, 14),
listOf(15, 16, 17, 18, 19),
listOf(20, 21, 22, 23, 24),
listOf(0, 5, 10, 15, 20),
listOf(1, 6, 11, 16, 21),
listOf(2, 7, 12, 17, 22),
listOf(3, 8, 13, 18, 23),
listOf(4, 9, 14, 19, 24),
listOf(0, 6, 12, 18, 24),
listOf(4, 8, 12, 16, 20)
)
fun boardIsWinning(): Boolean {
return winningLines
.any { winningLine -> // board is winning if any winning line has all marked bingo cells
winningLine.all { index -> bingoCells[index].marked }
}
}
fun processUntilWin(numbers: List<Int>): WinningState {
for (index in numbers.indices) {
val number = numbers[index]
processNumber(number)
if (boardIsWinning()) {
val score = number * bingoCells.filterNot { it.marked }.sumOf { it.number }
return WinningState(index, score)
}
}
error("something went wrong, processed all numbers but board didnt win")
}
fun processNumber(i: Int) {
bingoCells.filter { it.number == i }.forEach { it.mark() }
}
}
data class WinningState(val index: Int, val score: Int) | 0 | Kotlin | 0 | 1 | 4934242280cebe5f56ca8d7dcf46a43f5f75a2a2 | 3,107 | aoc-2021 | MIT License |
src/main/kotlin/se/brainleech/adventofcode/aoc2020/Aoc2020Day02.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2020
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
class Aoc2020Day02 {
open class PasswordPolicy(
val limitRule: String,
val character: Char,
val password: String
) {
open fun valid(): Boolean {
val (minOccurrence, maxOccurrence) = limitRule.split("-").map { it.toInt() }
return password.count { it == character } in (minOccurrence..maxOccurrence)
}
}
class PositionBasedPasswordPolicy(
positionRule: String,
character: Char,
password: String
) : PasswordPolicy(positionRule, character, password) {
override fun valid(): Boolean {
val (firstPosition, secondPosition) = limitRule.split("-").map { it.toInt() - 1 }
val excerpt = password[firstPosition] + "" + password[secondPosition]
return excerpt.count { it == character } == 1
}
}
private fun String.asPasswordPolicy(): PasswordPolicy {
val (limitRule, character, password) = this.split(" ")
return PasswordPolicy(limitRule, character.first(), password)
}
private fun String.asPositionBasedPasswordPolicy(): PasswordPolicy {
val (limitRule, character, password) = this.split(" ")
return PositionBasedPasswordPolicy(limitRule, character.first(), password)
}
fun part1(input: List<String>): Int {
return input
.asSequence()
.map { it.asPasswordPolicy() }
.count { it.valid() }
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.map { it.asPositionBasedPasswordPolicy() }
.count { it.valid() }
}
}
fun main() {
val solver = Aoc2020Day02()
val prefix = "aoc2020/aoc2020day02"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(2, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(1, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
} | 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 2,192 | adventofcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinPenaltyForShop.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
/**
* 2483. Minimum Penalty for a Shop
* @see <a href="https://leetcode.com/problems/minimum-penalty-for-a-shop">Source</a>
*/
fun interface MinPenaltyForShop {
infix operator fun invoke(customers: String): Int
fun helper(customers: String, penalty: Int, min: Int, earliest: Int): Triple<Int, Int, Int> {
var curPenalty = penalty
var minPenalty = min
var earliestHour = earliest
for (i in customers.indices) {
val ch: Char = customers[i]
// If status in hour i is 'Y', moving it to open hours decrement
// penalty by 1. Otherwise, moving 'N' to open hours increment
// penalty by 1.
if (ch == 'Y') {
curPenalty--
} else {
curPenalty++
}
// Update earliestHour if a smaller penalty is encountered.
if (curPenalty < minPenalty) {
earliestHour = i + 1
minPenalty = curPenalty
}
}
return Triple(curPenalty, minPenalty, earliestHour)
}
}
/**
* Approach 1: Two Passes
*/
class MinPenaltyForShopTwoPasses : MinPenaltyForShop {
override infix operator fun invoke(customers: String): Int {
var curPenalty = 0
for (i in customers.indices) {
if (customers[i] == 'Y') {
curPenalty++
}
}
// Start with closing at hour 0, the penalty equals all 'Y' in closed hours.
val minPenalty = curPenalty
val earliestHour = 0
return helper(customers, curPenalty, minPenalty, earliestHour).third
}
}
/**
* Approach 2: One Pass
*/
class MinPenaltyForShopOnePass : MinPenaltyForShop {
override infix operator fun invoke(customers: String) = helper(customers, 0, 0, 0).third
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,456 | kotlab | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.