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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
solutions/src/BallMaze.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} |
class BallMaze {
fun shortestDistance(maze: Array<IntArray>, start: IntArray, destination: IntArray) : Int {
return dfsMaze(maze, Pair(start[0],start[1]), Pair(destination[0],destination[1]),null, mutableSetOf()) ?: -1
}
private fun dfsMaze(maze: Array<IntArray>, start: Pair<Int,Int>, target: Pair<Int,Int>, direction: Direction?, visited: MutableSet<Pair<Int,Int>>) : Int? {
val yAxis = maze.size
val xAxis = maze[0].size
visited.add(start);
val possiblePaths = mutableListOf<Int?>();
val nextStep = when (direction) {
null -> null
Direction.LEFT-> Pair(start.first,start.second-1)
Direction.RIGHT -> Pair(start.first,start.second+1)
Direction.DOWN -> Pair(start.first-1,start.second)
Direction.UP -> Pair(start.first+1,start.second)
}
//hit a wall
if (nextStep == null || nextStep.first < 0 || nextStep.first >= yAxis || nextStep.second < 0 || nextStep.second >= xAxis || maze[nextStep.first][nextStep.second] == 1 ) {
if (start == target) {
return 0;
}
if (start.first+1<yAxis && !visited.contains(Pair(start.first+1,start.second)) && maze[start.first+1][start.second]!=1) {
possiblePaths.add(dfsMaze(maze, Pair(start.first+1,start.second),target,Direction.UP,visited.toMutableSet()))
}
if (start.first-1 >= 0 && !visited.contains(Pair(start.first-1,start.second))&& maze[start.first-1][start.second]!=1 ) {
possiblePaths.add(dfsMaze(maze, Pair(start.first-1,start.second),target,Direction.DOWN,visited.toMutableSet()))
}
if (start.second+1<xAxis && !visited.contains(Pair(start.first,start.second+1)) && maze[start.first][start.second+1]!=1 ) {
possiblePaths.add(dfsMaze(maze, Pair(start.first,start.second+1),target,Direction.RIGHT,visited.toMutableSet()));
}
if (start.second-1 >= 0 && !visited.contains(Pair(start.first,start.second-1)) && maze[start.first][start.second-1]!=1 ) {
possiblePaths.add(dfsMaze(maze, Pair(start.first,start.second-1),target,Direction.LEFT,visited.toMutableSet()));
}
}
else {
if (!visited.contains(nextStep)) {
possiblePaths.add(dfsMaze(maze,nextStep,target,direction,visited.toMutableSet()))
}
}
val minPath = possiblePaths.filterNotNull().min()
return if (minPath!=null) minPath+1 else null
}
private enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 2,662 | leetcode-solutions | MIT License |
src/Day20.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | class Mixer(val key: Long = 1L) {
// a list of pairs <number, original position>
val sequence = mutableListOf<Pair<Long, Int>>()
fun input(inp: List<String>) {
var counter = 0
inp.forEach {
check(it.length <= 5) {"Input line >$it< is longer than 5 characters!"} // still in Int range?
sequence.add(Pair(it.toLong() * key, counter))
counter++
}
}
fun doOneRound() {
for (i in 0..sequence.lastIndex) {
val indexedElement = sequence.find { it.second == i }!!
val indexedPos = sequence.indexOf(indexedElement)
sequence.removeAt(indexedPos)
var newPos: Long = indexedPos + indexedElement.first
newPos = newPos.mod(sequence.size.toLong())
sequence.add(newPos.toInt(), indexedElement)
}
}
fun coords(): Long {
val startElem = sequence.find { it.first == 0L }
val startPos = sequence.indexOf(startElem)
// 1000th after startPos
val offset = 1000
val off1 = (startPos + offset) % sequence.size
val off2 = (off1 + offset) % sequence.size
val off3 = (off2 + offset) % sequence.size
val sum = sequence[off1].first + sequence[off2].first + sequence[off3].first
return sum
}
}
fun main() {
fun part1(input: List<String>): Long {
val mix = Mixer()
mix.input(input)
mix.doOneRound()
return mix.coords()
}
fun part2(input: List<String>): Long {
val mix = Mixer(811_589_153L)
mix.input(input)
repeat(10) { mix.doOneRound() }
return mix.coords()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20-TestInput")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20-Input")
check(part1(input) < 9756)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 1,994 | AoC-2022-12-01 | Apache License 2.0 |
src/Day16.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} | import kotlin.math.max
fun main() {
val day = "16"
data class Valve(val idx: Int, val flowRate: Int, val tunnels: List<String>)
fun parseInput(input: List<String>) = input
.map { Regex("([A-Z]{2}|\\d+)").findAll(it).map { res -> res.value }.toList() }
.mapIndexed { idx, res -> res[0] to Valve(idx, res[1].toInt(), res.drop(2)) }
.toMap()
fun part1(input: List<String>): Int {
val valves = parseInput(input)
println(valves)
data class Configuration(val openValvesMask: Long, val atValve: String)
val maxTime = 30
val dp = Array(maxTime + 1) { HashMap<Configuration, Int>() }
fun memoize(time: Int, openValvesMask: Long, atValve: String, pressure: Int) {
val config = Configuration(openValvesMask, atValve)
// Get the current pressure for this valve
val current = dp[time][config]
// Set the time-configuration pressure to the given pressure if it doesn't exit or is lower
if (current == null || pressure > current) dp[time][config] = pressure
}
// In the beginning we are at valve AA, no valve open, no pressure released
memoize(0, 0, "AA", 0)
for (time in 0 ..< maxTime) {
// Get all memoized configurations and their pressure level at the current time
for ((config, pressure) in dp[time]) {
val (openValvesMask, valveName) = config
val valve = valves[valveName]!!
val valvePos = 1L shl valve.idx
// if this configuration's valve's flow rate is relevant and the valve is not yet open...
if (valve.flowRate != 0 && (valvePos and openValvesMask) == 0L) {
// ...open it and increase pressure level correspondingly
memoize(
/*time*/ time + 1,
/*openValveMask*/ valvePos or openValvesMask,
/*atValve*/ valveName,
/*pressure*/ pressure + (maxTime - time -1) * valve.flowRate
)
}
// Now go to all the neighbouring valves (without opening them yet)
for (neighbourValve in valve.tunnels) {
memoize(
/*time*/ time + 1,
/*openValveMask*/ openValvesMask,
/*atValve*/ neighbourValve,
/*pressure*/ pressure
)
}
}
}
return dp[maxTime].maxOf { (_, pressure) -> pressure }
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 1651)
// check(part2(testInput) == 0)
val input = readInput("Day${day}")
println(part1(input))
// println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 2,993 | aoc-2022 | Apache License 2.0 |
project/src/problems/EuclideanAlgorithm.kt | informramiz | 173,284,942 | false | null | package problems
/**
* https://codility.com/media/train/10-Gcd.pdf
*/
object EuclideanAlgorithm {
/**
* Returns greatest common divisor of both a and b
*/
fun gcd(a: Int, b: Int): Int {
if (a % b == 0) {
return b
}
return gcd(b, a % b)
}
/**
* Binary Euclidean Algorithm:
*
* A binary algorithm for finding gcd(N,M) is based on the following
* If N and M are even, gcd(N, M) = 2 gcd(N/2, M/2),
* If N is even while M is odd, then gcd(N, M) = gcd(N/2, M),
* If both N and M are odd, then (since N-M is even) |N-M| < max(N,M). Replace the largest of the two with |N-M|.
*
* Why is this algorithm more efficient?
*
* 1. The algorithm is known as binary because, unlike the original one, it does not use general division of integers
* but only division by 2. Since in a computer numbers are represented in the Binary system anyway,
* you should not be surprised to learn that there is a special machine instruction that implements division by 2
* in a highly efficient manner. This is known as the right shift wherein the rightmost bit is discharged,
* the remaining bits are shifted one place to the right and the leftmost bit is set to 0.
*
* 2. Another handy operation is a bitwise conjunction &. N & 1 is either 1 or 0 for any integer N. It's 1 iff N is odd.
* Bitwise conjunction is also implemented in hardware, i.e., as a machine instruction.
*
* For more info: https://www.cut-the-knot.org/blue/binary.shtml
*
* NOTE: As in case if N and M are even,
* gcd(N, M) = 2 gcd(N/2, M/2)
* or as it can be = 2 * 2 * 2 ... gcd(N/2, M/2)
* so we will write it as
* gcd(N, M) = residual * gcd(N/2, M/2)
* where residual can be any number multiple of 2
*/
private fun gcdBinary(a: Int, b: Int, res: Int = 1): Int {
if (a == b) {
return res * a
}
if (a % 2 == 0 && b % 2 == 0) {
//both a and b are even so
return gcdBinary(a/2, b/2, 2 * res)
} else if (a % 2 == 0) {
//a is even while b is odd
return gcdBinary(a/2, b, res)
} else if (b % 2 == 0) {
//b is even while as is odd
return gcdBinary(a, b/2, res)
} else if (a > b) {
//both a, b are odd and a > b so set a = a - b
return gcdBinary(a-b, b, res)
} else {
//both a, b are odd and b > a so set b = b - a
return gcdBinary(a, b - a, res)
}
}
fun gcdBinary(a: Int, b: Int): Int {
return gcdBinary(a, b, 1)
}
/**
* The least common multiple (LCM) of two integers a and b is the smallest positive integer that
* is divisible by both a and b. There is the following relation:
* lcm(a, b) = (a·b) / gcd(a,b)
*
* so if we know gcd we can calculate LCM
* @return long, long because otherwise integer overflow can happen
*/
fun lcm(a: Long, b: Long): Long {
return ((a * b) / gcdBinary(a.toInt(), b.toInt()))
}
/**
* Find lcm for multiple integers
* lcm(a1, a2, ... , an) = lcm(a1, lcm(a2, ... , an))
*/
fun lcm(A: Array<Int>): Long {
if (A.size < 2) return -1
var lcmValue = 1L
for (i in 0 until A.size) {
lcmValue = lcm(lcmValue, A[i].toLong())
}
return lcmValue
}
/**
* https://app.codility.com/programmers/lessons/12-euclidean_algorithm/chocolates_by_numbers/
* ------ChocolatesByNumbers----------
* There are N eatChocolates in a circle. Count the number of eatChocolates you will eat.
*
* DETAILS:
* Two positive integers N and M are given. Integer N represents the number of eatChocolates arranged in a circle, numbered from 0 to N − 1.
* You start to eat the eatChocolates. After eating a chocolate you leave only a wrapper.
* You begin with eating chocolate number 0. Then you omit the next M − 1 eatChocolates or wrappers on the circle, and eat the following one.
* More precisely, if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division).
* You stop eating when you encounter an empty wrapper.
*
* For example, given integers N = 10 and M = 4. You will eat the following eatChocolates: 0, 4, 8, 2, 6.
* The goal is to count the number of eatChocolates that you will eat, following the above rules.
*
* Write a function:
* class Solution { public int solution(int N, int M); }
*
* that, given two positive integers N and M, returns the number of eatChocolates that you will eat.
* For example, given integers N = 10 and M = 4. the function should return 5, as explained above.
*
* Write an efficient algorithm for the following assumptions:
* N and M are integers within the range [1..1,000,000,000].
*
* @param N, number of eatChocolates number in range [0, N-1]
*/
fun eatChocolates(N: Int, M: Int): Int {
//Consider the circle as a straight line, the place where the first eaten chocolate is revisited, proceeding
//with step M is actually the same as you if you proceed with step N. For example, N=10, if you proceed with
//step N=10 then first chocolate is revisited at step 20. Similarly, if you proceed with step M=4 then
//first eaten chocolate is revisited at step 20. If N = 12, M = 9 then first chocolate will be revisited
//at step 36 because this is where M and N meet.
// As step# in both cases is same so the step/place where
//first eaten chocolate is revisited (or an empty wrapper is encountered) is LCM of both M and N, so LCM(M,N)
//
//step at which first chocolate revisited = stepNumberOfRevisit = LCM(M,N)
//total jumps after which that (step occurs) chocolate is revisited,
//proceeding with step M is = stepNumberOfRevisit / M = lcm(M, N) / M
return (lcm(M.toLong(), N.toLong()) / M).toInt()
}
/**
* https://app.codility.com/programmers/lessons/12-euclidean_algorithm/common_prime_divisors/
* CommonPrimeDivisors
* Check whether two numbers have the same prime divisors.
*
* A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.
* A prime D is called a prime divisor of a positive integer P if there exists a positive integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20.
* You are given two positive integers N and M. The goal is to check whether the sets of prime divisors of integers N and M are exactly the same.
* For example, given:
* N = 15 and M = 75, the prime divisors are the same: {3, 5};
* N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5};
* N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}.
* Write a function:
* class Solution { public int solution(int[] A, int[] B); }
* that, given two non-empty arrays A and B of Z integers, returns the number of positions K for which the prime divisors of A[K] and B[K] are exactly the same.
* For example, given:
* A[0] = 15 B[0] = 75
* A[1] = 10 B[1] = 30
* A[2] = 3 B[2] = 5
* the function should return 1, because only one pair (15, 75) has the same set of prime divisors.
* Write an efficient algorithm for the following assumptions:
* Z is an integer within the range [1..6,000];
* each element of arrays A, B is an integer within the range [1..2,147,483,647].
*/
fun countNumbersWithCommonPrimeDivisors(A: Array<Int>, B: Array<Int>): Int {
var count = 0
for (i in 0 until A.size) {
if (haveCommonPrimeDivisors(A[i], B[i])) {
count++
}
}
return count
}
private fun haveCommonPrimeDivisors(a: Int, b: Int): Boolean {
if (a == b) {
//as both are equal so yes, they have same divisors
return true
} else if (a == 1 || b == 1) {
//as either b or a is 1 and other not so they will never have same prime divisors
return false
}
//If b and a have same prime divisors then their GCD will contain all the prime divisors
//
//-------Why GCD must contain all prime divisors?---------
//Proof is simple. Let g be the gcd of a and b. So we can express a and b as
// a=gc
// b=gd.
// If d and c had any common prime factor p, then p*g would be the gcd, contradicting our
// definition of g as the gcd. Hence the gcd of a,b contains ALL the common factors of a,b.
//---------------
val G = gcd(a, b)
//G is first divisor of a, let's get the next divisor of a. a/G will next divisor
var nextDivisorA = a/G
//keep taking g = gcd(nextDivisorA, G) and dividing nextDivisorA with that g (i.e, nextDivisorA /= g)
//until we reach nextDivisorA = 1 (means A is good) or we get gcd g = 1 (means A is not good).
//Note: G in gcd(nextDivisorA, G) makes sure that next divisor we get also divides G (which means also b)
while (nextDivisorA != 1) {
val g = gcd(nextDivisorA, G)
if (g == 1) {
//nextDivisorA and G does not have any common divisor which means a has a prime
//divisor that can't divide B
return false
}
//get the next divisor of A
nextDivisorA /= g
}
//now repeat the same process B
var nextDivisorB = b / G
while (nextDivisorB != 1) {
val g = gcd(nextDivisorB, G)
if (g == 1) {
return false
}
nextDivisorB /= g
}
return true
}
} | 0 | Kotlin | 0 | 0 | a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4 | 10,027 | codility-challenges-practice | Apache License 2.0 |
src/day3/Day03.kt | helbaroudy | 573,339,882 | false | null | package day3
import readInput
fun main() {
fun getType(compartment1: String, compartment2: String) = compartment1.first { compartment2.contains(it) }
fun Char.toPriority() = if (this >= 'a') {
this - 'a' + 1
} else {
this - 'A' + 1 + 26
}
fun part1(input: List<String>): Int = input.fold(0) { total, entry ->
val compartment1 = entry.substring(0 until entry.length / 2)
val compartment2 = entry.substringAfter(compartment1)
val type = getType(compartment1, compartment2)
total + type.toPriority()
}
fun getBadgeType(rucksack1: String, rucksack2: String, rucksack3: String) =
rucksack1.first { rucksack2.contains(it) && rucksack3.contains(it) }
fun part2(input: List<String>): Int {
var total = 0
for (i in input.indices step 3) {
val badgeType = getBadgeType(input.get(i), input.get(i + 1), input.get(i + 2))
total += badgeType.toPriority()
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
//part1(testInput)
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e9b98fc0eda739048e68f4e5472068d76ee50e89 | 1,312 | aoc22 | Apache License 2.0 |
2020/src/main/kotlin/de/skyrising/aoc2020/day13/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2020.day13
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.longs.LongArrayList
fun modInv(a: Long, b: Long): Long {
var a = a
var b = b
val m = b
var q = 0L
var x = 0L
var y = 1L
if (b == 1L) return 0
while (a > 1) {
if (b == 1L) {
y = x
break
}
// println("$a / $b")
q = a / b
run {
val t = b
b = a - q * b
a = t
}
run {
val t = x
x = y - q * x
y = t
}
}
if (y < 0) y += m
return y
}
fun crt(divisors: LongArray, remainders: LongArray): Long {
val product = remainders.reduce(Long::times)
var sum = 0L
for (i in divisors.indices) {
val partialProduct = product / remainders[i]
val inverse = modInv(partialProduct, remainders[i])
// println("x % ${divisors[i]} = ${remainders[i]}, $partialProduct, $inverse")
sum += partialProduct * inverse * divisors[i]
}
return sum % product
}
inline fun crt(n: Int, divisors: (Int) -> Long, remainders: (Int) -> Long): Long {
var product = 1L
for (i in 0 until n) product *= remainders(i)
var sum = 0L
for (i in 0 until n) {
val rem = remainders(i)
val partialProduct = product / rem
val inverse = modInv(partialProduct, rem)
sum += partialProduct * inverse * divisors(i)
}
return sum % product
}
val test = TestInput("""
939
7,13,x,x,59,x,31,19
""")
@PuzzleName("Shuttle Search")
fun PuzzleInput.part1v0(): Any {
val earliest = lines[0].toInt()
val buses = lines[1].split(",").stream().filter { it != "x" }.mapToInt(String::toInt).toArray()
var i = earliest
while (true) {
for (bus in buses) {
if (i % bus == 0) return (i - earliest) * bus
}
i++
}
}
@PuzzleName("Shuttle Search")
fun PuzzleInput.part1v1(): Any {
val earliest = lines[0].toInt()
val buses = lines[1].split(",").stream().filter { it != "x" }.mapToInt(String::toInt).toArray()
var pair = Pair(0, Integer.MAX_VALUE)
for (bus in buses) {
if (earliest % bus == 0) return 0
val dist = bus * (earliest / bus + 1) - earliest
if (dist < pair.second) pair = Pair(bus, dist)
}
return pair.first * pair.second
}
fun PuzzleInput.part2v0(): Any {
val split = lines[1].split(",")
val buses = LongArrayList()
val indexes = LongArrayList()
split.forEachIndexed { i, s ->
if (s == "x") return@forEachIndexed
buses.add(s.toLong())
indexes.add(i.toLong())
}
// println(buses)
// println(indexes)
return crt(
LongArray(buses.size) { i ->
val bus = buses.getLong(i)
(bus - indexes.getLong(i) % bus) % bus
},
buses.toLongArray()
)
}
fun PuzzleInput.part2v1(): Any {
val remainders = LongArrayList()
val divisors = LongArrayList()
var i = 0
if (!chars.positionAfter('\n')) throw IllegalArgumentException("Invalid input")
if (!chars.until('\n')) throw IllegalArgumentException("Invalid input")
chars.splitToRanges(',') { from, to ->
val index = i++
if (to == from + 1 && this[position() + from] == 'x') return@splitToRanges
val bus = substring(from, to).toLong()
remainders.add(bus)
divisors.add((bus - index % bus) % bus)
}
return crt(remainders.size, divisors::getLong, remainders::getLong)
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 3,522 | aoc | MIT License |
src/Day05.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | import java.util.SortedSet
import kotlin.math.min
import kotlin.time.measureTimedValue
typealias VMap = Pair<LongRange, Long>
fun main() {
val input = readInput("Day05")
fun String.splitRange(): VMap {
val p = split("\\s+".toRegex())
val r = p[2].toLong()
val dr = p[0].toLong() //.let { it until it + r }
val sr = p[1].toLong().let { it until it + r }
return sr to dr
}
fun VMap.sourceRange() = this.first
fun VMap.get(source: Long): Long {
if (this.first.contains(source)) {
val (sr, dr) = this
return dr + (source - sr.min())
}
return source
}
fun SortedSet<VMap>.get(source: Long): Long = measureTimedValue {
for (r in this) {
if (r.sourceRange().contains(source)) {
return@measureTimedValue r.get(source)
}
if (r.sourceRange().first > source)
break
}
return@measureTimedValue source
}.let {
println("SortedSet<VMap>.get took ${it.duration}")
it.value
}
fun SortedSet<VMap>.mapRange(range: LongRange): List<LongRange> = measureTimedValue {
// Border checks
if (range.last < first().sourceRange().first || range.first > this.last().sourceRange().last)
return listOf(range)
val result = mutableListOf<LongRange>()
var head = range.first
for (vmap in this) {
val sourceRange = vmap.sourceRange()
if (sourceRange.last < range.first) {
println("skip")
continue
}
if (sourceRange.first > head) {
result.add(head..<sourceRange.first)
val end = min(range.last, sourceRange.last)
result.add(vmap.get(sourceRange.first)..vmap.get(end))
head = end + 1
} else if (sourceRange.first <= head && head <= sourceRange.last) {
val start = head
val end = min(sourceRange.last, range.last)
result.add(vmap.get(start)..vmap.get(end))
head = end + 1
}
if (head > range.last) {
return@measureTimedValue result
}
}
return@measureTimedValue result
}.let {
println("SortedSet<VMap>.mapRange took ${it.duration}")
it.value
}
fun SortedSet<VMap>.mapRange(rl: List<LongRange>): List<LongRange> = measureTimedValue {
var rangeIndex = 0
var vmapIndex = 0
val vmapList = this.toList()
val result = mutableListOf<LongRange>()
fun getSourceRange(i: Int) = vmapList[i].sourceRange()
fun getRange(i: Int) = rl[i]
var head = rl[0].first
while (vmapIndex < this.size && rangeIndex < rl.size && head < rl.last().last) {
var sourceRange = getSourceRange(vmapIndex)
var range = getRange(rangeIndex)
if (sourceRange.last < range.first) {
vmapIndex++
continue
}
if (sourceRange.first > range.last) {
rangeIndex++
continue
}
head = range.first
while (vmapIndex < this.size && rangeIndex < rl.size) {
sourceRange = getSourceRange(vmapIndex)
range = getRange(rangeIndex)
val vmap = vmapList[vmapIndex]
if (sourceRange.first > head) {
result.add(head..<sourceRange.first)
val end = min(range.last, sourceRange.last)
val rToAdd = vmap.get(sourceRange.first)..vmap.get(end)
result.add(rToAdd)
head = end + 1
} else if (sourceRange.first <= head && head <= sourceRange.last) {
val start = head
val end = min(sourceRange.last, range.last)
val rToAdd = vmap.get(start)..vmap.get(end)
result.add(rToAdd)
head = end + 1
}
if (head > sourceRange.last)
vmapIndex++
if (head > range.last) {
rangeIndex++
break
}
}
}
if (head < rl.last().last) {
result.add(head..getRange(rangeIndex).last)
result.addAll(rl.subList(rangeIndex + 1, rl.size))
}
val queue = mutableListOf<LongRange>()
result.sortedBy { it.first }.forEach {
queue.lastOrNull()?.let { lastElem ->
if (lastElem.last + 1 == it.first) {
queue.removeLast()
queue.add(lastElem.first()..it.last)
} else queue.add(it)
} ?: queue.add(it)
}
return@measureTimedValue queue
}.let {
println("SortedSet<VMap>.mapRange took ${it.duration}")
it.value
}
fun part1(input: List<String>): Long {
val input = input.filter { it.isNotBlank() }
val seeds = input[0].split(":")[1].trim().split("\\s+".toRegex()).map { it.trim().toLong() }
val mapList = mutableListOf<SortedSet<VMap>>()
var i = 1
while (i < input.size) {
if (input[i].contains("map")) {
val dict = sortedSetOf(compareBy<VMap> { it.first.first })
i++
while (i < input.size && !input[i].contains("map")) {
dict.add(input[i].splitRange())
i++
}
mapList.add(dict)
}
}
mapList.println()
return seeds.minOf { seed ->
mapList.fold(seed) { acc, map -> map.get(acc) }
}
}
fun part2(input: List<String>): Long {
val input = input.filter { it.isNotBlank() }
val seeds =
input[0].split(":")[1].trim().split("\\s+".toRegex()).map { it.trim().toLong() }.chunked(2).map {
it[0] until it[0] + it[1]
}.sortedBy { it.first }
println(seeds)
val mapList = mutableListOf<SortedSet<VMap>>()
var i = 1
while (i < input.size) {
if (input[i].contains("map")) {
val dict = sortedSetOf(compareBy<VMap> { it.first.first })
i++
while (i < input.size && !input[i].contains("map")) {
dict.add(input[i].splitRange())
i++
}
mapList.add(dict)
}
}
mapList.println()
return mapList.fold(seeds) { acc, map ->
map.mapRange(acc).also { println(it) }
}[0].first
}
// part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 7,018 | aoc-2023 | Apache License 2.0 |
src/main/kotlin/adventofcode/year2020/Day14DockingData.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2020
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.String.replaceAt
class Day14DockingData(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val initializationInstructions by lazy { input.lines().map(InitializationInstruction::invoke) }
override fun partOne() = initializationInstructions
.fold(Pair("X".repeat(36), emptyMap<Long, Long>())) { (mask, memoryMap), instruction ->
when (instruction) {
is MaskInstruction -> Pair(instruction.mask, memoryMap)
is MemoryInstruction -> Pair(
mask,
memoryMap + mapOf(
instruction.address to (mask.indices)
.fold(instruction.value.toString(2).padStart(mask.length, '0')) { result, index ->
if (mask[index] == 'X') result else result.replaceAt(index, mask[index])
}.toLong(2)
)
)
}
}.second.values.sum()
override fun partTwo() = initializationInstructions
.fold(Pair("0".repeat(36), emptyMap<Long, Long>())) { (mask, memoryMap), instruction ->
when (instruction) {
is MaskInstruction -> Pair(instruction.mask, memoryMap)
is MemoryInstruction -> {
val addressMask = (mask.indices)
.fold(instruction.address.toString(2).padStart(mask.length, '0')) { result, index ->
if (mask[index] == '0') result else result.replaceAt(index, mask[index])
}
Pair(
mask,
memoryMap + (addressMask.indices)
.fold(listOf(addressMask)) { acc, index ->
when {
addressMask[index] != 'X' -> acc
else -> acc.flatMap { listOf(it.replaceAt(index, '0'), it.replaceAt(index, '1')) }
}
}
.map { it.toLong(2) to instruction.value }
)
}
}
}.second.values.sum()
companion object {
private sealed class InitializationInstruction {
companion object {
operator fun invoke(input: String): InitializationInstruction {
val parts = input.split(" = ")
return when (parts.first()) {
"mask" -> MaskInstruction(parts.last())
else -> MemoryInstruction(parts.first().substring(4 until parts.first().length - 1).toLong(), parts.last().toLong())
}
}
}
}
private data class MaskInstruction(val mask: String) : InitializationInstruction()
private data class MemoryInstruction(val address: Long, val value: Long) : InitializationInstruction()
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 3,090 | AdventOfCode | MIT License |
src/Day09.kt | robotfooder | 573,164,789 | false | {"Kotlin": 25811} | data class Step(val dir: Direction, val length: Int)
data class Move(val x: Int, val y: Int)
enum class Direction(val move: Move) {
UP(Move(0, 1)),
DOWN(Move(0, -1)),
LEFT(Move(-1, 0)),
RIGHT(Move(1, 0));
companion object {
fun fromString(dir: String): Direction {
return when (dir) {
"U" -> UP
"D" -> DOWN
"R" -> RIGHT
"L" -> LEFT
else -> error(dir)
}
}
}
}
fun main() {
fun getDiff(first: Int, second: Int): Int {
val diff = first - second
return if (diff > 1) {
1
} else if (diff < -1) {
-1
} else {
diff
}
}
fun part1(input: List<String>): Int {
val steps = input.map { it.toStep() }
var headPosition = Pair(0, 0)
val tailPositions = mutableSetOf<Pair<Int, Int>>()
tailPositions.add(Pair(0, 0))
for (step in steps) {
repeat(step.length) {
headPosition += step.dir.move
val lastTailPosition = tailPositions.last()
if (!headPosition.isTouching(lastTailPosition)) {
val yDiff = getDiff(headPosition.second, lastTailPosition.second)
val xDiff = getDiff(headPosition.first, lastTailPosition.first)
val newTailPos = Pair(lastTailPosition.first + xDiff, lastTailPosition.second + yDiff)
tailPositions.add(newTailPos)
}
}
}
return tailPositions.size
}
fun part2(input: List<String>): Int {
val tailPositions = mutableSetOf<Pair<Int, Int>>()
val steps = input.map { it.toStep() }
val knots = MutableList(10) {
Pair(0, 0)
}
for (step in steps) {
repeat(step.length) {
knots[0] = knots[0] + step.dir.move
for (i in 0 until knots.size - 1) {
if (!knots[i].isTouching(knots[i + 1])) {
val yDiff = getDiff(knots[i].second, knots[i + 1].second)
val xDiff = getDiff(knots[i].first, knots[i + 1].first)
knots[i + 1] = Pair(knots[i + 1].first + xDiff, knots[i + 1].second + yDiff)
}
}
tailPositions.add(knots.last())
}
}
return tailPositions.size
}
val day = "09"
// test if implementation meets criteria from the description, like:
runTest(46, day, ::part1)
runTest(36, day, ::part2)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private operator fun Pair<Int, Int>.plus(move: Move): Pair<Int, Int> = Pair(this.first + move.x, this.second + move.y)
private fun Pair<Int, Int>.isTouching(otherPair: Pair<Int, Int>): Boolean {
val xDIff = this.first - otherPair.first
val yDIff = this.second - otherPair.second
val intRange = -1..1
return xDIff in intRange && yDIff in intRange
}
fun String.toStep() = Step(
Direction.fromString(substringBefore(" ").uppercase()), substringAfter(" ").toInt()
)
| 0 | Kotlin | 0 | 0 | 9876a52ef9288353d64685f294a899a58b2de9b5 | 3,223 | aoc2022 | Apache License 2.0 |
src/main/kotlin/days/Day3.kt | sicruse | 434,002,213 | false | {"Kotlin": 29921} | package days
class Day3 : Day(3) {
class Diagnostics(data: List<String>) {
private val signals: List<Int> by lazy { data.map { Integer.parseInt(it, 2); } }
private val numberOfBits = data.first().length
// sum the 1 bits across each column of data and if greater than half of the total number of rows then the answer is 1 otherwise 0
// assume that there is never an even split of bits in the rows
enum class Diagnostic {
gamma {
override fun process(signalset: List<Int>, bitindex: Int): Int {
val threshold = signalset.count() / 2
return (bitindex downTo 1).fold(0) { acc, index ->
val countofones = signalset.sumOf { it shr index - 1 and 1 }
val bit = if (countofones > threshold) 1 else 0
acc or (bit shl (index - 1))
}
}
},
oxygen {
override fun process(signalset: List<Int>, bitindex: Int): Int {
val signals = mostCommon(signalset, bitindex)
return super.process(signals, bitindex)
}
},
co2 {
override fun process(signalset: List<Int>, bitindex: Int): Int {
val signals = leastCommon(signalset, bitindex)
return super.process(signals, bitindex)
}
};
fun mostCommon(signalset: List<Int>, bitindex: Int): List<Int> {
val countofones = signalset.sumOf { it shr bitindex - 1 and 1 }
val countofzeros = signalset.count() - countofones
if (countofones >= countofzeros)
return signalset.filter { it shr bitindex - 1 and 1 == 1 }
else
return signalset.filter { it shr bitindex - 1 and 1 == 0 }
}
fun leastCommon(signalset: List<Int>, bitindex: Int): List<Int> {
val countofones = signalset.sumOf { it shr bitindex - 1 and 1 }
val countofzeros = signalset.count() - countofones
if (countofzeros <= countofones)
return signalset.filter { it shr bitindex - 1 and 1 == 0 }
else
return signalset.filter { it shr bitindex - 1 and 1 == 1 }
}
open fun process(signalset: List<Int>, bitindex: Int): Int {
if (signalset.count() == 1) return signalset.first()
else return process(signalset, bitindex - 1)
}
}
private fun epsilonFromGamma(gamma: Int): Int {
val bitmask = -1 ushr Int.SIZE_BITS - numberOfBits
return gamma.inv() and bitmask
}
val powerconsumption by lazy {
val gamma = Diagnostic.gamma.process(signals, numberOfBits)
val epsilon = epsilonFromGamma(gamma)
gamma * epsilon
}
val lifesupport by lazy {
val oxygen = Diagnostic.oxygen.process(signals, numberOfBits)
val co2 = Diagnostic.co2.process(signals, numberOfBits)
oxygen * co2
}
}
override fun partOne(): Any {
val diagnostics = Diagnostics(inputList)
return diagnostics.powerconsumption
}
override fun partTwo(): Any {
val diagnostics = Diagnostics(inputList)
return diagnostics.lifesupport
}
}
| 0 | Kotlin | 0 | 0 | 172babe6ee67a86a7893f8c9c381c5ce8e61908e | 3,506 | aoc-kotlin-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/biz/koziolek/adventofcode/year2021/day24/day24.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2021.day24
import java.util.*
fun main() {
val validSerialNumbers = generateValidSerialNumbers()
println("Max valid serial number: ${validSerialNumbers.maxOf { it }}")
println("Min valid serial number: ${validSerialNumbers.minOf { it }}")
}
sealed interface VarOrNum
data class Var(val name: String) : VarOrNum
data class Num(val number: Int) : VarOrNum
sealed interface AluInstruction
data class Inp(val a: Var) : AluInstruction
data class Add(val a: Var, val b: VarOrNum) : AluInstruction
data class Mul(val a: Var, val b: VarOrNum) : AluInstruction
data class Div(val a: Var, val b: VarOrNum) : AluInstruction
data class Mod(val a: Var, val b: VarOrNum) : AluInstruction
data class Eql(val a: Var, val b: VarOrNum) : AluInstruction
data class State(val state: Map<String, Int> = emptyMap()) {
operator fun get(variable: Var): Int =
state.getOrDefault(variable.name, 0)
operator fun get(varOrNum: VarOrNum): Int =
when (varOrNum) {
is Num -> varOrNum.number
is Var -> get(varOrNum)
}
fun set(variable: Var, value: Int): State =
copy(state = state + (variable.name to value))
fun update(variable: Var, updater: (Int) -> Int): State =
set(variable, updater(get(variable)))
}
fun parseAluInstructions(lines: List<String>): List<AluInstruction> =
lines.map { it.split(' ') }
.map {
when (it[0]) {
"inp" -> Inp(Var(it[1]))
"add" -> Add(Var(it[1]), readVarOrNum(it[2]))
"mul" -> Mul(Var(it[1]), readVarOrNum(it[2]))
"div" -> Div(Var(it[1]), readVarOrNum(it[2]))
"mod" -> Mod(Var(it[1]), readVarOrNum(it[2]))
"eql" -> Eql(Var(it[1]), readVarOrNum(it[2]))
else -> throw IllegalArgumentException("Unknown instruction: $it")
}
}
private fun readVarOrNum(string: String): VarOrNum =
when {
string.all { it.isLetter() } -> Var(string)
else -> Num(string.toInt())
}
fun evaluate(instructions: List<AluInstruction>, input: Queue<Int>, state: State = State()): State =
instructions.fold(state) { currentState, instruction -> evaluate(instruction, input, currentState) }
fun evaluate(instruction: AluInstruction, input: Queue<Int>, state: State): State =
when (instruction) {
is Inp -> state.set(instruction.a, input.poll())
is Add -> state.update(instruction.a) { it + state[instruction.b] }
is Mul -> state.update(instruction.a) { it * state[instruction.b] }
is Div -> state.update(instruction.a) { it / state[instruction.b] }
is Mod -> state.update(instruction.a) { it % state[instruction.b] }
is Eql -> state.update(instruction.a) { if (it == state[instruction.b]) 1 else 0 }
}
fun generateCode(instructions: List<AluInstruction>): String =
instructions.joinToString(separator = "\n") {
generateCode(it)
}
fun generateCode(instruction: AluInstruction): String =
when (instruction) {
is Inp -> "${instruction.a.name} = input.poll()"
is Add -> "${instruction.a.name} += ${asCode(instruction.b)}"
is Mul -> "${instruction.a.name} *= ${asCode(instruction.b)}"
is Div -> "${instruction.a.name} /= ${asCode(instruction.b)}"
is Mod -> "${instruction.a.name} %= ${asCode(instruction.b)}"
is Eql -> "${instruction.a.name} = if (${instruction.a.name} == ${asCode(instruction.b)}) 1 else 0"
}
fun asCode(varOrNum: VarOrNum): String =
when (varOrNum) {
is Num -> varOrNum.number.toString()
is Var -> varOrNum.name
}
fun generateValidSerialNumbers() =
sequence {
val w1 = 9
for (w2 in 1..9) {
for (w3 in 1..9) {
val w4 = w3 + 7
for (w5 in 1..9) {
val w6 = w5 - 4
val w7 = 1
for (w8 in 1..9) {
for (w9 in 1..9) {
val w10 = w9 + 1
val w11 = w8 + 6
val w12 = w7 + 8
val w13 = w2 - 2
val w14 = w1 - 8
val digits = listOf(w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14)
if (digits.all { it in 1..9 }) {
yield(digits.joinToString(separator = "").toLong())
}
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 4,625 | advent-of-code | MIT License |
src/Day02.kt | slawa4s | 573,050,411 | false | {"Kotlin": 20679} | enum class ResultOfGame(val score: Int) {
DEFEAT(0),
DRAW(3),
WIN(6)
}
val mapOfScores = hashMapOf(
'X' to 1,
'Y' to 2,
'Z' to 3
)
val mapOfPlayersDraw = hashMapOf(
'X' to 'A',
'Y' to 'B',
'Z' to 'C'
)
val mapOfPlayersLose = hashMapOf(
'X' to 'B',
'Y' to 'C',
'Z' to 'A'
)
val mapOfPlayersWin = hashMapOf(
'X' to 'C',
'Y' to 'A',
'Z' to 'B'
)
val mapOfGameEnding = hashMapOf(
'X' to ResultOfGame.DEFEAT,
'Y' to ResultOfGame.DRAW,
'Z' to ResultOfGame.WIN
)
fun main() {
fun getRoundResult(first: Char, second: Char): ResultOfGame =
when (first) {
mapOfPlayersDraw[second] -> ResultOfGame.DRAW
mapOfPlayersWin[second] -> ResultOfGame.WIN
else -> ResultOfGame.DEFEAT
}
fun getPredictByResult(first: Char, gameResult: ResultOfGame): Int =
when(gameResult) {
ResultOfGame.DEFEAT -> mapOfScores[mapOfPlayersLose.entries.associate{ (k, v)-> v to k }[first]!!]!!
ResultOfGame.DRAW -> mapOfScores[mapOfPlayersDraw.entries.associate{ (k, v)-> v to k }[first]!!]!!
else -> mapOfScores[mapOfPlayersWin.entries.associate{ (k, v)-> v to k }[first]!!]!!
}
fun getRoundScorePart1(first: Char, second: Char): Int = mapOfScores[second]!! + getRoundResult(first, second).score
fun getRoundScorePart2(first: Char, second: Char): Int = mapOfGameEnding[second]!!.score +
getPredictByResult(first, mapOfGameEnding[second]!!)
fun part1(input: List<String>): Int = input.sumOf { getRoundScorePart1(it[0], it[2]) }
fun part2(input: List<String>): Int = input.sumOf { getRoundScorePart2(it[0], it[2]) }
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | cd8bbbb3a710dc542c2832959a6a03a0d2516866 | 1,838 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2023/Day01.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.InputUtils
fun main() {
val testInput = """1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet""".split("\n")
val test2Input = """
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""".trimIndent().split("\n")
val numbers = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
val allNumbers = numbers + numbers.entries.associate { it.value to it.value }
fun extractNum(s: String): Long {
return (buildString {
append(s.first { it.isDigit() })
append(s.last { it.isDigit() })
}).toLong()
}
fun part1(input: List<String>): Long {
return input.sumOf { extractNum(it) }
}
fun extractWordNums(s: String): Long {
val first = allNumbers
.map { (long, short) -> s.indexOf(long) to short }
.filter { it.first >= 0 }.minByOrNull { it.first }!!.second
val last = allNumbers.map { (long, short) -> s.lastIndexOf(long) to short }
.filter { it.first >= 0 }.maxByOrNull { it.first }!!.second
return (first + "" + last).toLong()
}
fun part2(input: List<String>): Long {
return input.map {
extractWordNums(it).also { println(it) }
}.sum()
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 142L)
val test2 = part2(test2Input)
println(test2)
check(test2 == 281L)
val puzzleInput = InputUtils.downloadAndGetLines(2023, 1)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 1,856 | aoc-2022-kotlin | Apache License 2.0 |
src/2021-Day07.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | import java.lang.Integer.min
import kotlin.math.absoluteValue
import kotlin.math.roundToInt
fun main() {
fun part1(input: List<String>): Int {
val positions = input[0].trim().split(',').map { it.toInt() }.sorted()
val median = positions[positions.size / 2]
return positions.sumOf { (it - median).absoluteValue }
}
fun part2(input: List<String>): Int {
val positions = input[0].trim().split(',').map { it.toInt() }
val mean = (positions.sum().toFloat() / positions.size)
println("Mean: $mean, mean.roundToInt():${mean.roundToInt()}, mean.toInt():${mean.toInt()}")
val meanInt = mean.toInt()
val low = positions.sumOf {
val diff = (it - meanInt).absoluteValue
diff*(diff+1)/2
}
val high = positions.sumOf {
val diff = (it - (meanInt + 1)).absoluteValue
diff*(diff+1)/2
}
return min(low, high)
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"16,1,2,0,4,2,7,1,2,14\n"
)
check(part1(testInput) == 37)
val pt2 = part2(testInput)
println(pt2)
check(pt2 == 168)
val input = readInput("2021-day7")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 1,298 | 2022-aoc-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortItems.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.Stack
/**
* 1203. Sort Items by Groups Respecting Dependencies
* @see <a href="https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies">Source</a>
*/
fun interface SortItems {
operator fun invoke(n: Int, m: Int, group: IntArray, beforeItems: List<List<Int>>): IntArray
}
class TopologicalSorting : SortItems {
override operator fun invoke(n: Int, m: Int, group: IntArray, beforeItems: List<List<Int>>): IntArray {
// If an item belongs to zero group, assign it a unique group id.
var groupId = m
for (i in 0 until n) {
if (group[i] == -1) {
group[i] = groupId
groupId++
}
}
// Sort all item regardless of group dependencies.
val itemGraph: MutableMap<Int, MutableList<Int>> = HashMap()
val itemIndegree = IntArray(n)
for (i in 0 until n) {
itemGraph[i] = ArrayList()
}
// Sort all groups regardless of item dependencies.
val groupGraph: MutableMap<Int, MutableList<Int>> = HashMap()
val groupIndegree = IntArray(groupId)
for (i in 0 until groupId) {
groupGraph[i] = ArrayList()
}
for (curr in 0 until n) {
for (prev in beforeItems[curr]) {
// Each (prev -> curr) represents an edge in the item graph.
itemGraph[prev]?.add(curr)
itemIndegree[curr]++
// If they belong to different groups, add an edge in the group graph.
if (group[curr] != group[prev]) {
groupGraph[group[prev]]!!.add(group[curr])
groupIndegree[group[curr]]++
}
}
}
// Topological sort nodes in the graph, return an empty array if a cycle exists.
val itemOrder = topologicalSort(itemGraph, itemIndegree)
val groupOrder = topologicalSort(groupGraph, groupIndegree)
if (itemOrder.isEmpty() || groupOrder.isEmpty()) {
return IntArray(0)
}
// Items are sorted regardless of groups, we need to differentiate them by the groups they belong to.
val orderedGroups: MutableMap<Int, MutableList<Int>> = HashMap()
for (item in itemOrder) {
orderedGroups.computeIfAbsent(
group[item],
) { ArrayList() }.add(item)
}
// Concatenate sorted items in all sorted groups.
// [group 1, group 2, ... ] -> [(item 1, item 2, ...), (item 1, item 2, ...), ...]
val answerList: MutableList<Int> = ArrayList()
for (groupIndex in groupOrder) {
answerList.addAll(orderedGroups.getOrDefault(groupIndex, ArrayList()))
}
return answerList.stream().mapToInt { obj: Int -> obj }.toArray()
}
private fun topologicalSort(graph: Map<Int, List<Int>>, indegree: IntArray): List<Int> {
val visited: MutableList<Int> = ArrayList()
val stack: Stack<Int> = Stack()
for (key in graph.keys) {
if (indegree[key] == 0) {
stack.add(key)
}
}
while (stack.isNotEmpty()) {
val curr: Int = stack.pop()
visited.add(curr)
for (prev in graph[curr]!!) {
indegree[prev]--
if (indegree[prev] == 0) {
stack.add(prev)
}
}
}
return if (visited.size == graph.size) visited else ArrayList()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,175 | kotlab | Apache License 2.0 |
mantono-kotlin/src/main/kotlin/com/mantono/aoc/day06/Orbits.kt | LinAGKar | 433,981,631 | true | {"Python": 390591, "C#": 189476, "Rust": 166608, "C++": 127941, "F#": 68551, "Haskell": 60413, "Nim": 46562, "Kotlin": 29504, "REXX": 13854, "OCaml": 12448, "Go": 11995, "C": 9751, "Swift": 8043, "JavaScript": 1750, "CMake": 1107, "PowerShell": 866, "AppleScript": 493, "Shell": 255} | package com.mantono.aoc.day06
import com.mantono.aoc.AoC
import com.mantono.aoc.Part
@AoC(6, Part.A)
fun calculateOrbits(input: String): Int {
val orbits: Map<String, List<String>> = input.split("\n").asSequence()
.map { it.trim().split(")") }
.groupBy({ it.first() }, { it.last() })
return computeRecursiveOrbits(orbits)
}
@AoC(6, Part.B)
fun orbitalTransfers(input: String): Int {
val orbits: Map<String, List<String>> = input.split("\n").asSequence()
.map { it.trim().split(")") }
.groupBy({ it.first() }, { it.last() })
val pathToSanta: List<String> = findPathToObject(orbits, "SAN")
val pathToMe: List<String> = findPathToObject(orbits, "YOU")
val commonPath: Set<String> = pathToSanta.toSet().intersect(pathToMe.toSet())
return (pathToMe.size + pathToSanta.size) - (commonPath.size * 2) - 2
}
fun findPathToObject(
orbits: Map<String, List<String>>,
destination: String,
path: List<String> = emptyList(),
current: String = "COM"
): List<String> {
val updatedPath: List<String> = path + current
if(destination == current) {
return updatedPath
}
val options: List<String> = orbits.getOrDefault(current, emptyList())
if(options.isEmpty()) {
return emptyList()
}
return options.asSequence()
.map { findPathToObject(orbits, destination, updatedPath, it) }
.firstOrNull { it.contains(destination) } ?: emptyList()
}
private fun computeRecursiveOrbits(
orbits: Map<String, List<String>>,
planet: String = "COM",
depth: Int = 0
): Int {
val orbitalChildren: List<String> = orbits.getOrDefault(planet, emptyList())
return if(orbitalChildren.isEmpty()) {
depth
} else {
orbitalChildren.asSequence()
.map { computeRecursiveOrbits(orbits, it, depth + 1) }
.sum() + depth
}
} | 0 | Python | 0 | 0 | 4f51eed64ba8fc5254dfa6740c8461f2de1c18a0 | 1,879 | advent_of_code_2019 | Apache License 2.0 |
src/Day02.kt | brste | 577,510,164 | false | {"Kotlin": 2640} | fun main() {
val pointsByShape = mapOf("X" to 1, "Y" to 2, "Z" to 3)
val leftBeatsRight = mapOf("Y" to "A", "X" to "C", "Z" to "B")
val draw = mapOf("X" to "A", "Y" to "B", "Z" to "C")
fun String.beats(other: String): Boolean = other == leftBeatsRight[this]
fun String.draw(other: String): Boolean = other == draw[this]
fun part1(input: List<String>): Int {
return input
.map { it.split(" ") }
.sumOf { (other, me) ->
when {
me.beats(other) -> 6 + pointsByShape[me]!!
me.draw(other) -> 3 + pointsByShape[me]!!
else -> 0 + pointsByShape[me]!!
}
}
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | e8d6604575021fef95ad3d31cc8d61e929ac9efa | 1,027 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/co/csadev/advent2021/Day15.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2021, Day 15
* Problem Description: http://adventofcode.com/2021/day/15
*/
package co.csadev.advent2021
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Point2D
import co.csadev.adventOfCode.Resources.resourceAsList
import java.util.PriorityQueue
class Day15(override val input: List<String> = resourceAsList("21day15.txt")) :
BaseDay<List<String>, Int, Int> {
private val cave: Array<IntArray> = parseInput(input)
override fun solvePart1(): Int =
cave.traverse()
override fun solvePart2(): Int =
cave.traverse(
Point2D((cave.first().size * 5) - 1, (cave.size * 5) - 1)
)
private fun Array<IntArray>.traverse(
destination: Point2D = Point2D(first().lastIndex, lastIndex)
): Int {
val toBeEvaluated = PriorityQueue<Traversal>().apply { add(Traversal(Point2D(0, 0), 0)) }
val visited = mutableSetOf<Point2D>()
while (toBeEvaluated.isNotEmpty()) {
val thisPlace = toBeEvaluated.poll()
if (thisPlace.point == destination) {
return thisPlace.totalRisk
}
if (thisPlace.point !in visited) {
visited.add(thisPlace.point)
thisPlace.point
.adjacent
.filter { it.x in (0..destination.x) && it.y in (0..destination.y) }
.forEach { toBeEvaluated.offer(Traversal(it, thisPlace.totalRisk + this[it])) }
}
}
error("No path to destination (which is really weird, right?)")
}
private operator fun Array<IntArray>.get(point: Point2D): Int {
val dx = point.x / this.first().size
val dy = point.y / this.size
val originalRisk = this[point.y % this.size][point.x % this.first().size]
val newRisk = (originalRisk + dx + dy)
return newRisk.takeIf { it < 10 } ?: (newRisk - 9)
}
private fun parseInput(input: List<String>): Array<IntArray> =
input.map { row ->
row.map { risk ->
risk.toString().toInt()
}.toIntArray()
}.toTypedArray()
private class Traversal(val point: Point2D, val totalRisk: Int) : Comparable<Traversal> {
override fun compareTo(other: Traversal): Int =
this.totalRisk - other.totalRisk
}
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 2,396 | advent-of-kotlin | Apache License 2.0 |
src/Day04.kt | saphcarter | 573,329,337 | false | null | fun main() {
fun part1(input: List<String>): Int {
var counter = 0
input.forEach {
val (firstFrom, firstTo, secondFrom, secondTo) = it.split('-', ',').map(String::toInt)
if((firstFrom <= secondFrom && firstTo >= secondTo) || (firstFrom >= secondFrom && firstTo <= secondTo)){
counter++
}
}
return counter
}
fun part2(input: List<String>): Long {
return input.sumOf {
val (firstFrom, firstTo, secondFrom, secondTo) = it.split('-', ',').map(String::toInt)
val pair = firstFrom..firstTo to secondFrom..secondTo
if (pair.first.toSet().intersect(pair.second.toSet()).isNotEmpty()) 1L else 0L
}
}
// test if implementation meets criteria from the description, like:
val testInput = listOf("2-4,6-8","2-3,4-5","5-7,7-9", "2-8,3-7", "6-6,4-6", "2-6,4-8")
val test1 = part1(testInput)
check(test1 == 2)
println("Test 1 passed")
/*val test2 = part2(testInput)
check(test2 == 4)
println("Test 2 passed")*/
val input = readInput("Input04")
//println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2037106e961dc58e75df2fbf6c31af6e0f44777f | 1,177 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | bunjix | 573,915,819 | false | {"Kotlin": 9977} | fun main() {
fun part1(input: List<String>, newCrane: Boolean): String {
val (stacksInput, craneStepsInput) = splitInput(input)
val stackCount = "(\\d*)\\s\$".toRegex().find(stacksInput.last())?.groupValues.orEmpty().last().toInt()
val stacks = mutableListOf<MutableList<Char>>()
repeat(stackCount) {
stacks.add(mutableListOf())
}
stacksInput.dropLast(1)
.map { line ->
line.chunked(4) { it.toString().replace("[", "").replace("]", "").trim() }
.forEachIndexed { index, s ->
if (s.isNotEmpty()) {
val stack = stacks[index]
stack.add(0, s.first())
}
}
}
val craneSteps = craneStepsInput.mapNotNull { it.toCraneSteps() }
craneSteps.forEach { step ->
if (newCrane) {
val move = stacks[step.from].takeLast(step.moves)
stacks[step.from] = stacks[step.from].dropLast(step.moves).toMutableList()
stacks[step.to].addAll(move)
} else {
repeat(step.moves) {
stacks[step.to].add(stacks[step.from].removeLast())
}
}
}
return stacks.mapNotNull { it.lastOrNull() }.joinToString(separator = "")
}
val input = readInput("Day05_input")
println(part1(input, newCrane = false))
println(part1(input, newCrane = true))
}
fun splitInput(input: List<String>): Pair<List<String>, List<String>> {
val lineSeparator = input.indexOfFirst { it.isEmpty() }
return input.subList(0, lineSeparator) to input.subList(lineSeparator, input.size)
}
fun String.toCraneSteps(): CraneSteps? {
return "\\w+\\s(\\d*)\\s\\w+\\s(\\d*)\\s\\w+\\s(\\d*)".toRegex().find(this)?.groupValues?.drop(1)?.takeIf { it.size == 3 }?.map { it.toInt() }
?.let {
CraneSteps(it.first(), it[1]-1, it.last()-1)
}
}
data class CraneSteps(val moves: Int, val from: Int, val to: Int) | 0 | Kotlin | 0 | 0 | ee2a344f6c0bb2563cdb828485e9a56f2ff08fcc | 2,098 | aoc-2022-kotlin | Apache License 2.0 |
2021/src/day10/Day10.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day10
import readInput
fun part1(lines: List<String>) : Int {
val chars = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>')
val points = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137)
var total = 0
for (line in lines) {
val stack = mutableListOf<Char>()
for (c in line) {
if (chars.keys.contains(c)) { // opening char
stack.add(c)
} else if (chars.values.contains(c)) { // closing char
if (c != chars[stack[stack.lastIndex]]) { // corrupted line
total += points[c]!!
break
} else {
stack.removeAt(stack.lastIndex)
}
}
}
}
return total
}
fun part2(lines: List<String>) : Long {
val chars = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>')
val points = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4)
val scores = mutableListOf<Long>()
for (line in lines) {
val stack = mutableListOf<Char>()
for (c in line) {
if (chars.keys.contains(c)) { // opening char
stack.add(c)
} else if (chars.values.contains(c)) { // closing char
if (c != chars[stack[stack.lastIndex]]) { // corrupted line
stack.clear()
break
} else {
stack.removeAt(stack.lastIndex)
}
}
}
var lineScore = 0L
while (!stack.isEmpty()) { // incomplete line
lineScore = lineScore * 5 + points[chars[stack[stack.lastIndex]]]!!
stack.removeAt(stack.lastIndex)
}
if (lineScore > 0) scores.add(lineScore)
}
scores.sort()
return scores[scores.size / 2]
}
fun main() {
val testInput = readInput("day10/test")
println("part1(testInput) => " + part1(testInput))
println("part2(testInput) => " + part2(testInput))
val input = readInput("day10/input")
println("part1(input) => " + part1(input))
println("part1(input) => " + part2(input))
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 2,119 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day7.kt | MisterJack49 | 729,926,959 | false | {"Kotlin": 31964} | package days
import days.Day7.CardAlternate.As
import days.Day7.CardAlternate.Joker
import days.Day7.HandType.FiveOfKind
import days.Day7.HandType.FourOfKind
import days.Day7.HandType.FullHouse
import days.Day7.HandType.None
import days.Day7.HandType.OnePair
import days.Day7.HandType.ThreeOfKind
import days.Day7.HandType.TwoPair
class Day7 : Day(7) {
override fun partOne() =
inputList.map { line ->
Hand(
line.split(" ")[0].map { CardRegular.fromString(it) },
line.split(" ")[1].toInt()
)
}.sorted()
.foldIndexed(0) { index, acc, hand -> acc + hand.bid * (index + 1) }
override fun partTwo() =
inputList.map { line ->
Hand(
line.split(" ")[0].map { CardAlternate.fromString(it) },
line.split(" ")[1].toInt()
)
}.sorted()
.foldIndexed(0) { index, acc, hand -> acc + hand.bid * (index + 1) }
data class Hand(val hand: List<Card>, val bid: Int, var kind: HandType = None) : Comparable<Hand> {
init {
require(hand.size == 5)
kind = hand.groupBy { it }
.let { if (hand.first() is CardAlternate) it.swapJokers() else it }
.let { groups ->
if (groups.size == 1) return@let FiveOfKind
if (groups.values.any { it.size == 4 }) return@let FourOfKind
if (groups.size == 2 && groups.values.any { it.size == 3 }) return@let FullHouse
if (groups.values.any { it.size == 3 }) return@let ThreeOfKind
if (groups.values.count { it.size == 2 } == 2) return@let TwoPair
if (groups.values.any { it.size == 2 }) return@let OnePair
HandType.HighCard
}
}
private fun Map<Card, List<Card>>.swapJokers(): Map<Card, List<Card>> =
(minus(Joker).values.maxByOrNull { it.size }?.firstOrNull() ?: As)
.let { strongCard ->
values.flatten()
.map { if (it == Joker) strongCard else it }
.groupBy { it }
}
override operator fun compareTo(other: Hand): Int {
if (kind == other.kind) return hand.compare(other.hand)
return if (kind > other.kind) 1 else -1
}
private fun List<Card>.compare(other: List<Card>) =
zip(other).firstOrNull { cards -> cards.compare() != 0 }?.compare() ?: 0
private fun Pair<Card, Card>.compare() =
if (first == second) 0
else if (first.value < second.value) 1
else -1
}
interface Card {
val value: Int
}
enum class CardRegular(val char: Char) : Card {
As('A'),
King('K'),
Queen('Q'),
Jack('J'),
Ten('T'),
Nine('9'),
Eight('8'),
Seven('7'),
Six('6'),
Five('5'),
Four('4'),
Three('3'),
Two('2');
override val value: Int
get() = ordinal
companion object {
fun fromString(c: Char) = CardRegular.values().first { it.char == c }
}
}
enum class CardAlternate(val char: Char) : Card {
As('A'),
King('K'),
Queen('Q'),
Ten('T'),
Nine('9'),
Eight('8'),
Seven('7'),
Six('6'),
Five('5'),
Four('4'),
Three('3'),
Two('2'),
Joker('J');
override val value: Int
get() = ordinal
companion object {
fun fromString(c: Char) = CardAlternate.values().first { it.char == c }
}
}
enum class HandType {
None,
HighCard,
OnePair,
TwoPair,
ThreeOfKind,
FullHouse,
FourOfKind,
FiveOfKind;
}
}
| 0 | Kotlin | 0 | 0 | 807a6b2d3ec487232c58c7e5904138fc4f45f808 | 3,922 | AoC-2023 | Creative Commons Zero v1.0 Universal |
AdventOfCodeDay21/src/nativeMain/kotlin/Day21.kt | bdlepla | 451,523,596 | false | {"Kotlin": 153773} | class Day21(lines: List<String>) {
val food = lines.associate {
val (ingredients, allergens) = parseLine(it)
ingredients to allergens
}
val allAllergies = food.values.flatten().toSet()
val allIngredients = food.keys.flatten().toSet()
fun solvePart2(): String {
// for each allergy, I want a list of bad ingredients associated with that allergy
val allergyToBadIngredients = mutableMapOf<String, MutableSet<String>>()
allAllergies.forEach { allergy ->
allergyToBadIngredients[allergy] = food
.filter { allergy in it.value }
.map { it.key }
.reduce {carry, s -> s intersect carry }.toMutableSet()
}
println(allergyToBadIngredients)
val resultMap = mutableMapOf<String, String>()
while (allergyToBadIngredients.values.any{it.isNotEmpty()}) {
val wow = allergyToBadIngredients.filter {it.value.count() == 1}
val key = wow.keys.first()
val value = allergyToBadIngredients[key]!!.first()
resultMap[key]=value
allergyToBadIngredients.values.forEach { setOfIngredients ->
setOfIngredients.remove(value)
}
}
val sortedKeys = resultMap.keys.sorted()
return sortedKeys.map{resultMap[it]}.joinToString(",")
}
fun solvePart1(): Long {
val badIngredients = allAllergies.flatMap { allergy ->
food
.filter { allergy in it.value }
.map { it.key }
.reduce {carry, s -> s intersect carry }
}.toSet()
println("badIngredients = $badIngredients")
val goodIngredients = allIngredients subtract badIngredients
println("goodIngredients = $goodIngredients")
val result = food.keys.sumOf { recipe ->
recipe.count{ingredient -> ingredient in goodIngredients}
}
return result.toLong()
}
companion object {
fun parseLine(line: String):Pair<Set<String>, Set<String>> {
// x y z a b c (contains n, m, o)
val ingredientList = line.substringBefore(" (").split(' ').toSet()
val allergenList = line.substringAfter("(contains ")
.substringBefore(")").split(", ").toSet()
return Pair(ingredientList, allergenList)
}
}
} | 0 | Kotlin | 0 | 0 | 043d0cfe3971c83921a489ded3bd45048f02ce83 | 2,395 | AdventOfCode2020 | The Unlicense |
src/year2016/day03/Day03.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2016.day03
import readInput
fun main() {
val input = readInput("2016", "Day03")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.parseFromRows().countValidTriangles()
private fun part2(input: List<String>) = input.parseFromCols().countValidTriangles()
private fun List<String>.parseFromRows(): List<Triple<Int, Int, Int>> = map { line ->
line.split(" ")
.mapNotNull { part -> part.trim().takeIf { it.isNotBlank() }?.toInt() }
.let { (a, b, c) -> Triple(a, b, c) }
}
private fun List<String>.parseFromCols(): List<Triple<Int, Int, Int>> = parseFromRows()
.let { list -> list.map { it.first } + list.map { it.second } + list.map { it.third } }
.chunked(3)
.map { (a, b, c) -> Triple(a, b, c) }
private fun List<Triple<Int, Int, Int>>.countValidTriangles() = count {
val (a, b, c) = it.toList().sorted()
a + b > c
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 928 | AdventOfCode | Apache License 2.0 |
src/Day04.kt | Fenfax | 573,898,130 | false | {"Kotlin": 30582} | fun main() {
val parSplit = ','
val rangeSplit = '-'
fun getRangeList(input: List<String>) = input
.map { fullString -> fullString.split(parSplit).map { it.split(rangeSplit) } }
.map { pairs -> pairs.map { it[0].toInt()..it[1].toInt() } }
fun part1(input: List<String>): Int {
val splitInput = getRangeList(input)
.filter { (it[0].first in it[1] && it[0].last in it[1]) || (it[1].first in it[0] && it[1].last in it[0]) }
return splitInput.size
}
fun part2(input: List<String>): Int {
val splitInput = getRangeList(input)
.filter { it[0].first in it[1] || it[0].last in it[1] || it[1].first in it[0] || it[1].last in it[0] }
return splitInput.size
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 28af8fc212c802c35264021ff25005c704c45699 | 845 | AdventOfCode2022 | Apache License 2.0 |
src/Day09.kt | ThijsBoehme | 572,628,902 | false | {"Kotlin": 16547} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
fun main() {
data class Coordinate(var x: Double, var y: Double) {
fun move(direction: String) {
when (direction) {
"D" -> y -= 1
"U" -> y += 1
"L" -> x -= 1
"R" -> x += 1
else -> error("invalid direction")
}
}
}
fun moveKnots(first: Coordinate, second: Coordinate) {
if (max(abs(first.x - second.x), abs(first.y - second.y)) > 1) {
second.x += sign(first.x - second.x)
second.y += sign(first.y - second.y)
}
}
fun part1(input: List<String>): Int {
val head = Coordinate(0.0, 0.0)
val tail = Coordinate(0.0, 0.0)
val visitedCoordinates = mutableSetOf(tail.copy())
input.forEach { line ->
val (direction, amountString) = line.split(" ")
repeat(amountString.toInt()) {
head.move(direction)
moveKnots(head, tail)
visitedCoordinates.add(tail.copy())
}
}
return visitedCoordinates.size
}
fun part2(input: List<String>): Int {
val head = Coordinate(0.0, 0.0)
val knot1 = Coordinate(0.0, 0.0)
val knot2 = Coordinate(0.0, 0.0)
val knot3 = Coordinate(0.0, 0.0)
val knot4 = Coordinate(0.0, 0.0)
val knot5 = Coordinate(0.0, 0.0)
val knot6 = Coordinate(0.0, 0.0)
val knot7 = Coordinate(0.0, 0.0)
val knot8 = Coordinate(0.0, 0.0)
val tail = Coordinate(0.0, 0.0)
val visitedCoordinates = mutableSetOf(tail.copy())
input.forEach { line ->
val (direction, amountString) = line.split(" ")
repeat(amountString.toInt()) {
head.move(direction)
moveKnots(head, knot1)
moveKnots(knot1, knot2)
moveKnots(knot2, knot3)
moveKnots(knot3, knot4)
moveKnots(knot4, knot5)
moveKnots(knot5, knot6)
moveKnots(knot6, knot7)
moveKnots(knot7, knot8)
moveKnots(knot8, tail)
visitedCoordinates.add(tail.copy())
}
}
return visitedCoordinates.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 707e96ec77972145fd050f5c6de352cb92c55937 | 2,700 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/day06/day06.kt | andrew-suprun | 725,670,189 | false | {"Kotlin": 18354, "Python": 17857, "Dart": 8224} | package day06
import java.io.File
import kotlin.math.ceil
import kotlin.math.sqrt
data class Race(val time: Long, val distance: Long)
fun main() {
run(::part1, ::solve)
run(::part1, ::altSolve)
run(::part2, ::solve)
run(::part2, ::altSolve)
}
fun run(part: (String) -> List<Long>, solution: (Race) -> Long) {
val lines = File("input.data").readLines()
val result = part(lines[0]).zip(part(lines[1]))
.map { (time, distance) -> Race(time = time, distance = distance) }
.map { solution(it) }
.reduce { acc, n -> acc * n }
println(result)
}
fun part1(line: String): List<Long> = line.split(Regex(" +")).drop(1).map { it.toLong() }
fun part2(line: String): List<Long> = listOf(line.split(Regex(" +")).drop(1).joinToString(separator = "").toLong())
fun solve(race: Race): Long {
var min = 0L
var max = race.time / 2
while (true) {
val mid = (min + max + 1) / 2
val prod = mid * (race.time - mid)
if (prod <= race.distance) {
min = mid
} else {
max = mid
}
if (max - min == 1L) {
return race.time + 1L - 2L * max
}
}
}
fun altSolve(race: Race): Long {
val discriminant = (race.time*race.time - 4*race.distance).toDouble()
val solution = (race.time - sqrt(discriminant)) / 2
val roundedUp = ceil(solution).toLong()
return race.time + 1L - 2L * roundedUp
}
// 2449062
// 33149631 | 0 | Kotlin | 0 | 0 | dd5f53e74e59ab0cab71ce7c53975695518cdbde | 1,458 | AoC-2023 | The Unlicense |
src/main/kotlin/com/hopkins/aoc/day3/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day3
import java.io.File
const val debug = true
const val part = 2
val digitRange = '0'.rangeTo('9')
/** Advent of Code 2023: Day 3 */
fun main() {
val inputFile = File("input/input3.txt")
val lines: List<String> = inputFile.readLines()
if (debug) {
// Print the lines
println("Lines:")
lines.take(3).forEachIndexed { y, line -> println(" y: $y, line: $line") }
}
// Find the parts
val parts: List<Part> =
lines.flatMapIndexed { y, line ->
line.mapIndexed { x, c ->
if (isPart(c)) {
Part(c, Position(x, y))
} else {
null
}
}
}.filterNotNull()
// Build a map of positions which are within proximity of a part
val partProximityMap: Map<Position, Part> =
parts.flatMap { part -> part.position.getSurrounding().map { it to part } }.toMap()
if (debug) {
// Print the parts (to debug)
println("Parts: ")
parts.take(3).forEach { println(" $it") }
// Print the part proximity (to debug)
println("Part Proximity: ")
parts.take(3).forEach { it.position.getSurrounding().forEach { println(" $it") } }
}
// Find all the part numbers
val numberPattern = Regex("[0-9]+")
val partNumbers: List<PartNumber> =
lines.flatMapIndexed { y, line ->
numberPattern.findAll(line).map { matchResult ->
PartNumber(matchResult.value, Position(matchResult.range.first, y))
}
}
// Part 1 only: Filter to only part numbers within proximity
val validParts: List<PartNumber> =
partNumbers.filter { partNumber ->
partProximityMap.keys.intersect(partNumber.getPositions()).isNotEmpty() }
// Part 2 only: Find pairs of parts that are both near the same gear
val partPairs: List<Pair<PartNumber, PartNumber>> =
parts.mapNotNull { part ->
val numberList: List<PartNumber> =
partNumbers.filter { partNumber -> isInProximity(part, partNumber) }
if (numberList.size == 2) {
Pair(numberList[0], numberList[1])
} else {
null
}
}
if (debug) {
if (part == 1) {
println("Valid Parts:");
validParts.take(3).forEach { println(" $it") }
} else {
println("Part Pairs:")
println("Pairs: $partPairs")
}
}
if (part == 1) {
val partNumberSum: Int = validParts.sumOf { it.toInt() }
println("Part Number Sum: $partNumberSum") // 535078
} else {
val gearRatioSum: Long = partPairs.map { it.first.toInt().toLong() * it.second.toInt().toLong() }.sum()
println("Gear ratio sum: $gearRatioSum")
}
}
fun isInProximity(part: Part, number: PartNumber): Boolean =
part.position.getSurrounding().intersect(number.getPositions()).isNotEmpty()
fun isPart(c: Char) =
if (part == 1) {
c != '.' && !digitRange.contains(c)
} else {
c == '*'
}
val surroundingIntRange = IntRange(-1, 1)
data class Position(val x: Int, val y: Int) {
override fun toString(): String = "[$x, $y]"
fun getSurrounding(): Set<Position> =
surroundingIntRange.flatMap { dx ->
surroundingIntRange.map { dy ->
Position(x + dx, y + dy)
}}
.toSet()
}
class Part(val symbol: Char, val position: Position) {
override fun toString(): String = "Part {c=$symbol pos=$position}"
}
class PartNumber(val symbol: String, val position: Position) {
fun toInt(): Int = symbol.toInt()
fun getPositions(): List<Position> =
IntRange(position.x, position.x + symbol.length - 1).map { tx -> Position(tx, position.y)}
override fun toString(): String = "PartNumber {$symbol pos=$position}"
} | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 3,929 | aoc2023 | MIT License |
src/Day04a.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} |
private fun String.toRanges() = indexOf(',').let { line ->
fun String.toRange() = indexOf('-').let { substring(0,it).toInt() .. substring(it+1).toInt() }
substring(0,line).toRange() to substring(line+1).toRange()
}
operator fun IntRange.contains(b: IntRange) = b.first>=first && b.last<=last
private fun part1(lines: List<String>): Int =
lines.count {
val(a, b) = it.toRanges()
a in b || b in a
}
private fun part2(lines: List<String>): Int =
lines.count {
val (a, b) = it.toRanges()
a.any { it in b }
}
fun main() {
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input)) // 588
println(part2(input)) // 911
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 794 | aoc2022 | Apache License 2.0 |
src/main/kotlin/year_2022/Day04.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2022
import utils.readInput
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {
val entry = it.split(",")
val first = entry.first()
val second = entry.last()
if (first.isContained(second) || second.isContained(first)) {
sum++
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach {
val entry = it.split(",")
val first = entry.first()
val second = entry.last()
if (first.overlaps(second)) {
sum++
}
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun String.isContained(value: String): Boolean {
val asdf = this.split("-")
val fdsa = value.split("-")
val thisInit = asdf.first().toInt()
val thisEnd = asdf.last().toInt()
val init = fdsa.first().toInt()
val end = fdsa.last().toInt()
return thisInit <= init && thisEnd >= end
}
fun String.overlaps(value: String): Boolean {
val a = this.split("-")
val b = value.split("-")
val aI = a.first().toInt()
val aE = a.last().toInt()
val bI = b.first().toInt()
val bE = b.last().toInt()
// sort by greater init
return if(aI <= bI){
bI <= aE
}else{
aI <= bE
}
} | 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 1,642 | advent-of-code | Apache License 2.0 |
src/Day23.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | fun Coordinates.neighborsIn(direction: Direction): List<Coordinates> =
when (direction) {
Direction.Up -> listOf(
copy(x = x - 1, y = y - 1),
copy(x = x, y = y - 1),
copy(x = x + 1, y = y - 1),
)
Direction.Down -> listOf(
copy(x = x - 1, y = y + 1),
copy(x = x, y = y + 1),
copy(x = x + 1, y = y + 1),
)
Direction.Left -> listOf(
copy(x = x - 1, y = y - 1),
copy(x = x - 1, y = y),
copy(x = x - 1, y = y + 1),
)
Direction.Right -> listOf(
copy(x = x + 1, y = y - 1),
copy(x = x + 1, y = y),
copy(x = x + 1, y = y + 1),
)
}
fun Coordinates.hasNeighborsIn(coordinates: List<Coordinates>, direction: Direction? = null): Boolean =
(direction?.let { neighborsIn(it) } ?: Direction.values().flatMap { neighborsIn(it) })
.any { it in coordinates }
fun Direction.next(): Direction =
when (this) {
Direction.Up -> Direction.Down
Direction.Down -> Direction.Left
Direction.Left -> Direction.Right
Direction.Right -> Direction.Up
}
fun main() {
fun List<String>.toElvesPositions(): List<Coordinates> =
flatMapIndexed { columnIndex, line ->
line.toCharArray().toList().mapIndexedNotNull { rowIndex, char ->
if (char == '#') Coordinates(x = rowIndex, y = columnIndex) else null
}
}
.toMutableList()
fun nextElvesPositions(elvesPositions: List<Coordinates>, direction: Direction): List<Pair<Coordinates, Int>> =
elvesPositions.mapIndexedNotNull { index, elf ->
if (elf.hasNeighborsIn(elvesPositions)) {
var currentDirection = direction
repeat(4) {
if (!elf.hasNeighborsIn(elvesPositions, currentDirection)) {
return@mapIndexedNotNull when (currentDirection) {
Direction.Up -> elf.copy(y = elf.y - 1)
Direction.Down -> elf.copy(y = elf.y + 1)
Direction.Left -> elf.copy(x = elf.x - 1)
Direction.Right -> elf.copy(x = elf.x + 1)
} to index
}
currentDirection = currentDirection.next()
}
}
null
}
fun part1(input: List<String>): Int {
var emptyGrounds = 0
var direction = Direction.Up
val elvesPositions = input.toElvesPositions().toMutableList()
repeat(10) {
val nextElvesPositionsAndIndexes = nextElvesPositions(elvesPositions, direction)
// Assign new positions
nextElvesPositionsAndIndexes.forEachIndexed { currentIndex, (nextCoordinates, index) ->
if (nextCoordinates !in nextElvesPositionsAndIndexes
.map { it.first }
.filterIndexed { index, _ -> index != currentIndex }
) {
elvesPositions[index] = nextCoordinates
}
}
// Change direction for next round
direction = direction.next()
}
(elvesPositions.minOf { it.y }..elvesPositions.maxOf { it.y }).forEach { y ->
(elvesPositions.minOf { it.x }..elvesPositions.maxOf { it.x }).forEach { x ->
if (Coordinates(x, y) !in elvesPositions) emptyGrounds++
}
}
return emptyGrounds
}
fun part2(input: List<String>): Int {
var rounds = 0
var direction = Direction.Up
val elvesPositions = input.toElvesPositions().toMutableList()
var nextElvesPositions: MutableList<Coordinates>
while (true) {
rounds++
val nextElvesPositionsAndIndexes = nextElvesPositions(elvesPositions, direction)
nextElvesPositions = nextElvesPositionsAndIndexes.map { it.first }.toMutableList()
if (nextElvesPositions.isEmpty()) {
break
}
// Assign new positions
nextElvesPositionsAndIndexes.forEachIndexed { currentIndex, (nextCoordinates, index) ->
if (nextCoordinates !in nextElvesPositions
.filterIndexed { index, _ -> index != currentIndex }
) {
elvesPositions[index] = nextCoordinates
}
}
// Change direction for next round
direction = direction.next()
}
return rounds
}
check(part1(readInput("Day23_test")) == 110)
check(part2(readInput("Day23_test")) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 4,839 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/graph/variation/ShortestPathNegEdge.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.Vertex
import graph.core.WeightedEdge
import graph.core.WeightedGraph
import graph.core.dijkstra
import util.min
// in the standard Dijkstra's algorithm, we assume all edges are positive
// what will happen if there is exactly one negative edge in the graph?
// you only need to report the length of such path
fun <V> WeightedGraph<V, Int>.shortestPathNegEdge(s: Vertex<V>, t: Vertex<V>): Int {
// given a negative weighted edge u -> v
// our strategy is:
// the shortest path from s to t either includes the negative edge or not
// if it doesn't, then remove it and find the shortest path from s to t
// if it does, then remove it, find the shortest path from s to u, add the
// negative edge u -> v, and finally find the shortest path from v to t
val newVertices = vertices
val newEdges = weightedEdges.filter { it.weight!! > 0 }
val newGraph = WeightedGraph(newVertices, newEdges)
val (u, v, _, d) = weightedEdges.first { it.weight!! < 0 }
val sMap = newGraph.dijkstra(s)
val notInclude = sMap.first[t]!!
val include = sMap.first[u]!! + d!! + newGraph.dijkstra(v).first[t]!!
return min(notInclude, include)
}
// given a graph with exactly one negative edge
// can you say if it has a negative cycle?
fun <V> WeightedGraph<V, Int>.hasNegCycles(): Boolean {
val (u, v, _, w) = weightedEdges.first { it.weight!! < 0 }
val newGraph = WeightedGraph(vertices, weightedEdges.filterNot { it.weight!! < 0 })
val (dist, _) = newGraph.dijkstra(v)
return dist[u]!! >= w!!
}
fun main(args: Array<String>) {
val vertices = (1..5).map { Vertex(it) }
val edges = setOf(
WeightedEdge(vertices[0], vertices[1], true, 3),
WeightedEdge(vertices[0], vertices[3], true, 1),
WeightedEdge(vertices[1], vertices[2], true, 1),
WeightedEdge(vertices[2], vertices[3], true, 2),
WeightedEdge(vertices[2], vertices[4], true, -300),
WeightedEdge(vertices[4], vertices[2], true, 1))
val graph = WeightedGraph(vertices, edges)
// println(graph.shortestPathNegEdge(vertices[0], vertices[4]))
println(graph.hasNegCycles())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,082 | AlgoKt | MIT License |
codeforces/round580/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round580
fun main() {
val n = readInt()
val a = List(n) { IntArray(n) }
a[0][0] = 1
propagate3(0, 1, 1, 2, a)
propagate3(1, 2, 1, 0, a)
for (i in a.indices) {
for (j in a.indices) {
if (i + j in setOf(0, 1, 2 * n - 2) || i == 1 && j == 2) continue
val ii = maxOf(i - 2, 0)
val jj = i + j - 2 - ii
propagate3(ii, jj, i, j, a)
}
}
val (b, c) = List(2) { t -> List(2 * n - 1) { val (x, y) = border(it, n); a[x][y] xor (t * it % 2) } }
val x = b.indices.first { x -> palindrome4(b, x) != palindrome4(c, x) }
val (x1, y1) = border(x, n)
val (x2, y2) = border(x + 3, n)
if (ask(x1, y1, x2, y2) != palindrome4(b, x)) {
for (i in a.indices) {
for (j in a.indices) {
a[i][j] = a[i][j] xor ((i + j) % 2)
}
}
}
println("!")
a.forEach { println(it.joinToString("")) }
}
private fun border(i: Int, n: Int) = if (i < n) Pair(0, i) else Pair(i - n + 1, n - 1)
private fun palindrome4(a: List<Int>, i: Int) = (a[i] == a[i + 3] && a[i + 1] == a[i + 2])
private fun propagate3(x1: Int, y1: Int, x2: Int, y2: Int, a: List<IntArray>) {
a[x2][y2] = a[x1][y1] xor if (ask(x1, y1, x2, y2)) 0 else 1
}
private fun ask(x1: Int, y1: Int, x2: Int, y2: Int): Boolean {
val output = setOf(listOf(x1, y1), listOf(x2, y2)).sortedBy { it.sum() }.flatten().map { it + 1 }
println("? ${output.joinToString(" ")}")
return readInt() == 1
}
private fun readInt() = readLine()!!.toInt()
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,423 | competitions | The Unlicense |
src/Day01.kt | Nplu5 | 572,211,950 | false | {"Kotlin": 15289} | fun main() {
fun mapToIndexedElves(input: List<String>) = input.fold(mutableListOf(Elf())) { elves, line ->
when {
line.isEmpty() -> elves.apply { add(Elf()) }
else -> elves.apply { last().addCalorie(Calorie(line.toInt())) }
}
}.mapIndexed { index, elf ->
index + 1 to elf
}
fun part1(input: List<String>): Int {
return mapToIndexedElves(input)
.maxBy { pair -> pair.second.sum }
.second.sum
}
fun part2(input: List<String>): Int {
return mapToIndexedElves(input)
.sortedBy { it.second.sum }
.reversed()
.slice(0..2)
.sumOf { it.second.sum }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
println(part1(testInput))
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
data class Calorie(val amountOfCalories: Int)
class Elf{
private val carriedCalories = mutableListOf<Calorie>()
fun addCalorie(calorie: Calorie){
carriedCalories.add(calorie)
}
val sum: Int
get() = carriedCalories.sumOf { calorie -> calorie.amountOfCalories }
} | 0 | Kotlin | 0 | 0 | a9d228029f31ca281bd7e4c7eab03e20b49b3b1c | 1,283 | advent-of-code-2022 | Apache License 2.0 |
src/day3/Day3.kt | omarshaarawi | 573,867,009 | false | {"Kotlin": 9725} | package day3
import readInput
fun main() {
fun part1(): Int {
val input = readInput("day3/Day03").map { lines ->
val (a, b) = lines.chunked(lines.length / 2)
Pair(a.toHashSet(), b.toHashSet())
}
val lowercaseAlphabet = ('a'..'z').toMutableList()
val uppercaseAlphabet = ('A'..'Z').toMutableList()
val alphabet = lowercaseAlphabet.plus(uppercaseAlphabet)
val priorityList = mutableListOf<Int>()
input.forEach {
it.first.forEach { c: Char ->
if (it.second.contains(c)) {
priorityList.add(alphabet.indexOf(c) + 1)
}
}
}
return priorityList.sum()
}
fun part2(): Int {
val lowercaseAlphabet = ('a'..'z').toMutableList()
val uppercaseAlphabet = ('A'..'Z').toMutableList()
val alphabet = lowercaseAlphabet.plus(uppercaseAlphabet)
val priorityList = mutableListOf<Int>()
val input = readInput("day3/Day03")
.chunked(3)
val listOfGroups = input.map { stringList ->
stringList.map {
it.toCharArray().toHashSet()
}
}
listOfGroups.forEach {
val (a, b, c) = it
val intersectA = a.intersect(b)
val result = intersectA.intersect(c)
priorityList.add(alphabet.indexOf(result.first()) + 1)
}
return priorityList.sum()
}
println(part1())
println(part2())
}
| 0 | Kotlin | 0 | 0 | 4347548045f12793a8693c4d31fe3d3dade5100a | 1,523 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/year2022/day24/Problem.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 154634} | package year2022.day24
import IProblem
class Problem : IProblem {
private val blizzards = mutableListOf<Blizzard>()
private val map = javaClass
.getResourceAsStream("/2022/24.txt")!!
.bufferedReader()
.readLines()
.mapIndexed { i, line ->
line.mapIndexed { j, c ->
when (c) {
'.' -> 0
'#' -> -1
else -> {
blizzards.add(Blizzard.of(j, i, c))
1
}
}
}
}
private val start = Point(map.first().indexOfFirst { it == 0 }, 0)
private val end = Point(map.last().indexOfFirst { it == 0 }, map.lastIndex)
private fun moves(p: Point): Sequence<Point> {
return sequence {
yield(p.copy(y = p.y - 1))
yield(p.copy(y = p.y + 1))
yield(p.copy(x = p.x - 1))
yield(p.copy(x = p.x + 1))
yield(p.copy())
}
}
private fun traverse(matrix: Array<IntArray>, blizzards: Array<Blizzard>, src: Point, dest: Point): Int {
val queue0 = ArrayDeque(listOf(src))
val queue1 = ArrayDeque<Point>()
var minute = 0
while (true) {
val visited = Array(matrix.size) { BooleanArray(matrix[0].size) }
val (curr, next) = if (minute and 1 == 0) {
Pair(queue0, queue1)
} else {
Pair(queue1, queue0)
}
for (blizzard in blizzards) {
blizzard.move(matrix)
}
while (curr.isNotEmpty()) {
val p = curr.removeFirst()
if (p == dest) {
return minute
}
for (q in moves(p)) {
if (q.y in 0..matrix.lastIndex && matrix[q.y][q.x] == 0 && !visited[q.y][q.x]) {
visited[q.y][q.x] = true
next.addLast(q)
}
}
}
minute++
}
}
override fun part1(): Int {
val matrix = Array(map.size) { i -> IntArray(map[i].size) { j -> map[i][j] } }
val blizzards = Array(blizzards.size) { i-> blizzards[i].copy() }
return traverse(matrix, blizzards, start, end)
}
override fun part2(): Int {
val matrix = Array(map.size) { i -> IntArray(map[i].size) { j -> map[i][j] } }
val blizzards = Array(blizzards.size) { i-> blizzards[i].copy() }
return traverse(matrix, blizzards, start, end) +
traverse(matrix, blizzards, end, start) +
traverse(matrix, blizzards, start, end) + 2
}
}
| 0 | Kotlin | 0 | 0 | 455bc8a69527c6c2f20362945b73bdee496ace41 | 2,724 | advent-of-code | The Unlicense |
src/Day03.kt | phoenixli | 574,035,552 | false | {"Kotlin": 29419} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach{
val wrongItem = findWrongItem(it)!!
if (wrongItem.isLowerCase()) {
sum += wrongItem - 'a' + 1
} else if (wrongItem.isUpperCase()) {
sum += wrongItem - 'A' + 27
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.chunked(3).forEach{
val badge = findBadge(it)!!
if (badge.isLowerCase()) {
sum += badge - 'a' + 1
} else if (badge.isUpperCase()) {
sum += badge - 'A' + 27
}
}
return sum
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
fun findWrongItem(rucksack: String): Char? {
val firstCompartment = rucksack.substring(0, rucksack.length / 2)
val secondCompartment = rucksack.substring(rucksack.length / 2)
val itemMap = mutableMapOf<Char, Int>()
for (item in firstCompartment.iterator()) {
val currQuantity = itemMap[item] ?: 0
itemMap[item] = currQuantity + 1
}
for (item in secondCompartment.iterator()) {
if (itemMap.containsKey(item)) {
return item
}
}
return null
}
fun findCommonItems(first: String, second: String): List<Char> {
val common = mutableListOf<Char>()
val itemMap = mutableMapOf<Char, Int>()
for (item in first.iterator()) {
val currQuantity = itemMap[item] ?: 0
itemMap[item] = currQuantity + 1
}
for (item in second.iterator()) {
if (itemMap.containsKey(item)) {
common.add(item)
}
}
return common
}
fun findBadge(elves: List<String>): Char? {
val first = elves[0]
val second = elves[1]
var common = findCommonItems(first, second)
val third = elves[2]
common = findCommonItems(String(common.toCharArray()), third)
return common.firstOrNull()
}
| 0 | Kotlin | 0 | 0 | 5f993c7b3c3f518d4ea926a792767a1381349d75 | 2,034 | Advent-of-Code-2022 | Apache License 2.0 |
src/day10/puzzle10.kt | brendencapps | 572,821,792 | false | {"Kotlin": 70597} | package day10
import Puzzle
import PuzzleInput
import java.io.File
fun day10Puzzle() {
Day10PuzzleSolution().solve(Day10PuzzleInput("inputs/day10/example.txt", 13140))
Day10PuzzleSolution().solve(Day10PuzzleInput("inputs/day10/input.txt", 13860))
//Day10Puzzle2Solution().solve(Day10PuzzleInput("inputs/day10/example.txt", 0))
Day10Puzzle2Solution().solve(Day10PuzzleInput("inputs/day10/input.txt", 0))
}
class Day10PuzzleInput(val input: String, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult)
class Day10PuzzleSolution : Puzzle<Int, Day10PuzzleInput>() {
private val cyclesToMeasure = setOf(20, 60, 100, 140, 180, 220)
private var cycle = 0
var x = 1
override fun solution(input: Day10PuzzleInput): Int {
return File(input.input).readLines().sumOf {operation ->
var score = 0
if(operation.startsWith("noop")) {
score += nextCycle()
}
else {
score += nextCycle() + nextCycle()
x += operation.split(" ")[1].toInt()
}
if(score != 0) println("$cycle $score")
score
}
}
private fun nextCycle(): Int {
cycle++
return if(cyclesToMeasure.contains(cycle)) x * cycle else 0
}
}
class Day10Puzzle2Solution : Puzzle<Int, Day10PuzzleInput>() {
private var cycle = 0
private var x = 1
override fun solution(input: Day10PuzzleInput): Int {
File(input.input).readLines().forEach { operation ->
if(operation.startsWith("noop")) {
runCycle()
}
else {
runCycle()
runCycle()
x += operation.split(" ")[1].toInt()
}
}
println()
return 0
}
private fun runCycle() {
if(cycle != 0 && cycle % 40 == 0) println()
if(kotlin.math.abs(x - cycle % 40) <= 1) {
print("#")
}
else {
print(" ")
}
cycle++
}
} | 0 | Kotlin | 0 | 0 | 00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3 | 2,114 | aoc_2022 | Apache License 2.0 |
app/src/main/kotlin/day09/Day09.kt | W3D3 | 572,447,546 | false | {"Kotlin": 159335} | package day09
import common.InputRepo
import common.readSessionCookie
import common.solve
import util.splitIntoPair
import kotlin.math.abs
fun main(args: Array<String>) {
val day = 9
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay09Part1, ::solveDay09Part2)
}
data class Pos(val x: Int, val y: Int) {
fun move(direction: String): Pos {
when (direction) {
"U" -> {
return Pos(x, y + 1)
}
"D" -> {
return Pos(x, y - 1)
}
"L" -> {
return Pos(x - 1, y)
}
"R" -> {
return Pos(x + 1, y)
}
}
throw IllegalArgumentException("Invalid direction")
}
fun follow(head: Pos): Pos {
val xDiff = head.x - x
val yDiff = head.y - y
if (abs(xDiff) > 1 && abs(yDiff) >= 1 || abs(xDiff) >= 1 && abs(yDiff) > 1) {
return Pos(this.x + 1 * sign(xDiff), this.y + 1 * sign(yDiff))
} else if (abs(xDiff) > 1) {
return Pos(this.x + 1 * sign(xDiff), this.y)
} else if (abs(yDiff) > 1) {
return Pos(this.x, this.y + +1 * sign(yDiff))
}
return this
}
}
fun sign(value: Int): Int {
if (value < 0) {
return -1
} else if (value > 0) {
return 1
} else {
return 0
}
}
fun solveDay09Part1(input: List<String>): Int {
val moves = input.map { it.splitIntoPair(" ") }
var head = Pos(0, 0)
var tail = Pos(0, 0)
val tailVisited = mutableSetOf(tail)
moves.forEach { (dir, repeat) ->
repeat(repeat.toInt()) {
head = head.move(dir)
tail = tail.follow(head)
tailVisited.add(tail)
}
}
return tailVisited.size
}
fun printGrid(n: Int, head: Pos, tails: List<Pos>) {
for (y in n downTo 0) {
for (x in 0..n) {
if (x == head.x && y == head.y) {
print("H")
} else if (tails.firstOrNull { it.x == x && it.y == y } != null) {
print(tails.indexOf(tails.firstOrNull { it.x == x && it.y == y }))
// print("T")
} else {
print(".")
}
}
println()
}
}
fun solveDay09Part2(input: List<String>): Int {
val moves = input.map { it.splitIntoPair(" ") }
var head = Pos(0, 0)
val tails = mutableListOf(
Pos(0, 0),
Pos(0, 0),
Pos(0, 0),
Pos(0, 0),
Pos(0, 0),
Pos(0, 0),
Pos(0, 0),
Pos(0, 0),
Pos(0, 0),
)
val tailVisited = tails.toMutableSet()
moves.forEach { (dir, repeat) ->
repeat(repeat.toInt()) {
printGrid(5, head, tails)
head = head.move(dir)
for ((index, tail) in tails.withIndex()) {
val currentFollowHead = if (index > 0) tails[index - 1] else head
tails[index] = tail.follow(currentFollowHead)
}
tailVisited.add(tails[8])
}
}
return tailVisited.size
}
| 0 | Kotlin | 0 | 0 | 34437876bf5c391aa064e42f5c984c7014a9f46d | 3,138 | AdventOfCode2022 | Apache License 2.0 |
src/day2/Day02.kt | dinoolivo | 573,723,263 | false | null | package day2
import readInput
fun main() {
val scoreMatrixPart1:Array<Array<Int>> = arrayOf(arrayOf(4,8,3), arrayOf(1,5,9), arrayOf(7,2,6))
val scoreMatrixPart2:Array<Array<Int>> = arrayOf(arrayOf(3,4,8,), arrayOf(1,5,9), arrayOf(2,6,7))
fun fromCode(code: String):Int = when (code) {
"X", "A" -> 0
"Y", "B" -> 1
"Z", "C" -> 2
else -> -1
}
fun codePairs(row:String):Pair<Int,Int> {
val cols = row.split(" ")
return Pair(fromCode(cols[0]), fromCode(cols[1]))
}
fun part1(input: List<Pair<Int,Int>>): Int = input.sumOf { codes ->
scoreMatrixPart1[codes.first][codes.second]
}
fun part2(input: List<Pair<Int,Int>>): Int = input.sumOf { codes ->
scoreMatrixPart2[codes.first][codes.second]
}
val testInput = readInput("inputs/Day02_test").map(::codePairs)
println("Test Part 1: " + part1(testInput))
println("Test Part 2: " + part2(testInput))
//execute the two parts on the real input
val input = readInput("inputs/Day02").map(::codePairs)
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 6e75b42c9849cdda682ac18c5a76afe4950e0c9c | 1,171 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day21.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2021/day/21",
date = Date(day = 21, year = 2021)
)
class Day21(val input: List<String>) : Puzzle {
private val start1 = input[0].substringAfter("Player 1 starting position: ").toInt()
private val start2 = input[1].substringAfter("Player 2 starting position: ").toInt()
override fun partOne() =
Universe(start1, 0, start2, 0).solveWithDeterministicDice()
override fun partTwo() =
Universe(start1, 0, start2, 0).solveWithDiracDice().let { maxOf(it.first, it.second) }
data class Universe(val field1: Int, val score1: Int, val field2: Int, val score2: Int) {
fun solveWithDiracDice(): Pair<Long, Long> {
memo[this]?.let { return it }
if (score1 >= 21) return 1L to 0L
if (score2 >= 21) return 0L to 1L
var answer = 0L to 0L
for ((dice, count) in diceCount) {
val newField1 = (field1 + dice - 1) % 10 + 1
val newScore1 = score1 + newField1
val (win2, win1) = Universe(field2, score2, newField1, newScore1).solveWithDiracDice()
answer = answer.first + win1 * count to answer.second + win2 * count
}
memo[this] = answer
return answer
}
fun solveWithDeterministicDice(): Int {
var players = Player(field1) to Player(field2)
val dice = DeterministicDice(100)
val min = dice.takeSumOfThree().firstNotNullOf { moves ->
players.first.moves(moves)
if (players.first.wins())
minOf(players.first.points, players.second.points)
else {
players = players.second to players.first
null
}
}
return dice.rolls * min
}
companion object {
val memo = mutableMapOf<Universe, Pair<Long, Long>>()
val diceCount = buildList {
for (i in 1..3)
for (j in 1..3)
for (k in 1..3)
add(i + j + k)
}.groupingBy { it }.eachCount()
}
class Player(var field: Int, var points: Int = 0) {
fun wins() = points >= 1000
fun moves(amount: Int) {
field += amount
field = (field - 1) % 10 + 1
points += field
}
}
class DeterministicDice(private val sides: Int) {
private var r = 0
val rolls get() = r
fun takeSumOfThree() =
generateSequence(1) { x -> if (x == sides) 1 else x + 1 }
.chunked(3)
.onEach { r += 3 }
.map { it.sum() }
}
}
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 2,884 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/com/leecode/array/Code2.kt | zys0909 | 305,335,860 | false | null | package com.leecode.array
/**
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:2 <= n <= 100000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
*/
/**
* 用一个容器装已经确定的数
*/
fun findRepeatNumber1(nums: IntArray): Int {
val map = mutableSetOf<Int>()
for (i in nums) {
if (map.contains(i)) {
return i
} else {
map.add(i)
}
}
return -1
}
/**
* 先排序,再判断相邻的数是否相等
*/
fun findRepeatNumber2(nums: IntArray): Int {
nums.sort()
for (i in 1 until nums.size) {
if (nums[i] == nums[i - 1]) {
return nums[i]
}
}
return -1
}
/**
* 所有数字都在长度范围内,将每个数字放到对应的下标位置,判断当前数字是否与该位置的数字相等
*/
fun findRepeatNumber3(nums: IntArray): Int {
for (i in nums.indices) {
val n = nums[i]
if (i != n) {
if (nums[n] == n) {
return n
} else {
nums[i] = nums[n]
nums[n] = n
}
}
}
return -1
} | 0 | Kotlin | 0 | 0 | 869c7c2f6686a773b2ec7d2aaa5bea2de46f1e0b | 1,498 | CodeLabs | Apache License 2.0 |
kotlin-samples/src/yitian/study/skilled/collections.kt | techstay | 83,331,563 | false | null | package yitian.study.skilled
fun main(args: Array<String>) {
//获取订单数最多的顾客
val customerOfMaxOrder = orders().groupBy { it.customer }
.maxBy { it.value.size }
?.key
println("获取订单数最多的顾客:$customerOfMaxOrder")
//获取订单金额最多的顾客
val customerOfMaxOrderPrice = orders().groupBy { it.customer }
.maxBy { it.value.sumByDouble { it.products.sumByDouble { it.price } } }
?.key
println("获取订单金额最多的顾客:$customerOfMaxOrderPrice")
//价格最贵的商品
val mostExpensiveProduct = products().maxBy { it.price }
println("价格最贵的商品:$mostExpensiveProduct")
//计算机类的所有商品
val productsOfComputer = products().filter { it.category == Category.Computer }
println("计算机类的所有商品:$productsOfComputer")
//最便宜的三件商品
val productsOfCheapestThree = products().sortedBy { it.price }
.filterIndexed({ index, _ -> index < 3 })
println("最便宜的三件商品:$productsOfCheapestThree")
//每个顾客购买的商品列表
val productsOfCustomers = orders().groupBy { it.customer }
.map { it.value.map { it.products }.flatten() }
//每位顾客都购买了的商品
val productsOfEveryCustomer = productsOfCustomers.fold(products(), {
result, products ->
result.intersect(products).toList()
})
println("每位顾客都购买了的商品:$productsOfEveryCustomer")
}
data class Product(val name: String, val price: Double, val category: Category)
data class City(val name: String)
data class Customer(val name: String, val city: City) {
override fun toString(): String {
return "Customer(name=$name, city=$city)"
}
}
data class Order(val products: List<Product>, val customer: Customer)
enum class Category {
Computer, Education, Game
}
fun cities(): List<City> {
return listOf(City("呼和浩特")
, City("北京")
, City("上海")
, City("天津")
, City("武汉"))
}
fun products(): List<Product> {
return listOf(Product("Intel Core i7-7700k", 2799.00, Category.Computer),
Product("AMD Ryzen 7 1700", 2499.0, Category.Computer),
Product("Counter Strike", 10.0, Category.Game),
Product("Batman", 79.0, Category.Game),
Product("Thinking in Java", 59.0, Category.Education),
Product("C# Programming", 99.0, Category.Education)
)
}
fun customers(): List<Customer> {
return listOf(Customer("易天", cities()[0])
, Customer("张三", cities()[1])
, Customer("李四", cities()[2])
, Customer("沪生", cities()[3])
, Customer("王五", cities()[4]))
}
fun orders(): List<Order> {
return listOf(Order(products().subList(0, 3), customers()[0])
, Order(products().subList(3, products().size), customers()[0])
, Order(products().subList(1, 3), customers()[1])
, Order(products().subList(2, 4), customers()[2])
, Order(products().subList(0, 4), customers()[3])
, Order(products().subList(1, 5), customers()[4])
)
} | 2 | Kotlin | 0 | 0 | 822a02ca42783521ac6f5b5c62c52f0ea4b39ec8 | 3,255 | kotlin-study | MIT License |
src/day04/Day04_functional.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day04
import readLines
/**
* Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin)
* I'm experimenting with his solutions to better learn functional programming in Kotlin.
* Files without the _functional suffix are my original solutions.
*/
private fun String.asIntRange(): IntRange =
substringBefore("-").toInt()..substringAfter("-").toInt()
private fun String.asRanges(): Pair<IntRange,IntRange> =
substringBefore(",").asIntRange() to substringAfter(",").asIntRange()
private infix fun IntRange.fullyOverlaps(other: IntRange): Boolean =
first <= other.first && last >= other.last
private infix fun IntRange.overlaps(other: IntRange): Boolean =
first <= other.last && other.first <= last
private fun part1(input: List<String>): Int {
val ranges: List<Pair<IntRange, IntRange>> = input.map { it.asRanges() }
return ranges.count { it.first fullyOverlaps it.second || it.second fullyOverlaps it.first }
}
private fun part2(input: List<String>): Int {
val ranges: List<Pair<IntRange, IntRange>> = input.map { it.asRanges() }
return ranges.count { it.first overlaps it.second }
}
fun main() {
println(part1(readLines("day04/test")))
println(part1(readLines("day04/input")))
println(part2(readLines("day04/test")))
println(part2(readLines("day04/input")))
}
| 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 1,344 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day20/Day20.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day20
import java.io.File
private const val LIGHT_PIXEL = '#'
private const val DARK_PIXEL = '.'
fun parseInput(lines: List<String>): Pair<String, List<String>> = lines.first() to lines.drop(2)
private fun square3x3(center: Pair<Int, Int>): List<Pair<Int, Int>> =
listOf(
// sorted according to the particular order in which the square has to be traversed
-1 to -1, 0 to -1, 1 to -1,
-1 to 0, 0 to 0, 1 to 0,
-1 to 1, 0 to 1, 1 to 1,
).map { (x, y) -> center.first + x to center.second + y }
fun enhanceImage(imageEnhancement: String, image: List<String>, iterations: Int): List<String> {
fun computePixel(position: Pair<Int, Int>, image: List<String>, default: Char): Char {
val index = square3x3(position)
.map { (x, y) -> image.getOrNull(y)?.getOrNull(x) ?: default }
.fold(0) { acc, pixel -> acc.shl(1) + if (pixel == LIGHT_PIXEL) 1 else 0 }
return imageEnhancement[index]
}
fun iterate(image: List<String>, default: Char): List<String> {
// the canvas extends in all directions indefinitely so the 'default' char in
// the position 'out of the frame' is also subject to image enhancement effects
// the default is the one that should be used when checking for an adjacent that's
// out of the frame. This default will change depending on the algorithm
val canvasWidth = image.firstOrNull()?.length ?: 0
val blankLine = listOf(default.toString().repeat(canvasWidth))
val expandedImage = blankLine + image + blankLine
val outputImage = mutableListOf<String>()
for ((y, line) in expandedImage.withIndex()) {
val builder = StringBuilder()
for (x in -1..(line.length + 1)) {
builder.append(computePixel(x to y, expandedImage, default))
}
outputImage.add(builder.toString())
}
return outputImage
}
var default = DARK_PIXEL
var outputImage = image
repeat(iterations) {
outputImage = iterate(outputImage, default)
default = imageEnhancement[if (default == LIGHT_PIXEL) 511 else 0]
}
return outputImage
}
fun countLightPixels(image: List<String>): Int = image.sumOf { it.count { pixel -> pixel == LIGHT_PIXEL } }
fun main() {
File("./input/day20.txt").useLines { lines ->
val (enhancement, image) = parseInput(lines.toList())
val output = enhanceImage(enhancement, image, 50)
println(countLightPixels(output))
}
}
| 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 2,385 | advent-of-code-2021 | MIT License |
src/main/kotlin/aoc23/Day05.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc23
import aoc23.Day05Domain.Almanac
import aoc23.Day05Domain.SeedMapper
import aoc23.Day05Parser.toSeedMapper
import aoc23.Day05Solution.part1Day05
import aoc23.Day05Solution.part2Day05
import common.Year23
object Day05 : Year23 {
fun List<String>.part1(): Long = part1Day05()
fun List<String>.part2(): Long = part2Day05()
}
object Day05Solution {
fun List<String>.part1Day05(): Long =
toSeedMapper()
.findLowestLocationSeed()
fun List<String>.part2Day05(): Long =
toSeedMapper()
.findLowestLocationSeedRange()
}
typealias Mapper = List<Day05Domain.FromToMap>
object Day05Domain {
data class SeedMapper(
val seeds: List<Long>,
val almanac: Almanac,
) {
fun findLowestLocationSeed(): Long =
seeds.minOf { seed ->
almanac.mapFromTo(seed)
}
private val seedsRanges: List<LongRange> =
seeds.chunked(2)
.map { it.first()..it.first() + (it.last() - 1) }
private val locations: Sequence<Long> = generateSequence(1L) { it + 1 }
private val reversedAlmanac: Almanac by lazy {
Almanac(
mappers =
almanac.mappers
.reversed()
.map { mapper ->
mapper
.reversed()
.map {
it.copy(fromStart = it.toStart, toStart = it.fromStart)
}
}
)
}
fun findLowestLocationSeedRange(): Long =
locations.first { location ->
reversedAlmanac.mapFromTo(location).let { seed ->
seedsRanges.any { seedRange -> seed in seedRange }
}
}
}
data class Almanac(
val mappers: List<Mapper>,
) {
fun mapFromTo(seed: Long): Long =
mappers.fold(seed) { acc, mapper ->
mapper
.firstNotNullOfOrNull { map -> map.toOrNull(acc) } ?: acc
}
}
data class FromToMap(
val fromStart: Long,
val toStart: Long,
val range: Long
) {
private val fromRange = fromStart..(fromStart + range)
private val fromToDelta = toStart - fromStart
fun toOrNull(from: Long): Long? =
when {
from in fromRange -> from + fromToDelta
else -> null
}
}
}
object Day05Parser {
fun List<String>.toSeedMapper(): SeedMapper =
SeedMapper(
seeds = parseSeeds(),
almanac = Almanac(
mappers = parseMappers()
)
)
private fun List<String>.parseMappers(): List<Mapper> =
this.joinToString(System.lineSeparator())
.split("${System.lineSeparator()}${System.lineSeparator()}")
.drop(1)
.map { mapperString ->
val fromTos =
mapperString
.split(":")
.last()
.split(System.lineSeparator())
.filter { it.isNotBlank() }
fromTos
.map { fromTo -> fromTo.parseFromToMap() }
}
private fun String.parseFromToMap(): Day05Domain.FromToMap {
val numbers = split(" ").map { it.toLong() }
return Day05Domain.FromToMap(
fromStart = numbers[1],
toStart = numbers[0],
range = numbers[2],
)
}
private fun List<String>.parseSeeds(): List<Long> =
first()
.split(":")
.last()
.split(" ")
.filter { it.isNotBlank() }
.map { it.trim().toLong() }
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 3,836 | aoc | Apache License 2.0 |
src/Day03.kt | brigittb | 572,958,287 | false | {"Kotlin": 46744} | fun main() {
val priority = ('a'..'z') + ('A'..'Z')
fun part1(input: List<String>): Int =
input
.map { it.chunked(it.length / 2) }
.map { (first, second) ->
val itemsOfFirst = first.asSequence().toSet()
val itemsOfSecond = second.asSequence().toSet()
itemsOfFirst
.intersect(itemsOfSecond)
.first()
}
.sumOf { priority.indexOf(it) + 1 }
fun part2(input: List<String>): Int =
input
.chunked(3)
.map { (first, second, third) ->
val itemsOfFirst = first.asSequence().toSet()
val itemsOfSecond = second.asSequence().toSet()
val itemsOfThird = third.asSequence().toSet()
itemsOfFirst
.intersect(itemsOfSecond)
.intersect(itemsOfThird)
.first()
}
.sumOf { priority.indexOf(it) + 1 }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 470f026f2632d1a5147919c25dbd4eb4c08091d6 | 1,260 | aoc-2022 | Apache License 2.0 |
src/twentytwentytwo/day3/Day03.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | package twentytwentytwo.day3
import readInput
import kotlin.text.CharCategory.UPPERCASE_LETTER
fun main() {
fun part1(input: List<String>): Int = input.sumOf { sack ->
val firstSack = sack.substring(0, sack.length / 2)
val secondSack = sack.substring(sack.length / 2)
(firstSack.toSet().intersect(secondSack.toSet())).sumOf { score(it) }
}
fun part2(input: List<String>): Int {
var counter = 0
var groupId = 0
val map = input.groupBy { line ->
counter++
val ret = groupId
if (counter % 3 == 0) {
groupId++
counter = 0
}
return@groupBy ret
}
return map.values.sumOf { group ->
(group[0].toSet() intersect group[1].toSet() intersect group[2].toSet()).sumOf {
score(it)
}
}
}
val input = readInput("day3", "Day03_input")
println(part1(input))
println(part2(input))
}
private fun score(char: Char): Int = if (char.category == UPPERCASE_LETTER) {
char - 'A' + 27
} else {
char - 'a' + 1
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 1,129 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day9.kt | mstar95 | 317,305,289 | false | null | package days
class Day9 : Day(9) {
override fun partOne(): Any {
val input = prepareInput(inputList)
val result = calculate(input, 25)
return result
}
private fun calculate(input: List<Long>, log: Int): Long {
return (log until input.size).asSequence()
.map { findSum(input.subList(it - log, it), input[it]) }
.find { it != null } ?: -1
}
private fun findSum(numbers: List<Long>, sum: Long): Long? {
println(" ${numbers.size}, $numbers, $sum")
val find = pairs(numbers).asSequence()
.map { (a, b) -> a + b }
.find { it == sum }
return if (find == null) sum else null
}
private fun pairs(list: List<Long>): List<Pair<Long, Long>> = list.flatMap { e1 -> list.map { e2 -> Pair(e1, e2) } }
override fun partTwo(): Any {
val v1 = 127L
val v2 = 18272118L
val input = prepareInput(inputList)
val set = findContiguousSum(input, v2)
val min = set.minOrNull()!!
val max = set.maxOrNull()!!
print(set)
print(min)
println(max)
return min + max
}
private fun findContiguousSum(inputList: List<Long>, objective: Long): Set<Long> {
var start = 0
var end = 1
var sum = inputList[start] + inputList[end]
while (sum != objective) {
if (start == end) {
throw RuntimeException()
}
if (sum > objective) {
sum -= inputList[start]
start++
}
if (sum < objective) {
end++
sum += inputList[end]
}
}
return inputList.subList(start, end).toSet()
}
}
private fun prepareInput(list: List<String>) = list.map { it.toLong() }
| 0 | Kotlin | 0 | 0 | ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81 | 1,848 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/Day14.kt | D000L | 575,350,411 | false | {"Kotlin": 23716} | import kotlin.math.max
class Dropper(input: List<String>) {
enum class StopCondition { CantMove, TouchFloor }
private val cave = mutableMapOf<Pair<Int, Int>, Char>()
private var floorHeight = 0
init {
input.forEach { line ->
line.filterNot { it.isWhitespace() }.split("->").windowed(2) { (start, end) ->
var (sX, sY) = start.split(",").map { it.toInt() }
var (eX, eY) = end.split(",").map { it.toInt() }
if (sX > eX) sX = eX.also { eX = sX }
if (sY > eY) sY = eY.also { eY = sY }
for (x in sX..eX) {
for (y in sY..eY) {
cave[x to y] = 'r'
}
}
floorHeight = max(floorHeight, eY)
}
}
}
fun run(stopCondition: StopCondition): Int {
val dir = listOf(0 to 1, -1 to 1, 1 to 1)
var count = 0
while (true) {
var (x, y) = 500 to 0
var dropping = true
while (dropping) {
if (y > floorHeight) {
when (stopCondition) {
StopCondition.CantMove -> break
StopCondition.TouchFloor -> return count
}
}
dir.map { (dX, dY) -> x + dX to y + dY }.firstOrNull { cave[it] == null }?.let { (nx, ny) ->
x = nx
y = ny
} ?: run {
dropping = false
}
}
if (cave[x to y] != null) return count
cave[x to y] = 's'
count++
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return Dropper(input).run(Dropper.StopCondition.TouchFloor)
}
fun part2(input: List<String>): Int {
return Dropper(input).run(Dropper.StopCondition.CantMove)
}
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b733a4f16ebc7b71af5b08b947ae46afb62df05e | 2,029 | adventOfCode | Apache License 2.0 |
src/main/kotlin/mytechtoday/aoc/year2022/Day4.kt | mytechtoday | 572,836,399 | false | {"Kotlin": 15268, "Java": 1717} | package mytechtoday.aoc.year2022
import mytechtoday.aoc.util.readInput
fun main() {
fun String.parsePair() =
split("-").let { IntRange(it[0].toInt() , it[1].toInt()) }
fun contains(pair:List<IntRange>) : Boolean {
return (pair[0].contains(pair[1].first) && pair[0].contains(pair[1].last))
|| (pair[1].contains(pair[0].first) && pair[1].contains(pair[0].last))
}
fun overlaps(pair:List<IntRange>) :Boolean {
return pair[0].first <= pair[1].last && pair[0].last >= pair[1].first
}
fun part1(input: List<String>): Int {
val ranges = input.map { it.split(",").map { it.parsePair() } }
var total = 0;
for(item in ranges){
if(contains(item)){
total++
}
}
return total
}
fun part2(input: List<String>): Int {;
val ranges = input.map { it.split(",").map { it.parsePair() } }
var total = 0;
for(item in ranges){
if(overlaps(item)){
total++
}
}
return total
}
val input = readInput(2022,"day4")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3f25cb010e6367af20acaa2906aff17a80f4e623 | 1,187 | aoc2022 | Apache License 2.0 |
src/Day01.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | fun main() {
fun part1(input: List<String>): Int {
val energy = input
.map(String::trim)
.fold(Pair(listOf<Int>(), 0)) { acc, t ->
if (t.trim().isEmpty()) {
Pair(acc.first + acc.second, 0)
} else {
Pair(acc.first, acc.second + t.toInt())
}
}
return energy.first.max()
}
fun part2(input: List<String>): Int {
val energy = input
.map(String::trim)
.fold(Pair(listOf<Int>(), 0)) { acc, t ->
if (t.trim().isEmpty()) {
Pair(acc.first + acc.second, 0)
} else {
Pair(acc.first, acc.second + t.toInt())
}
}
return energy.first.sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 72478)
val input = readInput("Day01_test")
check(part2(testInput) == 210367)
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 1,083 | aoc-2022-in-kotlin | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/binary_tree_right_side_view/BinaryTreeRightSideView.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.binary_tree_right_side_view
import datsok.shouldEqual
import org.junit.jupiter.api.Test
import java.util.*
import kotlin.collections.ArrayList
//
// https://leetcode.com/problems/binary-tree-right-side-view ✅
//
// Given a binary tree, imagine yourself standing on the right side of it,
// return the values of the nodes you can see ordered from top to bottom.
//
// Example:
// Input: [1,2,3,null,5,null,4]
// Output: [1, 3, 4]
// Explanation:
// 1 <---
// / \
// 2 3 <---
// \ \
// 5 4 <---
//
// Example:
// 1 <---
// / \
// 2 3 <---
// \ /\
// 5 4 6 <---
//
// Example:
// 1 <---
// / \
// 2 3 <---
// \ /
// 5 4 <---
//
fun rightSideView(root: TreeNode?): List<Int> {
return if (root == null) emptyList()
else rightSideViewOf(root).map { it.value }
// else breadthFirst(root).map { it.last().value }
}
private fun rightSideViewOf(node: TreeNode?): List<TreeNode> {
if (node == null) return emptyList()
val leftView = rightSideViewOf(node.left)
val rightView = rightSideViewOf(node.right)
return listOf(node) + (rightView + leftView.drop(rightView.size))
}
val TreeNode.value get() = `val`
class Tests {
@Test fun `some examples`() {
rightSideView(TreeNode(1)) shouldEqual listOf(1)
rightSideView(TreeNode(1,
TreeNode(2, right = TreeNode(5)),
TreeNode(3, right = TreeNode(4))
)) shouldEqual listOf(1, 3, 4)
rightSideView(TreeNode(1,
TreeNode(2, right = TreeNode(5)),
TreeNode(3, left = TreeNode(4), right = TreeNode(6))
)) shouldEqual listOf(1, 3, 6)
rightSideView(TreeNode(1,
TreeNode(2, right = TreeNode(5)),
TreeNode(3, left = TreeNode(4))
)) shouldEqual listOf(1, 3, 4)
rightSideView(TreeNode(1,
TreeNode(2, left = TreeNode(4)),
TreeNode(3)
)) shouldEqual listOf(1, 3, 4)
}
}
private fun breadthFirst(rootNode: TreeNode): List<List<TreeNode>> {
val queue = LinkedList<List<TreeNode>>()
queue.add(listOf(rootNode))
val result = ArrayList<List<TreeNode>>()
while (queue.isNotEmpty()) {
val nodes = queue.removeFirst()
result.add(nodes)
val elements = ArrayList<TreeNode>().also { list ->
nodes.forEach {
if (it.left != null) list.add(it.left!!)
if (it.right != null) list.add(it.right!!)
}
}
if (elements.isNotEmpty()) queue.add(elements)
}
return result
}
data class TreeNode(
var `val`: Int,
var left: TreeNode? = null,
var right: TreeNode? = null,
)
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,775 | katas | The Unlicense |
src/Day05.kt | RobvanderMost-TomTom | 572,005,233 | false | {"Kotlin": 47682} | data class Instruction(
val amount: Int,
val fromStack: Int,
val toStack: Int
)
fun main() {
fun splitStacksAndInstructions(input: List<String>): Pair<List<String>, List<String>> {
val separator = input.indexOfFirst { it.isEmpty() }
return input.subList(0, separator) to input.subList(separator + 1, input.size)
}
fun parseStacks(input: List<String>): List<MutableList<Char>> {
val numberOfStacks = input.last().split(" ").last().toInt()
val stacks = buildList(numberOfStacks + 1) {
(0..numberOfStacks).forEach{ _ -> add(mutableListOf<Char>())}
}
input.dropLast(1).reversed().forEach { row ->
(1..numberOfStacks).forEach { stackNr ->
val crateCol = 1 + 4 * (stackNr - 1)
if (crateCol < row.length) {
val crate = row[crateCol]
if (!crate.isWhitespace()) {
stacks[stackNr].add(crate)
}
}
}
}
return stacks
}
fun parseInstructions(input: List<String>) =
input.mapNotNull {
"move (\\d+) from (\\d+) to (\\d+)".toRegex().find(it)
}.map {
Instruction(it.groupValues[1].toInt(), it.groupValues[2].toInt(), it.groupValues[3].toInt())
}
fun createMover9000(stacks: List<MutableList<Char>>, instructions: List<Instruction>) {
instructions.forEach {instruction ->
check(instruction.fromStack < stacks.size)
check(instruction.toStack < stacks.size)
check(stacks[instruction.fromStack].size >= instruction.amount)
(1..instruction.amount).forEach { _ ->
stacks[instruction.toStack].add(stacks[instruction.fromStack].removeLast())
}
stacks.drop(1).forEachIndexed { index, chars -> println("${index+1} - ${chars.joinToString()}") }
}
}
fun createMover9001(stacks: List<MutableList<Char>>, instructions: List<Instruction>) {
instructions.forEach {instruction ->
check(instruction.fromStack < stacks.size)
check(instruction.toStack < stacks.size)
check(stacks[instruction.fromStack].size >= instruction.amount)
stacks[instruction.toStack].addAll(stacks[instruction.fromStack].takeLast(instruction.amount))
(1..instruction.amount).forEach { _ ->
stacks[instruction.fromStack].removeLast()
}
stacks.drop(1).forEachIndexed { index, chars -> println("${index+1} - ${chars.joinToString()}") }
}
}
fun part1(input: List<String>): String {
val (rawStacks, rawInstructions) = splitStacksAndInstructions(input)
val stacks = parseStacks(rawStacks)
check(stacks.maxOf { it.size } == rawStacks.size - 1)
val instructions = parseInstructions(rawInstructions)
check(instructions.size == rawInstructions.size)
createMover9000(stacks, instructions)
return stacks.drop(1).joinToString(separator = "") { it.last().toString() }
}
fun part2(input: List<String>): String {
val (rawStacks, rawInstructions) = splitStacksAndInstructions(input)
val stacks = parseStacks(rawStacks)
check(stacks.maxOf { it.size } == rawStacks.size - 1)
val instructions = parseInstructions(rawInstructions)
check(instructions.size == rawInstructions.size)
createMover9001(stacks, instructions)
return stacks.drop(1).joinToString(separator = "") { it.last().toString() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
println("==========================================")
check(part2(testInput) == "MCD")
println("==========================================")
val input = readInput("Day05")
println(part1(input))
println("==========================================")
println(part2(input))
}
| 5 | Kotlin | 0 | 0 | b7143bceddae5744d24590e2fe330f4e4ba6d81c | 4,054 | advent-of-code-2022 | Apache License 2.0 |
src/org/aoc2021/Day5.kt | jsgroth | 439,763,933 | false | {"Kotlin": 86732} | package org.aoc2021
import java.nio.file.Files
import java.nio.file.Path
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sign
object Day5 {
data class Vent(val x1: Int, val y1: Int, val x2: Int, val y2: Int)
private fun solvePart1(filename: String): Int {
val vents = Files.readAllLines(Path.of(filename), Charsets.UTF_8)
.map(Day5::parseLine)
val counts = emptyCountsGrid(vents)
vents.forEach { vent ->
if (vent.x1 == vent.x2) {
val start = min(vent.y1, vent.y2)
val end = max(vent.y1, vent.y2)
for (j in start..end) {
counts[vent.x1][j]++
}
}
if (vent.y1 == vent.y2) {
val start = min(vent.x1, vent.x2)
val end = max(vent.x1, vent.x2)
for (i in start..end) {
counts[i][vent.y1]++
}
}
}
return counts.sumOf { column ->
column.count { it >= 2 }
}
}
private fun solvePart2(filename: String): Int {
val vents = Files.readAllLines(Path.of(filename), Charsets.UTF_8)
.map(Day5::parseLine)
val counts = emptyCountsGrid(vents)
vents.forEach { vent ->
val dx = (vent.x2 - vent.x1).sign
val dy = (vent.y2 - vent.y1).sign
val length = max(abs(vent.x2 - vent.x1), abs(vent.y2 - vent.y1))
for (i in 0..length) {
counts[vent.x1 + dx * i][vent.y1 + dy * i]++
}
}
return counts.sumOf { column ->
column.count { it >= 2 }
}
}
private fun emptyCountsGrid(vents: List<Vent>): Array<Array<Int>> {
val maxX = vents.maxOf { max(it.x1, it.x2) } + 1
val maxY = vents.maxOf { max(it.y1, it.y2) } + 1
return Array(maxX) { Array(maxY) { 0 } }
}
private fun parseLine(line: String): Vent {
val (p1, p2) = line.split(" -> ")
val (x1, y1) = p1.split(",").map(String::toInt)
val (x2, y2) = p2.split(",").map(String::toInt)
return Vent(x1, y1, x2, y2)
}
@JvmStatic
fun main(args: Array<String>) {
val filename = "input5.txt"
val solution1 = solvePart1(filename)
println(solution1)
val solution2 = solvePart2(filename)
println(solution2)
}
} | 0 | Kotlin | 0 | 0 | ba81fadf2a8106fae3e16ed825cc25bbb7a95409 | 2,447 | advent-of-code-2021 | The Unlicense |
src/main/kotlin/dev/bogwalk/batch3/Problem39.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch3
import dev.bogwalk.util.maths.isCoPrime
import dev.bogwalk.util.maths.pythagoreanTriplet
import dev.bogwalk.util.maths.sum
import kotlin.math.ceil
import kotlin.math.sqrt
/**
* Problem 39: Integer Right Triangles
*
* https://projecteuler.net/problem=39
*
* Goal: If P is the perimeter of a right-angle triangle, find the smallest value of P <= N that
* has the maximum number of (a, b, c) solutions.
*
* Constraints: 12 <= N <= 5e6
*
* e.g. P = 120 has 3 solutions: (20, 48, 52), (24, 45, 51), & (30, 40, 50).
*
* e.g.: N = 12
* P = 12 as 12 is the only sum of a Pythagorean triplet (3, 4, 5)
*/
class IntegerRightTriangles {
/**
* Brute solution based on the following:
*
* - Pythagorean Triplets must either be all evens OR 2 odds with 1 even. So, the sum of
* triplets will only ever be an even number as the sum of evens is an even number, as is
* the sum of 2 odds.
*
* - Since a < b < c and a + b + c = P, a will not be higher than P/3.
*
* - If c = P - a - b is inserted into the equation a^2 + b^2 = c^2, then:
*
* a^2 + b^2 = P^2 - 2aP - 2bP + 2ab + a^2 + b^2
*
* b = P(P - 2 a) / 2(P - a)
*
* which means values of P and a that result in an integer value b represent a valid Triplet.
*
* SPEED (WORST) 10.58s for N = 1e5
*/
fun mostTripletSolutionsBrute(n: Int): Int {
var bestP = 12
var mostSols = 1
for (p in 14..n step 2) {
var pSols = 0
for (a in 4 until p / 3) {
val b: Long = (1L * p * (1L * p - 2 * a)) % (1L * 2 * (p - a))
if (b == 0L) pSols++
}
if (pSols > mostSols) {
bestP = p
mostSols = pSols
}
}
return bestP
}
/**
* Solution is influenced by the previously determined solution for finding primitive
* Pythagorean Triplets (Batch 0 - Problem 9).
*
* SPEED (BETTER) 63.07ms for N = 1e5
*/
fun mostTripletSolutions(n: Int): Int {
var bestP = 12
var mostSols = 1
for (p in 14..n step 2) {
var pSols = 0
val limit = p / 2
val mMax = ceil(sqrt(1.0 * limit)).toInt()
for (m in 2..mMax) {
if (limit % m == 0) {
val kMax = p / (2 * m)
var k = if (m % 2 == 1) m + 2 else m + 1
while (k < 2 * m && k <= kMax) {
if (kMax % k == 0 && isCoPrime(k, m)) {
pSols++
}
k += 2
}
}
}
if (pSols > mostSols) {
bestP = p
mostSols = pSols
}
}
return bestP
}
/**
* Solution above is optimised further by relying solely on Euclid's formula to generate all
* primitive Pythagorean triplets.
*
* Every perimeter that has a triplet will be represented as a count in pSols. This array
* is finally converted to another that accumulates the perimeter (below the given limit)
* with the most counts.
*
* N.B. The upper bound for m is found by substituting Euclid's formulae into the perimeter
* formula & reducing to:
*
* p = 2dm(m + n)
*
* which means when d = 1 & n = 1, at most 2m^2 must be below the given limit.
*
* SPEED (BEST) 24.96ms for N = 1e5
*/
fun mostTripletSolutionsImproved(limit: Int): Int {
val pSols = IntArray(limit + 1)
var m = 2
while (2 * m * m < limit) {
for (n in 1 until m) {
// ensure both m and n are not odd and that m and n are co-prime (gcd == 1)
if (m % 2 == 1 && n % 2 == 1 || !isCoPrime(m, n)) continue
var d = 1
while (true) {
val p = pythagoreanTriplet(m, n, d).sum()
if (p > limit) break
pSols[p] += 1
d++
}
}
m++
}
var bestP = 12
var bestCount = 1
val best = IntArray(limit + 1) { i ->
if (i < 12) pSols[i] else {
val count = pSols[i]
if (count > bestCount) {
bestP = i
bestCount = count
}
bestP
}
}
return best[limit]
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 4,591 | project-euler-kotlin | MIT License |
src/main/kotlin/practicecode/coursera/functionalcodingpractice/TaxiParkMain.kt | mnhmasum | 556,253,855 | false | null | package practicecode.coursera.functionalcodingpractice
import practicecode.Driver
import practicecode.Passenger
import practicecode.TaxiPark
import practicecode.Trip
fun main() {
val taxiPark = TaxiPark(
setOf(Driver("D1"), Driver("D2")), setOf(Passenger("P1"), Passenger("P2"), Passenger("P3"), Passenger("P4")),
listOf(
Trip(Driver("D1"), setOf(Passenger("P1"), Passenger("P2")), 1, 2.5, 3.0),
Trip(Driver("D1"), setOf(Passenger("P2"), Passenger("P3")), 1, 2.5, null),
Trip(Driver("D2"), setOf(Passenger("P2"), Passenger("P3")), 1, 2.5, null),
)
)
//findFaithfulPassenger(taxiPark)
//findFrequentPassenger(taxiPark)
val findSmartPassenger = taxiPark.allPassengers.filter { p->
val x = taxiPark.trips.filter { p.name in it.passengers.map {p-> p.name } }.partition { it.discount != null }
x.first.count() > x.second.count()
}
val findTheMostFrequentTripDurationPeriod = taxiPark.trips.groupBy {
(it.duration / 10) * 10..it.duration / 10 * 10 + 9
}.maxBy { it.value.size }.key
val findTheMostFrequentTripDurationPeriod2 = taxiPark.trips.groupBy {
(it.duration / 10) * 10..it.duration / 10 * 10 + 9
}
.maxBy { (_,group)-> group.size }.key
}
private fun findFaithfulPassenger(taxiPark: TaxiPark) {
val r = taxiPark.trips.map { it.passengers }.flatten().groupBy { it.name }
val findFaithfulPassengers = taxiPark.allPassengers.asSequence()
.filter { taxiPark.trips.isNotEmpty() }
.map {
it.name to (r[it.name]?.size ?: 0)
}.filter { it.second >= 0 }.map { Passenger(it.first) }.toSet()
println(findFaithfulPassengers)
}
private fun findFrequentPassenger(taxiPark: TaxiPark) {
val findFrequentPassengers = taxiPark.trips.filter { it.driver.name == "D1" }
.groupBy { it.driver.name }
.filter { it.key == "D1" }
.toList()
.map { it.second }
.flatten()
.flatMap { it.passengers }
.groupBy { it.name }
.filter { it.value.isNotEmpty() }
.flatMap { it.value }.distinctBy { it.name }
println(findFrequentPassengers)
}
| 0 | Kotlin | 0 | 0 | 260b8d1e41c3924bc9ac710bb343107bff748aa0 | 2,184 | ProblemSolvingDaily | Apache License 2.0 |
src/main/java/challenges/educative_grokking_coding_interview/sliding_window/_9/StringPermutation.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.sliding_window._9
/**
* Given a string and a pattern, find out if the string contains any permutation of the pattern.
* Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations:
* abc
* acb
* bac
* bca
* cab
* cba
* If a string has ‘n’ distinct characters, it will have n! permutations.
*
* https://www.educative.io/courses/grokking-the-coding-interview/N0o9QnPLKNv
*/
object StringPermutation {
private fun findPermutation(str: String, pattern: String): Boolean {
var windowStart = 0
var matched = 0
val charFrequencyMap: MutableMap<Char, Int> = HashMap()
for (chr in pattern.toCharArray()) charFrequencyMap[chr] = charFrequencyMap.getOrDefault(chr, 0) + 1
// our goal is to match all the characters from the 'charFrequencyMap' with the current window
// try to extend the range [windowStart, windowEnd]
for (windowEnd in str.indices) {
val rightChar = str[windowEnd]
if (charFrequencyMap.containsKey(rightChar)) {
// decrement the frequency of the matched character
charFrequencyMap[rightChar] = charFrequencyMap[rightChar]!! - 1
if (charFrequencyMap[rightChar] == 0) // character is completely matched
matched++
}
if (matched == charFrequencyMap.size) return true
if (windowEnd >= pattern.length - 1) { // shrink the window by one character
val leftChar = str[windowStart++]
if (charFrequencyMap.containsKey(leftChar)) {
if (charFrequencyMap[leftChar] == 0) matched-- // before putting the character back, decrement the matched count
// put the character back for matching
charFrequencyMap[leftChar] = charFrequencyMap[leftChar]!! + 1
}
}
}
return false
}
/**
* This is a brute force solution by me.
* The problem in this solution is that we have to loop over the pattern chars
* every time in the sliding window.
*/
private fun findPermutation2(str: String, pattern: String): Boolean {
val patternLength = pattern.length
var windowStart = 0
val charFrequencyMap: MutableMap<Char, Int> = HashMap()
for (windowEnd in str.toCharArray().indices) {
val rightChar = str[windowEnd]
charFrequencyMap[rightChar] = charFrequencyMap.getOrDefault(rightChar, 0) + 1
if (windowEnd - windowStart + 1 == patternLength) {
var isPermutation = true
for (char in pattern) {
if (!charFrequencyMap.containsKey(char)) {
isPermutation = false
break
}
}
if (isPermutation) return true
val leftChar = str[windowStart]
charFrequencyMap[leftChar] = charFrequencyMap[leftChar]!! - 1
if (charFrequencyMap[leftChar]!! == 0) charFrequencyMap.remove(leftChar)
windowStart++
}
}
return false
}
@JvmStatic
fun main(args: Array<String>) {
println(findPermutation("oidbcaf", "abc"))
println(findPermutation("odicf", "dc"))
println(findPermutation("bcdxabcdy", "bcdxabcdy"))
println(findPermutation("aaacb", "abc"))
println("=============")
println(findPermutation2("oidbcaf", "abc"))
println(findPermutation2("odicf", "dc"))
println(findPermutation2("bcdxabcdy", "bcdxabcdy"))
println(findPermutation2("aaacb", "abc"))
}
}
| 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 3,804 | CodingChallenges | Apache License 2.0 |
src/Day03.kt | BHFDev | 572,832,641 | false | null | import java.lang.Error
fun main() {
fun part1(input: List<String>): Int {
val priorities = mutableMapOf<Char, Int>()
var count = 1
('a'..'z').forEach { priorities[it] = count++ }
('A'..'Z').forEach { priorities[it] = count++ }
return input.sumOf {rucksack ->
val firstCompartment = rucksack
.substring(0, rucksack.length / 2)
.toSet()
val item = rucksack
.substring(rucksack.length / 2, rucksack.length)
.find { firstCompartment.contains(it) }
priorities[item] ?: throw Error()
}
}
fun part2(input: List<String>): Int {
val priorities = mutableMapOf<Char, Int>()
var count = 1
('a'..'z').forEach { priorities[it] = count++ }
('A'..'Z').forEach { priorities[it] = count++ }
return input
.chunked(3)
.sumOf { elves ->
val firstCompartment = elves[0].toSet()
val secondCompartment = elves[1].toSet()
val item = elves[2].find { firstCompartment.contains(it) && secondCompartment.contains(it) }
priorities[item] ?: throw Error()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b158069483fa02636804450d9ea2dceab6cf9dd7 | 1,481 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/wtf/log/xmas2021/day/day08/Day08.kt | damianw | 434,043,459 | false | {"Kotlin": 62890} | package wtf.log.xmas2021.day.day08
import com.google.common.collect.Multimap
import wtf.log.xmas2021.Day
import wtf.log.xmas2021.util.collect.copy
import wtf.log.xmas2021.util.collect.multimapOf
import java.io.BufferedReader
object Day08 : Day<List<Entry>, Int, Int> {
override fun parseInput(reader: BufferedReader): List<Entry> = reader
.lineSequence()
.map(Entry::parse)
.toList()
override fun part1(input: List<Entry>): Int {
val sizes = setOf(2, 3, 4, 7)
return input.sumOf { entry ->
entry.outputs.count { signal ->
signal.size in sizes
}
}
}
override fun part2(input: List<Entry>): Int = input.sumOf { entry ->
val mapping = computeMapping(entry)
entry.outputs
.map { checkNotNull(Digit.fromSignal(it.mapTo(mutableSetOf(), mapping::getValue))) }
.toInt()
}
private fun computeMapping(entry: Entry): Map<Segment, Segment> {
val digitsBySize = mapOf(
2 to Digit.ONE,
3 to Digit.SEVEN,
4 to Digit.FOUR,
7 to Digit.EIGHT,
)
val allSegments = Segment.values()
val candidates = multimapOf<Segment, Segment>()
for (segment in allSegments) {
candidates.putAll(segment, allSegments.asIterable())
}
for (signal in entry.patterns) {
val digit = digitsBySize[signal.size]
if (digit != null) {
for (segment in signal) {
candidates[segment].retainAll(digit.signal)
}
}
}
return checkNotNull(search(candidates, entry.patterns, emptySet()))
}
private fun search(
candidates: Multimap<Segment, Segment>,
testSignals: Set<Set<Segment>>,
currentSearch: Set<Segment>,
): Map<Segment, Segment>? {
val keyCount = candidates.keySet().size
val segmentCount = Segment.values().size
if (keyCount == segmentCount && candidates.size() == segmentCount) {
val mapping = candidates.asMap().mapValues { (_, segments) -> segments.single() }
for (signal in testSignals) {
val mappedSignal = signal.mapTo(mutableSetOf(), mapping::getValue)
if (Digit.fromSignal(mappedSignal) == null) {
return null
}
}
return mapping
} else if (keyCount < segmentCount) {
return null
}
val segment = candidates
.keySet()
.filter { it !in currentSearch && candidates[it].size > 1 }
.minByOrNull { candidates[it].size }
?: return null
for (choice in candidates[segment]) {
val snapshot = candidates.copy()
snapshot.commitChoice(segment, choice)
val nextSearch = search(snapshot, testSignals, currentSearch + segment)
if (nextSearch != null) {
return nextSearch
}
}
return null
}
private fun Multimap<Segment, Segment>.commitChoice(key: Segment, value: Segment) {
for (otherSegment in Segment.values()) {
if (otherSegment != key && remove(otherSegment, value)) {
val otherMapping = get(otherSegment)
if (otherMapping.size == 1) {
commitChoice(otherSegment, otherMapping.single())
}
}
}
removeAll(key)
put(key, value)
}
private fun Iterable<Digit>.toInt(): Int {
var result = 0
for (digit in this) {
result *= 10
result += digit.ordinal
}
return result
}
}
enum class Digit(val signal: Set<Segment>) {
ZERO(Segment.A, Segment.B, Segment.C, Segment.E, Segment.F, Segment.G),
ONE(Segment.C, Segment.F),
TWO(Segment.A, Segment.C, Segment.D, Segment.E, Segment.G),
THREE(Segment.A, Segment.C, Segment.D, Segment.F, Segment.G),
FOUR(Segment.B, Segment.C, Segment.D, Segment.F),
FIVE(Segment.A, Segment.B, Segment.D, Segment.F, Segment.G),
SIX(Segment.A, Segment.B, Segment.D, Segment.E, Segment.F, Segment.G),
SEVEN(Segment.A, Segment.C, Segment.F),
EIGHT(Segment.A, Segment.B, Segment.C, Segment.D, Segment.E, Segment.F, Segment.G),
NINE(Segment.A, Segment.B, Segment.C, Segment.D, Segment.F, Segment.G),
;
constructor(vararg segments: Segment) : this(setOf(*segments))
companion object {
private val mapping: Map<Set<Segment>, Digit> = values().associateBy { it.signal }
fun fromSignal(signal: Set<Segment>): Digit? = mapping[signal]
}
}
data class Entry(
val patterns: Set<Set<Segment>>,
val outputs: List<Set<Segment>>,
) {
companion object {
fun parse(line: String): Entry {
val split = line.split('|')
check(split.size == 2)
return Entry(
patterns = split[0].trim().split(' ').mapTo(mutableSetOf(), Segment::parse),
outputs = split[1].trim().split(' ').map(Segment::parse),
)
}
}
}
enum class Segment {
A,
B,
C,
D,
E,
F,
G,
;
companion object {
private val mapping = values().associateBy { it.name.lowercase().single() }
fun parse(text: String): Set<Segment> = text.mapTo(mutableSetOf(), mapping::getValue)
}
}
| 0 | Kotlin | 0 | 0 | 1c4c12546ea3de0e7298c2771dc93e578f11a9c6 | 5,461 | AdventOfKotlin2021 | BSD Source Code Attribution |
src/Day03.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private fun priority(item: Char): Int {
return if (item in 'a'..'z') {
item - 'a' + 1
} else if (item in 'A' .. 'Z') {
item - 'A' + 27
} else {
throw IllegalArgumentException("Unknown priority for item $item")
}
}
private fun part1(input: List<String>): Int {
var totalPriority = 0
for (line in input) {
val duplicatedItems = mutableSetOf<Char>()
val compartment1 = line.substring(0, line.length / 2)
val compartment2 = line.substring(line.length / 2)
for (item in compartment1) {
if (compartment2.contains(item) && !duplicatedItems.contains(item)) {
totalPriority += priority(item)
duplicatedItems.add(item)
}
}
}
return totalPriority
}
private fun part2(input: List<String>): Int {
var totalPriority = 0
for (i in input.indices step 3) {
val rucksack1 = input[i]
val rucksack2 = input[i + 1]
val rucksack3 = input[i + 2]
var commonItemFound = false
for (item in rucksack1) {
if (rucksack2.contains(item) && rucksack3.contains(item)) {
totalPriority += priority(item)
commonItemFound = true
break
}
}
if (!commonItemFound) {
throw IllegalArgumentException("Common item not found")
}
}
return totalPriority
}
fun main() {
val input = readInput("Day03")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 1,601 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | l8nite | 573,298,097 | false | {"Kotlin": 105683} | import java.util.ArrayDeque
fun parseStacks(input: List<String>): MutableList<ArrayDeque<String>> {
val stackIdPattern = Regex("^(\\s+\\d)+$")
val stacks = mutableListOf(ArrayDeque<String>())
val crateNameFilter = Regex("[^A-Z]")
// parse input lines until we reach something that looks like " 1 2 3"
// iterate those lines backwards, and add the corresponding crates to their stacks
input.takeWhile { !stackIdPattern.containsMatchIn(it) }.reversed().forEach { line ->
line.chunked(4).withIndex().forEach {
if (it.index == stacks.size) { stacks.add(ArrayDeque<String>()) }
val crate = it.value.replace(crateNameFilter, "")
if (crate.isNotEmpty()) {
stacks[it.index].push(crate)
}
}
}
return stacks
}
fun parseInstructions(input: List<String>): List<List<Int>> {
val instrPattern = Regex("move (\\d+) from (\\d+) to (\\d+)")
return input.mapNotNull { instrPattern.find(it) }.map { instr ->
instr.destructured.toList().map { it.toInt() }
}
}
fun main() {
fun part1(input: List<String>): String {
val stacks = parseStacks(input)
parseInstructions(input).forEach { instruction ->
val (n, src, dst) = instruction
repeat(n) {
stacks[dst-1].push(stacks[src-1].pop())
}
}
return stacks.joinToString("") { it.peek() }
}
fun part2(input: List<String>): String {
val stacks = parseStacks(input)
parseInstructions(input).forEach { instruction ->
val (n, src, dst) = instruction
stacks[src-1].take(n).reversed().forEach { stacks[dst-1].push(it) }
repeat(n) { stacks[src-1].pop() } // clear items from src array
}
return stacks.joinToString("") { it.peek() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f74331778fdd5a563ee43cf7fff042e69de72272 | 2,145 | advent-of-code-2022 | Apache License 2.0 |
y2016/src/main/kotlin/adventofcode/y2016/Day15.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
object Day15 : AdventSolution(2016, 15, "Timing is Everything") {
override fun solvePartOne(input: String) = calulateWaitingTime(parseConfig(input)).toString()
override fun solvePartTwo(input: String) = calulateWaitingTime(parseConfig(input) + Disc(11, 0)).toString()
private fun parseConfig(s: String): List<Disc> =
s.lines()
.map {
val size = it.substringAfter(" has ").substringBefore(" ").toLong()
val position = it.substringAfterLast(' ').dropLast(1).toLong()
Disc(size, position)
}
private fun calulateWaitingTime(configuration: List<Disc>): Long = configuration
.mapIndexed { i, d -> d.rotate(i + 1) }
.reduce(this::combine)
.let { it.a % it.size }
private data class Disc(val size: Long, val position: Long) {
fun rotate(steps: Int): Disc = this.copy(position = (position + steps) % size)
val a: Long
get() = size - position
}
private fun combine(one: Disc, two: Disc): Disc {
val gcd = extendedGcd(one.size, two.size)
val s = one.size * two.size
val r = one.a * ((two.size * gcd.third) % s) + two.a * ((one.size * gcd.second) % s)
return Disc(s, (s - r) % s)
}
private fun extendedGcd(i: Long, j: Long): Triple<Long, Long, Long> {
var a = i
var b = j
val aa = longArrayOf(1, 0)
val bb = longArrayOf(0, 1)
while (true) {
val q = a / b
a %= b
aa[0] = aa[0] - q * aa[1]
bb[0] = bb[0] - q * bb[1]
if (a == 0L) {
return Triple(b, aa[1], bb[1])
}
val q1 = b / a
b %= a
aa[1] = aa[1] - q1 * aa[0]
bb[1] = bb[1] - q1 * bb[0]
if (b == 0L) {
return Triple(a, aa[0], bb[0])
}
}
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,677 | advent-of-code | MIT License |
src/Day12.kt | ka1eka | 574,248,838 | false | {"Kotlin": 36739} | import java.util.PriorityQueue
import kotlin.math.sqrt
fun main() {
val startSymbol = 'S'
val endSymbol = 'E'
fun Pair<Int, Int>.distance(other: Pair<Int, Int>) =
sqrt(0.0 + (this.first - other.first) * (this.first - other.first) + (this.second - other.second) * (this.second - other.second))
fun List<String>.height(position: Pair<Int, Int>): Char =
when (val current = this[position.second][position.first]) {
startSymbol -> 'a'
endSymbol -> 'z'
else -> current
}
class Node(val position: Pair<Int, Int>, val target: Pair<Int, Int>) {
val distance = position.distance(target)
private var _cost: Int = 1
private var _score: Double = distance + _cost
var parent: Node? = null
set(value) {
field = value
_cost = 1 + (value?.cost ?: 0)
_score = distance + _cost
}
val cost: Int
get() = _cost
val score: Double
get() = _score
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Node
if (position != other.position) return false
return true
}
override fun hashCode(): Int = position.hashCode()
}
fun getNeighbors(current: Node, input: List<String>): List<Node> = listOf(
Pair(current.position.first, current.position.second - 1),
Pair(current.position.first, current.position.second + 1),
Pair(current.position.first - 1, current.position.second),
Pair(current.position.first + 1, current.position.second)
).filter {
it.second >= 0 && it.second < input.size
&& it.first >= 0 && it.first < input[it.second].length
&& input.height(it) - input.height(current.position) <= 1
}.map { Node(it, current.target) }
fun findShortestPath(startPosition: Pair<Int, Int>, endPosition: Pair<Int, Int>, input: List<String>): Int? {
val path = ArrayDeque<Pair<Int, Int>>()
val openList = PriorityQueue<Node>(compareBy { it.score })
val start = Node(startPosition, endPosition)
openList.add(start)
val closedList = mutableSetOf<Node>()
var current: Node = start
while (openList.isNotEmpty() && current.position != endPosition) {
current = openList.poll()!!
closedList.add(current)
val neighbors = getNeighbors(current, input)
for (n in neighbors) {
if (!closedList.contains(n)) {
if (!openList.contains(n)) {
n.parent = current
openList.add(n)
}
}
}
}
var step: Node? = closedList.find { it.position == endPosition } ?: return null
while (step != null && step.position != startPosition) {
path.addFirst(step.position)
step = step.parent
}
return path.size
}
fun part1(input: List<String>): Int {
val start = input
.withIndex()
.find { it.value.startsWith(startSymbol) }
.let { Pair(0, it!!.index) }
val end = input
.withIndex()
.find { it.value.contains(endSymbol) }
.let { Pair(it!!.value.indexOf(endSymbol), it.index) }
return findShortestPath(start, end, input)!!
}
fun part2(input: List<String>): Int {
val end = input
.withIndex()
.find { it.value.contains(endSymbol) }
.let { Pair(it!!.value.indexOf(endSymbol), it.index) }
return input
.withIndex()
.filter {
it.value.contains(startSymbol) || it.value.contains('a')
}
.flatMap { line ->
line.value
.toCharArray()
.withIndex()
.filter { ch -> ch.value == startSymbol || ch.value == 'a' }
.map { ch -> ch.index }
.map { x -> Pair(x, line.index) }
}.mapNotNull { findShortestPath(it, end, input) }
.min()
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f7893448db92a313c48693b64b3b2998c744f3b | 4,513 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | hufman | 573,586,479 | false | {"Kotlin": 29792} | import kotlin.math.absoluteValue
sealed class CPUOpcode(val cycles: Int) {
companion object {
fun fromLine(line: String): CPUOpcode? {
val parts = line.split(' ')
return when (parts[0]) {
"noop" -> NOOP()
"addx" -> ADDX(parts[1].toInt())
else -> null
}
}
}
class NOOP(): CPUOpcode(1)
class ADDX(val operand: Int): CPUOpcode(2) {
override fun run(current: CPUState) = current.copy(X = current.X + operand)
}
open fun run(current: CPUState) = current
override fun toString(): String {
return when (this) {
is NOOP -> "NOOP()"
is ADDX -> "ADDX(${this.operand})"
}
}
}
data class CPUState(val X: Int = 1)
fun main() {
fun parse(input: List<String>): List<CPUOpcode> {
return input.mapNotNull { CPUOpcode.fromLine(it) }
}
fun execute(commands: Iterable<CPUOpcode>) = sequence<CPUState> {
var state = CPUState()
commands.forEach { command ->
// println(command)
(0 until command.cycles).forEach { _ ->
yield(state)
}
state = command.run(state)
}
}
fun part1(input: List<String>): Int {
return execute(parse(input))
// .filterIndexed { pc, cpuState ->
// println("${pc+1} -> $cpuState"); true
// }
.filterIndexed { pc, cpuState -> (pc + 1 >= 20) && (pc + 1 - 20) % 40 == 0 }
.mapIndexed { pc_40, cpuState -> (pc_40 * 40 + 20) * cpuState.X }
// .filter { println(it); true}
.take(6)
.sum()
}
fun part2(input: List<String>): List<String> {
val output = Array(6) {
CharArray(40) {'.'}
}
execute(parse(input)).forEachIndexed { pc, cpuState ->
val y = pc / 40
val x = pc % 40
if ((x - cpuState.X).absoluteValue < 2) {
output[y][x] = '#'
}
}
return output.map {
it.joinToString("")
}
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
println(part2(testInput).joinToString("\n"))
val input = readInput("Day10")
println(part1(input))
println(part2(input).joinToString("\n"))
} | 0 | Kotlin | 0 | 0 | 1bc08085295bdc410a4a1611ff486773fda7fcce | 2,368 | aoc2022-kt | Apache License 2.0 |
src/Day02.kt | felldo | 572,233,925 | false | {"Kotlin": 76496} | enum class RPC(val points: Int, val opponent: String, val self: String) {
ROCK(1, "A", "X"),
PAPER(2, "B", "Y"),
SCISSORS(3, "C", "Z");
companion object {
fun getByName(x: String): RPC {
for (value in values()) {
if (value.opponent == x || value.self == x) {
return value
}
}
return ROCK
}
}
}
fun getPoints(pair: Pair<RPC, RPC>): Int {
return if (pair.first == RPC.ROCK && pair.second == RPC.PAPER
|| pair.first == RPC.PAPER && pair.second == RPC.SCISSORS
|| pair.first == RPC.SCISSORS && pair.second == RPC.ROCK
) {
6
} else if (pair.first == pair.second) {
3
} else {
0
}
}
fun main() {
val testInput = readInput("Day02")
val part1 = testInput
.map { it.split(" ") }
.map { Pair(RPC.getByName(it[0]), RPC.getByName(it[1])) }
.sumOf { getPoints(it) + it.second.points }
println(part1)
val part2 = testInput
.map { it.split(" ") }
.map {
val opponent = RPC.getByName(it[0])
if (RPC.getByName(it[1]) == RPC.ROCK) { //LOOSE
return@map when (opponent) {
RPC.ROCK -> RPC.SCISSORS
RPC.PAPER -> RPC.ROCK
RPC.SCISSORS -> RPC.PAPER
}.points
} else if (RPC.getByName(it[1]) == RPC.PAPER) { //DRAW
return@map 3+opponent.points
} else { //WIN
return@map when (opponent) {
RPC.ROCK -> RPC.PAPER
RPC.PAPER -> RPC.SCISSORS
RPC.SCISSORS -> RPC.ROCK
}.points + 6
}
}
.sum()
println(part2)
}
| 0 | Kotlin | 0 | 0 | 0ef7ac4f160f484106b19632cd87ee7594cf3d38 | 1,806 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day06.kt | ajspadial | 573,864,089 | false | {"Kotlin": 15457} | fun main() {
fun areDistinctCharacters(s: String): Boolean {
var distinct = true
for (i in 0 until s.length) {
if (s[i] in s.substring(i + 1)) {
distinct = false
break
}
}
return distinct
}
fun findFirstDistinctPackage(input: String, size: Int): Int {
var i = 0
var found = false
while (!found && i < input.length - size + 1) {
val packet = input.substring(i, i + size)
found = areDistinctCharacters(packet)
i++
}
return i + size - 1
}
fun part1(input: String): Int {
return findFirstDistinctPackage(input, 4)
}
fun part2(input: String): Int {
return findFirstDistinctPackage(input, 14)
}
// test if implementation meets criteria from the description, like:
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11)
check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19)
check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23)
check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26)
val input = readInput("Day06")
println(part1(input[0]))
println(part2(input[0]))
}
| 0 | Kotlin | 0 | 0 | ed7a2010008be17fec1330b41adc7ee5861b956b | 1,493 | adventofcode2022 | Apache License 2.0 |
src/Day02.kt | jalex19100 | 574,686,993 | false | {"Kotlin": 19795} | // X > C, Z > B, Y > A, X=A, Y=B, Z=C
enum class HandShape(
val desc: String, private val defeats: Char, private val ties: Char, private val shapeValue: Int
) {
X("Rock", 'C', 'A', 1),
Y("Paper", 'A', 'B', 2),
Z("Scissors", 'B', 'C', 3);
fun play(opponentShape: Char): Int {
val score = when (opponentShape) {
this.defeats -> 6
this.ties -> 3
else -> 0
}
return score + this.shapeValue
}
}
/**
## A (rock)
* X (lose:0, scissors:3 = 3)
* Y (draw:3, rock:1 = 4)
* Z (win:6, paper:2 = 8)
## B (paper)
* X (lose:0, rock:1 = 1)
* Y (draw:3, paper:2 = 5)
* Z (win:6, scissors:3 = 9)
## C (scissors)
* X (lose:0, paper:2 = 2)
* Y (draw:3, scissors:3 = 6)
* Z (win:6, rock:1 = 7)
*/
enum class HandShapeSuggestion(val desc: String, val X: Int, val Y: Int, val Z: Int) {
A("Rock", 3, 4, 8),
B("Paper", 1, 5, 9),
C("Scissors", 2, 6, 7);
fun play(desiredResult: Char): Int {
val score = when (desiredResult) {
'X' -> this.X
'Y' -> this.Y
'Z' -> this.Z
else -> 0
}
return score
}
}
fun main() {
fun part1(input: List<String>): Int {
var total = 0
input.forEach { line ->
val yourShape = HandShape.values().first { it.name == line.substring(2, 3) }
val score = yourShape.play(line.toCharArray()[0])
total += score
}
return total
}
// TODO: combine and pass in unique logic via function argument
fun part2(input: List<String>): Int {
var total = 0
input.forEach { line ->
val opponentsShape = HandShapeSuggestion.values().first { it.name == line.substring(0, 1) }
val score = opponentsShape.play(line.toCharArray()[2])
total += score
}
return total
}
// 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: ${part1(input)}")
println("Part2: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | a50639447a2ef3f6fc9548f0d89cc643266c1b74 | 2,195 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day03.kt | zychu312 | 573,345,747 | false | {"Kotlin": 15557} | fun Char.toPriority(): Int = when (this.category) {
CharCategory.UPPERCASE_LETTER -> this.code - 'A'.code + 'z'.toPriority() + 1
CharCategory.LOWERCASE_LETTER -> this.code - 'a'.code + 1
else -> error("Wrong letter")
}
infix fun String.toCompartment(range: IntRange) = this.substring(range).toCharArray().toSet()
fun loadInventories() = loadFile("Day03Input.txt").readLines()
fun main() {
loadInventories()
.sumOf { line ->
val halfIndex = line.length / 2
val firstCompartment = line toCompartment (0 until halfIndex)
val secondCompartment = line toCompartment (halfIndex until line.length)
val itemsOccurringMultipleTimes = firstCompartment.intersect(secondCompartment)
itemsOccurringMultipleTimes.sumOf {
it.toPriority()
}
}.let { println("Problem one: $it") }
loadInventories()
.asSequence()
.chunked(3)
.map { strings -> strings.map { it.toCharArray().toSet() } }
.map { threeInventories -> threeInventories.reduce { a, b -> a intersect b } }
.map { intersectionChars -> intersectionChars.first() }
.sumOf { uniqueItem -> uniqueItem.toPriority() }
.let { println("Problem two: $it") }
}
| 0 | Kotlin | 0 | 0 | 3e49f2e3aafe53ca32dea5bce4c128d16472fee3 | 1,282 | advent-of-code-kt | Apache License 2.0 |
2021/src/main/kotlin/Day20.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | class Day20(val input: List<String>) {
private val algorithm = input[0].map { it == '#' }.toTypedArray()
private val image = input[1].split("\n").map { line ->
line.map { it == '#' }.toTypedArray()
}.toTypedArray()
private fun Array<Array<Boolean>>.getAt(x: Int, y: Int, unknown: Boolean): Boolean {
return this.getOrNull(y)?.getOrNull(x) ?: unknown
}
private fun Array<Array<Boolean>>.getSurrounding(x: Int, y: Int, unknown: Boolean): Int {
val replacement = if (algorithm[0]) unknown else false
var result = 0
if (this.getAt(x - 1, y - 1, replacement)) result += 256
if (this.getAt(x, y - 1, replacement)) result += 128
if (this.getAt(x + 1, y - 1, replacement)) result += 64
if (this.getAt(x - 1, y, replacement)) result += 32
if (this.getAt(x, y, replacement)) result += 16
if (this.getAt(x + 1, y, replacement)) result += 8
if (this.getAt(x - 1, y + 1, replacement)) result += 4
if (this.getAt(x, y + 1, replacement)) result += 2
if (this.getAt(x + 1, y + 1, replacement)) result += 1
return result
}
private fun applyAlgorithm(map: Array<Array<Boolean>>, unknown: Boolean): Array<Array<Boolean>> {
return (-2..map.size + 1).map { y ->
(-2..map[0].size + 1).map { x ->
val surrounding = map.getSurrounding(x, y, unknown)
algorithm[surrounding]
}.toTypedArray()
}.toTypedArray()
}
private fun solve(n: Int): Int {
var processed = image
return repeat(n) {
processed = applyAlgorithm(processed, it % 2 != 0)
}.let {
processed.sumOf { row ->
row.count { it }
}
}
}
fun solve1(): Int {
return solve(2)
}
fun solve2(): Int {
return solve(50)
}
}
| 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 1,897 | adventofcode-2021-2025 | MIT License |
src/com/ncorti/aoc2023/Day13.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
fun main() {
fun parseInput() = getInputAsText("13") {
split("\n\n").filter(String::isNotBlank).map {
it.split("\n").filter(String::isNotBlank).map { line ->
line.toCharArray()
}.toTypedArray()
}
}
fun hasSmudgeInCol(map: Array<CharArray>, col1: Int, col2: Int): Boolean {
var countDiffs = 0
for (j in map.indices) {
if (map[j][col1] != map[j][col2]) {
countDiffs++
}
}
return countDiffs == 1
}
fun areColEquals(map: Array<CharArray>, col1: Int, col2: Int, withSmudge: Boolean): Boolean {
if (!withSmudge) {
return map.all { it[col1] == it[col2] }
} else {
if (map.all { it[col1] == it[col2] }) {
return true
}
return hasSmudgeInCol(map, col1, col2)
}
}
fun hasSmudgeInRow(map: Array<CharArray>, row1: Int, row2: Int): Boolean {
var countDiffs = 0
for (j in map[0].indices) {
if (map[row1][j] != map[row2][j]) {
countDiffs++
}
}
return countDiffs == 1
}
fun areRowEquals(map: Array<CharArray>, row1: Int, row2: Int, withSmudge: Boolean): Boolean {
if (!withSmudge) {
return map[row1].contentEquals(map[row2])
} else {
if (map[row1].contentEquals(map[row2])) {
return true
}
return hasSmudgeInRow(map, row1, row2)
}
}
fun findReflectionColumn(map: Array<CharArray>, withSmudge: Boolean): Int {
for (i in 0 until map[0].size - 1) {
if (areColEquals(map, i, i + 1, withSmudge)) {
var smudgeFound = hasSmudgeInCol(map, i, i + 1)
var colLeft = i - 1
var colRight = i + 2
val candidate = i + 1
while (colLeft >= 0 && colRight <= map[0].size - 1) {
if (areColEquals(map, colLeft, colRight, withSmudge)) {
smudgeFound = smudgeFound || hasSmudgeInCol(map, colLeft, colRight)
colLeft--
colRight++
} else {
break
}
}
if (colLeft == -1 || colRight == map[0].size && (!withSmudge || smudgeFound)) {
return candidate
}
}
}
return 0
}
fun findReflectionRow(map: Array<CharArray>, withSmudge: Boolean): Int {
for (i in 0 until map.size - 1) {
if (areRowEquals(map, i, i + 1, withSmudge)) {
var smudgeFound = hasSmudgeInRow(map, i, i + 1)
var rowUp = i - 1
var rowDown = i + 2
val candidate = i + 1
while (rowUp >= 0 && rowDown <= map.size - 1) {
if (areRowEquals(map, rowUp, rowDown, withSmudge)) {
smudgeFound = smudgeFound || hasSmudgeInRow(map, rowUp, rowDown)
rowUp--
rowDown++
} else {
break
}
}
if (rowUp == -1 || rowDown == map.size && (!withSmudge || smudgeFound)) {
return candidate
}
}
}
return 0
}
fun part(withSmudge: Boolean = false): Int {
val input = parseInput()
return input.sumOf { map ->
val reflectionRow = findReflectionRow(map, false)
val reflectionRowWithSmudge = findReflectionRow(map, true)
val reflectionCol = findReflectionColumn(map, false)
val reflectionColWithSmudge = findReflectionColumn(map, true)
if (!withSmudge) {
if (reflectionRow != 0) {
100 * reflectionRow
} else {
reflectionCol
}
} else {
if (reflectionRowWithSmudge != 0 && reflectionRow != reflectionRowWithSmudge) {
100 * reflectionRowWithSmudge
} else {
reflectionColWithSmudge
}
}
}
}
println(part(withSmudge = false))
println(part(withSmudge = true))
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 4,408 | adventofcode-2023 | MIT License |
src/main/kotlin/day11/Day11.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day11
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day11/Day11.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 11 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Monkey(
val initialItems: List<Long>,
val operation: (Long) -> Long,
val condition: Long,
val consequent: Int,
val alternate: Int,
)
private fun List<String>.toMonkey(): Monkey {
val lines = filter { it.startsWith(" ") }
val initialItems = lines[0]
.substringAfterLast(": ")
.split(", ")
.map(String::toLong)
val (op, rhs) = lines[1]
.split(" ")
.takeLast(2)
val operator = when (op) {
"*" -> { a: Long, b: Long -> a * b }
"+" -> { a: Long, b: Long -> a + b }
else -> error("Invalid operator: '$op'")
}
val operation = if (rhs == "old") { n: Long ->
operator(n, n)
} else { n: Long ->
operator(n, rhs.toLong())
}
val condition = lines[2]
.substringAfterLast(" ")
.toLong()
val consequent = lines[3]
.substringAfterLast(" ")
.toInt()
val alternate = lines[4]
.substringAfterLast(" ")
.toInt()
return Monkey(
initialItems, operation, condition, consequent, alternate
)
}
@Suppress("SameParameterValue")
private fun parse(path: String): List<Monkey> =
File(path)
.readLines()
.chunked(7)
.map { it.toMonkey() }
private fun List<Monkey>.solve(rounds: Int, transform: (Long) -> Long): Long {
val items = map { it.initialItems.toMutableList() }
val interactions = Array(size) { 0L }
repeat(rounds) {
for ((i, monkey) in withIndex()) {
for (item in items[i]) {
val worry = transform(monkey.operation(item))
val target = if (worry % monkey.condition == 0L) {
monkey.consequent
} else {
monkey.alternate
}
items[target].add(worry)
}
interactions[i] += items[i].size.toLong()
items[i].clear()
}
}
return interactions
.sortedArrayDescending()
.take(2)
.reduce(Long::times)
}
private fun part1(monkeys: List<Monkey>): Long {
return monkeys.solve(rounds = 20) { it / 3L }
}
private fun part2(monkeys: List<Monkey>): Long {
val test = monkeys
.map(Monkey::condition)
.reduce(Long::times)
return monkeys.solve(rounds = 10_000) { it % test }
}
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 2,704 | advent-of-code-2022 | MIT License |
src/Day09.kt | punx120 | 573,421,386 | false | {"Kotlin": 30825} | import java.lang.RuntimeException
import kotlin.math.abs
fun main() {
fun moveHead(pos : Pair<Int, Int>, direction : Pair<Int, Int>) : Pair<Int, Int> {
return Pair(pos.first + direction.first, pos.second + direction.second)
}
fun moveTail(hp: Pair<Int, Int>, tp: Pair<Int, Int>): Pair<Int, Int> {
if (abs(hp.first - tp.first) < 2 && abs(hp.second - tp.second) < 2)
return tp
return if (hp.first == tp.first) { // Same y axis
val second = if (tp.second < hp.second) hp.second -1 else hp.second +1
Pair(hp.first, second)
} else if (hp.second == tp.second) { // same x axis
val first = if (tp.first < hp.first) hp.first -1 else hp.first +1
Pair(first, hp.second)
} else {
val first = if (tp.first < hp.first) tp.first + 1 else tp.first - 1
val second = if (tp.second < hp.second) tp.second + 1 else tp.second -1
Pair(first, second)
}
}
fun part1(input: List<String>): Int {
val position = mutableSetOf<Pair<Int, Int>>()
var hp = Pair(0, 0)
var tp = Pair(0, 0)
for (line in input) {
val dir = when (line[0]) {
'R' -> Pair(1, 0)
'L' -> Pair(-1, 0)
'U' -> Pair(0, 1)
'D' -> Pair(0, -1)
else -> throw RuntimeException("invalid $line")
}
val steps = line.substring(2, line.length).toInt()
for (i in 0 until steps) {
hp = moveHead(hp, dir)
tp = moveTail(hp, tp)
position.add(tp)
}
}
return position.size
}
fun part2(input: List<String>): Int {
val position = mutableSetOf<Pair<Int, Int>>()
val ropes = Array(10) { _ -> Pair(0, 0)}
for (line in input) {
val dir = when (line[0]) {
'R' -> Pair(1, 0)
'L' -> Pair(-1, 0)
'U' -> Pair(0, 1)
'D' -> Pair(0, -1)
else -> throw RuntimeException("invalid $line")
}
val steps = line.substring(2, line.length).toInt()
for (i in 0 until steps) {
ropes[0] = moveHead(ropes[0], dir)
for (j in 1 until 10) {
ropes[j] = moveTail(ropes[j - 1], ropes[j])
}
position.add(ropes[9])
}
}
return position.size
}
val testInput = readInput("Day09_test")
println(part1(testInput))
println(part2(testInput))
println(part2(readInput("Day09_test2")))
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | eda0e2d6455dd8daa58ffc7292fc41d7411e1693 | 2,758 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day04.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 4 - Giant Squid
* Problem Description: http://adventofcode.com/2021/day/4
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day4/
*/
package com.ginsberg.advent2021
typealias BingoBoard = List<List<Int>>
class Day04(input: List<String>) {
private val draws: List<Int> = input.first().split(",").map { it.toInt() }
private val boards: Set<BingoBoard> = parseInput(input)
fun solvePart1(): Int {
val drawn = draws.take(4).toMutableSet()
return draws.drop(4).firstNotNullOf { draw ->
drawn += draw
boards.firstOrNull { it.isWinner(drawn) }?.let { winner ->
draw * winner.sumUnmarked(drawn)
}
}
}
fun solvePart2(): Int {
val drawn = draws.toMutableSet()
return draws.reversed().firstNotNullOf { draw ->
drawn -= draw
boards.firstOrNull { !it.isWinner(drawn) }?.let { winner ->
draw * (winner.sumUnmarked(drawn) - draw)
}
}
}
private fun BingoBoard.isWinner(draws: Set<Int>) =
this.any { row -> row.all { it in draws } } ||
(0..4).any { col -> this.all { row -> row[col] in draws } }
private fun BingoBoard.sumUnmarked(draws: Set<Int>): Int =
this.sumOf { row ->
row.filterNot { it in draws }.sum()
}
private fun parseInput(input: List<String>): Set<BingoBoard> =
input
.asSequence()
.drop(1)
.filter { it.isNotEmpty() }
.chunked(5)
.map { parseSingleBoard(it) }
.toSet()
private fun parseSingleBoard(input: List<String>): BingoBoard =
input.map { row ->
row.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 1,879 | advent-2021-kotlin | Apache License 2.0 |
src/Day09.kt | ivancordonm | 572,816,777 | false | {"Kotlin": 36235} | import kotlin.math.absoluteValue
fun main() {
fun part1(input: List<String>): Int {
var h = Pair(0, 0)
var t = Pair(0, 0)
val visited = mutableSetOf(t)
for (line in input) {
val (direction, steps) = line.split(" ")
for (step in 1..steps.toInt()) {
val prev = h
when (direction) {
"U" -> h = h.first + 1 to h.second
"D" -> h = h.first - 1 to h.second
"R" -> h = h.first to h.second + 1
"L" -> h = h.first to h.second - 1
}
if (!t.isTouching(h)) {
t = prev
visited.add(t)
}
}
}
return visited.size
}
fun printBoard(knots: MutableList<Pair<Int, Int>>) {
for (row in (0..20).reversed()) {
for (col in 0..25) {
if (Pair(row, col) in knots) print("${knots.indexOf(Pair(row, col))}")
else print(".")
}
println()
}
println()
}
fun printTailBoard(visited: MutableSet<Pair<Int, Int>>) {
for (row in (0..20).reversed()) {
for (col in 0..25) {
if (Pair(row, col) in visited) print("#")
else print(".")
}
println()
}
println()
}
fun part2(input: List<String>): Int {
val knots = MutableList(10) { 5 to 11 }
val visited = mutableSetOf(5 to 11)
// printBoard(knots)
for (line in input) {
val (direction, steps) = line.split(" ")
for (step in 1..steps.toInt()) {
when (direction) {
"U" -> knots[0] = knots[0].first + 1 to knots[0].second
"D" -> knots[0] = knots[0].first - 1 to knots[0].second
"R" -> knots[0] = knots[0].first to knots[0].second + 1
"L" -> knots[0] = knots[0].first to knots[0].second - 1
}
// printBoard(knots)
if (!knots[1].isTouching(knots.first())) {
for (index in knots.indices.drop(1)) {
if (!knots[index].isTouching(knots[index - 1])) {
if (knots[index].isDiagonal(knots[index - 1])) {
knots[index] = listOf(
1 to 1,
1 to -1,
-1 to 1,
-1 to -1
).map { it.first + knots[index].first to it.second + knots[index].second }
.first { p -> p.isTouching(knots[index - 1]) }
} else {
knots[index] = listOf(
1 to 0,
0 to -1,
0 to 1,
-1 to 0
).map { it.first + knots[index].first to it.second + knots[index].second }
.first { p -> p.isTouching(knots[index - 1]) }
}
}
}
visited.add(knots.last())
}
// printBoard(knots)
}
}
// printTailBoard(visited)
return visited.size
}
val testInput = readInput("Day09_test")
val testInput2 = readInput("Day09_test2")
val input = readInput("Day09")
println(part1(testInput))
check(part1(testInput) == 13)
println(part1(input))
println(part2(testInput2))
check(part2(testInput2) == 36)
println(part2(input))
}
private fun Pair<Int, Int>.isTouching(h: Pair<Int, Int>) =
(h.first - first).absoluteValue <= 1 && (h.second - second).absoluteValue <= 1
private fun Pair<Int, Int>.isDiagonal(h: Pair<Int, Int>) =
h.first != first && h.second != second
| 0 | Kotlin | 0 | 2 | dc9522fd509cb582d46d2d1021e9f0f291b2e6ce | 4,081 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/day11/Day11.kt | Arch-vile | 317,641,541 | false | null | package day11
import readFile
fun straightLineOffsets(xOffset: Int, yOffset: Int): Sequence<Pair<Int, Int>> {
var x = xOffset
var y = yOffset
return sequence {
while (true) {
yield(Pair(x, y))
x += xOffset
y += yOffset
}
}
}
fun main(args: Array<String>) {
val input = readFile("./src/main/resources/day11Input.txt")
val width = input[0].length
val height = input.size
var lobby = input.joinToString("").toCharArray().toList()
var newLobby = lobby
do {
lobby = newLobby
newLobby = lobby
.mapIndexed { index, char -> transform(char, index, lobby, width, height) }
} while (!areEqual(lobby, newLobby))
println(
newLobby.filter { it == '#' }.count()
)
}
private fun transform(char: Char, index: Int, lobby: List<Char>, width: Int, height: Int): Char {
if (char == 'L') {
if (allSurroundingsEmpty(index, lobby, width, height)) {
return '#'
}
} else if (char == '#') {
if (hasNeighbourgs(index, lobby, width, height)) {
return 'L'
}
}
return char
}
fun areEqual(lobby: List<Char>, newLobby: List<Char>) =
lobby.toCharArray() contentEquals newLobby.toCharArray()
fun hasNeighbourgs(index: Int, lobby: List<Char>, width: Int, height: Int): Boolean {
val lines: List<List<Int>> = getSurrounds(index, width, height)
var count =
lines.mapNotNull { line ->
line
.map { lobby[it] }
.firstOrNull { it != '.' }
}
.filter { it == '#' }
.count()
return count >= 5
}
fun allSurroundingsEmpty(index: Int, lobby: List<Char>, width: Int, height: Int): Boolean {
val lines: List<List<Int>> = getSurrounds(index, width, height)
for (line in lines) {
for (coord in line) {
if (lobby[coord] == 'L')
break
if (lobby[coord] == '#')
return false
}
}
return true
}
private fun getSurrounds(index: Int, width: Int, height: Int): List<List<Int>> {
return listOf(
straightLineIndexes(index, width, height, -1, -1),
straightLineIndexes(index, width, height, 0, -1),
straightLineIndexes(index, width, height, 1, -1),
straightLineIndexes(index, width, height, -1, 0),
straightLineIndexes(index, width, height, 1, 0),
straightLineIndexes(index, width, height, -1, 1),
straightLineIndexes(index, width, height, 0, 1),
straightLineIndexes(index, width, height, 1, 1)
)
}
private fun straightLineIndexes(index: Int, width: Int, height: Int, xOffset: Int, yOffset: Int): List<Int> {
return straightLineOffsets(xOffset, yOffset)
.map {
relativeTo(index, width, height, it.first, it.second)
}.takeWhile { it != null }.toList() as List<Int>
}
fun relativeTo(index: Int, width: Int, height: Int, xOffset: Int, yOffset: Int): Int? {
var y = index / width
var x = index - y * width
y += yOffset
x += xOffset
return if (x < 0 || x >= width || y < 0 || y >= height)
null
else
x + y * width
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 2,936 | adventOfCode2020 | Apache License 2.0 |
src/Day03.kt | kipwoker | 572,884,607 | false | null |
fun main() {
fun getPriority(ch: Char): Long {
if (ch in 'A'..'Z') {
return ch - 'A' + 27L
}
return ch - 'a' + 1L
}
fun part1(input: List<String>): Long {
return input.sumOf { line ->
line
.chunkedSequence(line.length / 2)
.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.sumOf {
getPriority(it)
}
}
}
fun part2(input: List<String>): Long {
return input
.chunked(3)
.sumOf { group ->
group
.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.sumOf {
getPriority(it)
}
}
}
check(getPriority('a') == 1L)
check(getPriority('z') == 26L)
check(getPriority('A') == 27L)
check(getPriority('Z') == 52L)
val testInput = readInput("Day03_test")
check(part1(testInput) == 157L)
check(part2(testInput) == 70L)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 1,209 | aoc2022 | Apache License 2.0 |
src/com/ajithkumar/aoc2022/Day07.kt | ajithkumar | 574,372,025 | false | {"Kotlin": 21950} | package com.ajithkumar.aoc2022
import com.ajithkumar.utils.*
sealed interface FileSystemNode {
fun size() :Int
}
class File(val name: String, private val size: Int): FileSystemNode {
override fun size(): Int = size
}
class Directory(val name: String, val children: MutableList<FileSystemNode>): FileSystemNode {
lateinit var parent: Directory
private var size: Int = 0
fun allDirectories(): List<Directory> {
val result = mutableListOf<Directory>()
result.add(this)
val childrenResult = this.children.filterIsInstance<Directory>()
.flatMap { it.allDirectories() }
result.addAll(childrenResult)
return result
}
fun addChildren(node: FileSystemNode) {
children.add(node)
}
fun findDirectory(name: String): Directory {
return children.filter { it is Directory && it.name == name }[0] as Directory
}
override fun size(): Int {
if(size > 0) return size
size = children.sumOf { it.size() }
return size
}
}
class CommandLineInterpreter(private val input: List<String>) {
private lateinit var rootDirectory: Directory
private lateinit var currentDirectory: Directory
fun parse(): Directory {
input.forEach {
when {
"$ cd /" in it -> setRootDirectory()
"$ cd .." in it -> currentDirectory = currentDirectory.parent
"$ cd" in it -> {
val (_prompt,_cmd, dirName) = it.split(" ")
val directory = currentDirectory.findDirectory(dirName)
currentDirectory = directory
}
"$ ls" in it -> {}
"dir" in it -> {
val (_cmd, dirName) = it.split(" ")
addDirToChildren(dirName)
}
else -> {
val (size,name) = it.split(" ")
addFileToChildren(name, size.toInt())
}
}
}
return rootDirectory
}
private fun setRootDirectory() {
rootDirectory = Directory("/", mutableListOf())
rootDirectory.parent = rootDirectory
currentDirectory = rootDirectory
}
private fun addDirToChildren(name: String) {
val newDir = Directory(name, mutableListOf())
newDir.parent = currentDirectory
currentDirectory.addChildren(newDir)
}
private fun addFileToChildren(name: String, size: Int) {
currentDirectory.addChildren(File(name, size))
}
}
fun main() {
fun buildDirectoryStructure(input: List<String>): Directory {
return CommandLineInterpreter(input).parse()
}
fun part1(input: List<String>): Int {
val rootDirectory = buildDirectoryStructure(input)
return rootDirectory.allDirectories()
.filter { it.size() <= 100_000 }
.sumOf { it.size() }
}
fun part2(input: List<String>): Int {
val totalSpace = 70_000_000
val requiredSpace = 30_000_000
val rootDirectory = buildDirectoryStructure(input)
val minSizeToDelete = requiredSpace - (totalSpace - rootDirectory.size())
return rootDirectory.allDirectories()
.filter { it.size() >= minSizeToDelete }
.minByOrNull { directory -> directory.size() }!!
.size()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f95b8d1c3c8a67576eb76058a1df5b78af47a29c | 3,651 | advent-of-code-kotlin-template | Apache License 2.0 |
src/Day05.kt | raneric | 573,109,642 | false | {"Kotlin": 13043} | var stackSourceIndex = -1
var stackDestinationIndex = -1
fun main() {
fun part1(input: List<String>): String {
val stackList = getStackList(input)
val moveIndex = stackList.size + 2
val procedure = getMoveList(moveIndex, input)
val stackNb = input[moveIndex - 2].trim().split(" ").last().toInt()
val reversedData = transpose(stackList, stackNb)
for (move in procedure) {
stackSourceIndex = move[1] - 1
stackDestinationIndex = move[2] - 1
for (i in 1..move[0]) {
reversedData[stackDestinationIndex].add(0, reversedData[stackSourceIndex].removeFirst())
}
}
return reversedData.joinToString(separator = "") { it.first().trim().removeBracket() }
}
fun part2(input: List<String>): String {
val stackList = getStackList(input)
val moveIndex = stackList.size + 2
val procedure = getMoveList(moveIndex, input)
val stackNb = input[moveIndex - 2].trim().split(" ").last().toInt()
val reversedData = transpose(stackList, stackNb)
for (move in procedure) {
stackSourceIndex = move[1] - 1
stackDestinationIndex = move[2] - 1
val stackToMove = reversedData[stackSourceIndex].take(move[0])
reversedData[stackDestinationIndex].addAll(0, stackToMove)
for (i in stackToMove.indices) {
reversedData[stackSourceIndex].removeFirst()
}
}
return reversedData.joinToString(separator = "") { it.first().trim().removeBracket() }
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
fun getStackList(input: List<String>): ArrayList<ArrayList<String>> {
val stackList = ArrayList<ArrayList<String>>()
for (i in input.indices) {
if (input[i].startsWith(" 1 ")) {
break
}
stackList.add(input[i].extraDataToArray())
}
return stackList
}
fun String.extraDataToArray(): ArrayList<String> {
return this.chunked(4) as ArrayList<String>
}
fun getMoveList(moveIndex: Int, input: List<String>): List<List<Int>> {
return input.subList(moveIndex, input.size).map {
it.extractProcedure()
}
}
fun String.extractProcedure(): List<Int> {
val regex = "-?[0-9]+(\\.[0-9]+)?".toRegex()
val result = this.split(" ").filter { regex.matches(it) }.map { it.toInt() }
return result
}
fun transpose(stackSource: ArrayList<ArrayList<String>>, width: Int): ArrayList<ArrayList<String>> {
val transposed = ArrayList<ArrayList<String>>()
for (i in 0 until width) {
val tempData = ArrayList<String>()
for (j in stackSource.indices) {
if (i == stackSource[j].size) continue
if (stackSource[j][i].startsWith(" ")) {
continue
} else {
tempData.add(stackSource[j][i])
}
}
transposed.add(tempData)
}
return transposed
}
fun String.removeBracket(): String {
return this.replace("[", "").replace("]", "")
} | 0 | Kotlin | 0 | 0 | 9558d561b67b5df77c725bba7e0b33652c802d41 | 3,104 | aoc-kotlin-challenge | Apache License 2.0 |
src/main/aoc2019/Day24.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2019
import kotlin.math.pow
class Day24(input: List<String>) {
// level 0 is same level, -1 or 1 is one lower or higher level
private data class Tile(val level: Int, val index: Int)
private val parsedInput = input.joinToString("")
.replace('.', '0')
.replace('#', '1')
.map { it.toString().toInt() }
.toIntArray()
private lateinit var adjacent: Map<Int, List<Tile>>
private val emptyGrid = IntArray(25) { 0 }
private fun adjacentBugs(level: Int, index: Int, grids: Map<Int, IntArray>): Int {
// Sum up the number of bugs on all adjacent tiles
return (adjacent[index] ?: error("$index has no adjacent tiles")).sumOf { adjacentTile ->
grids.getOrDefault(level + adjacentTile.level, emptyGrid)[adjacentTile.index]
}
}
private fun tick(grids: Map<Int, IntArray>): Map<Int, IntArray> {
val noEmpty = grids.filterNot { it.value.contentEquals(emptyGrid) }
val min = noEmpty.keys.minOrNull()!! - 1
val max = noEmpty.keys.maxOrNull()!! + 1
val nextState = mutableMapOf<Int, IntArray>()
for (level in min..max) {
val nextLevel = IntArray(25)
for (index in 0..24) {
val adjacent = adjacentBugs(level, index, grids)
val newValue = if (grids.getOrDefault(level, emptyGrid)[index] == 1) {
// A bug dies unless there is exactly one bug adjacent to it
if (adjacent == 1) 1 else 0
} else {
// An empty space becomes infested if exactly one or two bugs are adjacent to it.
if ((1..2).contains(adjacent)) 1 else 0
}
nextLevel[index] = newValue
}
nextState[level] = nextLevel
}
return nextState
}
private fun generateAdjacencyMapPart1(): Map<Int, List<Tile>> {
val adjacentTiles = mutableMapOf<Int, List<Tile>>()
for (it in 0..24) {
val adjacent = mutableListOf<Tile>()
// Up, down, left, right
if (it in 5..24) adjacent.add(Tile(0, it - 5))
if (it in 0..19) adjacent.add(Tile(0, it + 5))
if ((it % 5) != 0) adjacent.add(Tile(0, it - 1))
if ((it % 5) != 4) adjacent.add(Tile(0, it + 1))
adjacentTiles[it] = adjacent
}
return adjacentTiles
}
fun solvePart1(): Int {
adjacent = generateAdjacencyMapPart1()
var ret = mapOf(0 to parsedInput)
val seen = mutableSetOf<Int>()
var diversity: Int
while (true) {
ret = tick(ret)
diversity = ret.getValue(0).withIndex().sumOf { 2.0.pow(it.index).toInt() * it.value }
if (!seen.add(diversity)) {
break
}
}
return diversity
}
private fun generateAdjacencyMapPart2(): Map<Int, List<Tile>> {
val adjacentTiles = mutableMapOf<Int, List<Tile>>()
for (it in 0..24) {
if (it == 12) {
// Center square is actually a separate level, so it's handled
// specially. Mark it as adjacent to no one
adjacentTiles[it] = listOf()
continue
}
val adjacent = mutableListOf<Tile>()
// Up
when (it) {
in 0..4 -> adjacent.add(Tile(1, 7))
17 -> (20..24).forEach { i -> adjacent.add(Tile(-1, i)) }
else -> adjacent.add(Tile(0, it - 5))
}
// Down
when (it) {
in 20..24 -> adjacent.add(Tile(1, 17))
7 -> (0..4).forEach { i -> adjacent.add(Tile(-1, i)) }
else -> adjacent.add(Tile(0, it + 5))
}
// Left
when {
(it % 5) == 0 -> adjacent.add(Tile(1, 11))
it == 13 -> listOf(4, 9, 14, 19, 24).forEach { i -> adjacent.add(Tile(-1, i)) }
else -> adjacent.add(Tile(0, it - 1))
}
// Right
when {
(it % 5) == 4 -> adjacent.add(Tile(1, 13))
it == 11 -> listOf(0, 5, 10, 15, 20).forEach { i -> adjacent.add(Tile(-1, i)) }
else -> adjacent.add(Tile(0, it + 1))
}
adjacentTiles[it] = adjacent
}
return adjacentTiles
}
fun solvePart2(duration: Int): Int {
adjacent = generateAdjacencyMapPart2()
var grids = mapOf(0 to parsedInput)
repeat(duration) {
grids = tick(grids)
}
return grids.values.sumOf { it.sum() }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 4,701 | aoc | MIT License |
src/Day04.kt | hanmet | 573,490,488 | false | {"Kotlin": 9896} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (i in input) {
var leftContainsRight = true
var rightContainsLeft = true
val sections = i.split(",")
.map { it.split("-") }
val left = sections[0][0].toInt()..sections[0][1].toInt()
val right = sections[1][0].toInt()..sections[1][1].toInt()
left.forEach{
if(!right.contains(it)) {
rightContainsLeft = false
}
}
right.forEach{
if(!left.contains(it)) {
leftContainsRight = false
}
}
if (leftContainsRight || rightContainsLeft) {
sum++
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (i in input) {
var overlap = false
val sections = i.split(",")
.map { it.split("-") }
val left = sections[0][0].toInt()..sections[0][1].toInt()
val right = sections[1][0].toInt()..sections[1][1].toInt()
left.forEach{
if(right.contains(it)) {
overlap = true
}
}
if (overlap) {
sum++
}
}
return sum
}
// 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 | e4e1722726587639776df86de8d4e325d1defa02 | 1,642 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day4.kt | clechasseur | 435,726,930 | false | {"Kotlin": 315943} | package io.github.clechasseur.adventofcode2021
import io.github.clechasseur.adventofcode2021.data.Day4Data
object Day4 {
private val data = Day4Data.data
fun part1(): Int {
val game = Game(data.lines())
for (draw in game.draws) {
game.cards.forEach { it.mark(draw) }
val winner = game.cards.find { it.won }
if (winner != null) {
return winner.score(draw)
}
}
error("No winner!")
}
fun part2(): Int {
val game = Game(data.lines())
for (draw in game.draws) {
game.cards.forEach { it.mark(draw) }
val losers = game.cards.filter { !it.won }
if (losers.size == 1) {
val loser = losers.first()
for (loserDraw in game.draws) {
loser.mark(loserDraw)
if (loser.won) {
return loser.score(loserDraw)
}
}
}
}
error("No winner!")
}
private val lineRegex = """^(..) (..) (..) (..) (..)$""".toRegex()
private class Square(val value: Int, var marked: Boolean = false)
private class Card(lines: List<String>) {
val squares: List<List<Square>> = lines.map { lineNumbers(it) }
val won: Boolean
get() = squares.any { it.filled() } || columns().any { it.filled() }
fun mark(draw: Int) {
squares.forEach { line ->
line.forEach {
if (it.value == draw) {
it.marked = true
}
}
}
}
fun score(lastDraw: Int) = lastDraw * squares.flatten().filter { !it.marked }.sumOf { it.value }
private fun lineNumbers(line: String): List<Square> {
val match = lineRegex.matchEntire(line) ?: error("Wrong line format: $line")
return match.groupValues.drop(1).map { Square(it.trim().toInt()) }
}
private fun columns(): List<List<Square>> = squares[0].indices.map { i -> squares.map { it[i] } }
private fun List<Square>.filled() = all { it.marked }
}
private class Game(lines: List<String>) {
val draws: List<Int> = lines[0].split(',').map { it.toInt() }
val cards: List<Card> = lines.drop(2).filter { it.isNotBlank() }.chunked(5).map { Card(it) }
}
}
| 0 | Kotlin | 0 | 0 | 4b893c001efec7d11a326888a9a98ec03241d331 | 2,415 | adventofcode2021 | MIT License |
src/cn/leetcode/codes/simple18/Simple18.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple18
import cn.leetcode.codes.out
import java.util.*
fun main() {
// val nums = intArrayOf(1, 0, -1, 0, -2, 2)
val nums = intArrayOf(-2,-1,-1,1,1,2,2)
// val nums = intArrayOf(1,0,-1,0,-2,2)
// val s = fourSum(nums, 0) // [[-2, -1, 1, 2], [-1, -1, 1, 1]]
val s2 = Simple18_2().fourSum(nums,0) // [[-2, -1, 1, 2], [-2, -1, 1, 2], [-2, -1, 1, 2], [-2, -1, 1, 2], [-1, -1, 1, 1]]
// out("s = $s")
out("s2 = $s2")
}
/*
18. 四数之和
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
*/
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val list = mutableListOf<List<Int>>()
if (nums.size < 4) {
return list
}
//排序
Arrays.sort(nums)
val len = nums.size
for (i in 0 until len - 3) {
//如果和本次循环数据 和上次数据一样 没有必要再次循环
if (i > 0 && nums[i] == nums[i - 1]) {
continue
}
//前三个值都大于给定值 后面没有必要再比较
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
break
}
//后三个值小于给定值 直接开始下一次循环即可
if (nums[i] + nums[len - 3] + nums[len - 2] + nums[len - 1] < target) {
continue
}
for (j in i + 1 until len - 2) {
//如果和本次循环数据 和上次数据一样 没有必要再次循环
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue
}
if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
break
}
if (nums[i] + nums[j] + nums[len - 2] + nums[len - 1] < target) {
continue
}
//双指针
var l = j + 1
var r = nums.size - 1
while (l < r) {
val sum = nums[i] + nums[j] + nums[l] + nums[r]
when {
sum == target -> {
list.add(listOf(nums[i], nums[j], nums[l], nums[r]))
//去重
while (l < r && nums[l] == nums[l + 1]) {
l++
}
l++
//去重
while (l < r && nums[r] == nums[r - 1]) {
r--
}
r--
}
sum < target -> {
l++
}
sum > target -> {
r--
}
}
}
}
}
return list
}
| 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 3,124 | LeetCodeSimple | Apache License 2.0 |
src/Day09.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
import kotlin.math.sin
data class Pos(val x: Int, val y: Int){
fun move(direction: Char):Pos {
return when(direction){
'R' -> copy(x = x + 1)
'L' -> copy(x= x - 1)
'U' -> copy(y = y - 1)
'D' -> copy(y = y + 1)
else -> Pos(0,0)
}
}
fun follow(head: Pos, direction: Char):Pos{
val dx = head.x - x
val dy = head.y - y
val d = Pos(dx, dy).move(direction)
if (abs(d.x) <= 1 && abs(d.y) <= 1) return this
return copy(x = x + d.x.sign, y = y + d.y.sign)
}
fun follow(newHead: Pos):Pos{
val dx = newHead.x - x
val dy = newHead.y - y
if (abs(dx) <= 1 && abs(dy) <= 1) return this
return copy(x = x + dx.sign, y = y + dy.sign)
}
}
fun main() {
fun part1(input: List<String>): Int {
var head = Pos(0,0)
var tail = Pos(0,0)
return input.fold(mutableSetOf<Pos>(tail)){
acc, s ->
val direction = s.first()
val repeat = s.split( " ").last().toInt()
repeat(repeat){
// println("$head - $tail")
head = head.move(direction)
tail = tail.follow(head)
acc.add(tail)
}
acc
}.size
}
fun part2(input: List<String>): Int {
var head = Pos(0,0)
var tail = Pos(0,0)
val posArray = Array<Pos>(8){Pos(0,0)}
return input.fold(mutableSetOf<Pos>(tail)){
acc, s ->
val direction = s.first()
val repeat = s.split( " ").last().toInt()
repeat(repeat){
// println("$head - $tail")
head = head.move(direction)
posArray[0] = posArray[0].follow(head)
(1..7).forEach {
posArray[it] = posArray[it].follow(posArray[it-1])
}
tail = tail.follow(posArray[7])
acc.add(tail)
}
acc
}.size
}
var input = readInput("Test09")
println(part1(input))
println(part2(input))
input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 2,311 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/aoc2022/day07/AoC07.kt | Saxintosh | 576,065,000 | false | {"Kotlin": 30013} | package aoc2022.day07
import readLines
interface AnElement {
val name: String
var size: Int
}
class AFile(
override val name: String,
override var size: Int,
) : AnElement
class ADir(
override val name: String,
) : AnElement {
override var size: Int = 0
private val content = HashMap<String, AnElement>()
var parent: ADir? = null
private set
private val localDirs get() = content.values.filterIsInstance(ADir::class.java)
fun getAllDirectories(): List<ADir> = localDirs.flatMap { it.getAllDirectories() } + localDirs
fun addFile(name: String, size: Int) {
content[name] = AFile(name, size)
addChildSize(size)
}
private fun addChildSize(size: Int) {
this.size += size
parent?.addChildSize(size)
}
fun createDir(name: String): ADir = ADir(name).also {
it.parent = this
content[name] = it
}
fun getDir(name: String) = content[name] as ADir
}
class Disk {
val root = ADir("/")
private var cwd = root
fun cd(name: String) {
cwd = when (name) {
"/" -> root
".." -> cwd.parent!!
else -> cwd.getDir(name)
}
}
fun processCmd(cmd: String) {
val parts = cmd.split(" ")
val (p1, p2) = parts
when (p1) {
"$" -> if (p2 == "cd") cd(parts[2])
"dir" -> createDir(p2)
else -> addFile(p2, p1.toInt())
}
}
fun createDir(name: String) = cwd.createDir(name)
fun addFile(name: String, size: Int) = cwd.addFile(name, size)
fun findSmallDir(limit: Int) = root.getAllDirectories().filter { it.size <= limit }.sumOf { it.size }
companion object {
fun from(lines: List<String>) = Disk().apply {
lines.forEach(::processCmd)
}
}
}
fun main() {
fun part1(lines: List<String>): Int {
val disk = Disk.from(lines)
return disk.findSmallDir(100000)
}
fun part2(lines: List<String>): Int {
val disk = Disk.from(lines)
val free = 70000000 - disk.root.size
val needed = 30000000 - free
val l = disk.root.getAllDirectories().sortedBy { it.size }.first { it.size >= needed }
return l.size
}
readLines(95437, 24933642, ::part1, ::part2)
}
| 0 | Kotlin | 0 | 0 | 877d58367018372502f03dcc97a26a6f831fc8d8 | 2,018 | aoc2022 | Apache License 2.0 |
src/main/kotlin/days/day05.kt | josergdev | 573,178,933 | false | {"Kotlin": 20792} | package days
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
fun parseCrates(crates: String) = crates.split("\n").dropLast(1)
.map { it.windowed(3,4) }
.map { it.map { s -> s.trim(' ', '[', ']') } }
.foldRight(mapOf<Int, Stack<String>>()) { line, cratesAcc ->
line.foldIndexed(cratesAcc) { index, acc, crate ->
if (crate.isNotBlank())
acc.toMutableMap().let { map ->
map.getOrDefault(index + 1, Stack())
.also { it.push(crate) }
.also { map[index + 1] = it }
map.toMap()
}
else acc
}
}
fun parseMoves(moves: String) = moves.split("\n")
.map { it.replace("move ", "").replace(" from ", " ").replace(" to ", " ") }
.map { it.split(" ").map(String::toInt) }
fun Map<Int, Stack<String>>.move(quantity: Int, from: Int, to: Int) =
this.toMutableMap().let { stacks ->
repeat(quantity) {
stacks[to]!!.push(stacks[from]!!.pop())
}
stacks.toMap()
}
fun Map<Int, Stack<String>>.peekString() = this.entries.sortedBy { it.key }.joinToString("") { it.value.peek() }
fun day5part1() = Files.readString(Paths.get("input/05.txt")).split("\n\n")
.let { parseCrates(it[0]) to parseMoves(it[1]) }
.let { (crates, moves) -> moves.fold(crates) { acc, move -> acc.move(move[0], move[1], move[2]) } }
.peekString()
fun Map<Int, Stack<String>>.move2(quantity: Int, from: Int, to: Int) =
this.toMutableMap().let {
(1..quantity)
.fold(listOf<String>()) { acc, _ -> (acc + it[from]!!.pop()) }
.reversed().forEach { crate -> it[to]!!.push(crate) }
it.toMap()
}
fun day5part2() = Files.readString(Paths.get("input/05.txt")).split("\n\n")
.let { parseCrates(it[0]) to parseMoves(it[1]) }
.let { (crates, moves) -> moves.fold(crates) { acc, move -> acc.move2(move[0], move[1], move[2]) } }
.peekString() | 0 | Kotlin | 0 | 0 | ea17b3f2a308618883caa7406295d80be2406260 | 2,012 | aoc-2022 | MIT License |
day4/src/main/kotlin/com/lillicoder/adventofcode2023/day4/Day4.kt | lillicoder | 731,776,788 | false | {"Kotlin": 98872} | package com.lillicoder.adventofcode2023.day4
import kotlin.math.pow
fun main() {
val day4 = Day4()
val cards = ScratchcardParser().parse("input.txt")
println("The total score of the given scratchcards is ${day4.part1(cards)}.")
println("The total count of cards, including clones, is ${day4.part2(cards)}.")
}
class Day4 {
fun part1(cards: List<Scratchcard>) = cards.sumOf { it.score() }
fun part2(cards: List<Scratchcard>) = ScratchcardCloneCalculator().countWithWinners(cards)
}
/**
* Represents a single scratchcard.
* @param winningNumbers Numbers to match to win points.
* @param playNumbers Numbers played.
*/
data class Scratchcard(
val id: Int,
val winningNumbers: List<Int>,
val playNumbers: List<Int>,
) {
/**
* Gets the number of winning numbers that match the play numbers.
* @return Number of matches.
*/
fun matches() = winningNumbers.count { it in playNumbers }
/**
* Gets the score for this scratchcard.
* @return Score.
*/
fun score() =
when (val matches = matches()) {
0 -> 0
else -> 2.0.pow(matches - 1).toInt()
}
}
/**
* Parses scratchcard records into a list of [Scratchcard].
*/
class ScratchcardParser {
/**
* Parses the file with the given filename and returns a list of [Scratchcard].
* @param filename Name of the file to parse.
* @return List of scratchcards.
*/
fun parse(filename: String) = parse(javaClass.classLoader.getResourceAsStream(filename)!!.reader().readLines())
/**
* Parses the given raw scratchcard input to an equivalent list of [Scratchcard].
* @param raw Raw list of scratchcards.
* @return List of scratchcards.
*/
fun parse(raw: List<String>) = raw.map { parseScratchcard(it) }
/**
* Parses a [Scratchcard] from the given raw scratchcard input.
* @param raw Raw scratchcard.
* @return Scratchcard.
*/
private fun parseScratchcard(raw: String): Scratchcard {
val id = raw.substringBefore(":").substringAfter("Card ").trim().toInt()
val blocks = raw.substringAfter(": ").split(" | ")
// Single digits have an extra space, so when we split we'll end up with some
// elements as an empty string, so drop those before attempting to cast
val winning = blocks[0].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
val played = blocks[1].split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
return Scratchcard(id, winning, played)
}
}
/**
* Calculator for counting the total number of scratchcards, including winning copies.
*/
class ScratchcardCloneCalculator {
/**
* Counts the total number of scratchcards represented by the given list of [Scratchcard], including
* cards that get copied due to having one or more matches.
* @param scratchcards Scratchcards to evaluate.\
* @return Count of scratchcards.
*/
fun countWithWinners(scratchcards: List<Scratchcard>): Int {
// We start with 1 of each card
val frequency = scratchcards.associate { it.id to 1 }.toMutableMap()
scratchcards.forEachIndexed { index, card ->
val count = frequency[card.id]!!
val matches = card.matches()
val copyIds = getCopyIds(scratchcards, index, matches)
copyIds.forEach { id -> frequency.merge(id, count, Int::plus) }
}
// All cards have been copied and their counts updated
return frequency.values.sum()
}
/**
* Gets the IDs of the scratchcards that are after the card at the given start index.
* @param scratchcards List of [Scratchcard].
* @param start Starting index.
* @return List of card IDs.
*/
private fun getCopyIds(
scratchcards: List<Scratchcard>,
start: Int,
count: Int,
) = IntRange(1, count).mapNotNull {
scratchcards.getOrNull(start + it)?.id
}
}
| 0 | Kotlin | 0 | 0 | 390f804a3da7e9d2e5747ef29299a6ad42c8d877 | 3,987 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day22.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 22 - Reactor Reboot
* Problem Description: http://adventofcode.com/2021/day/22
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day22/
*/
package com.ginsberg.advent2021
class Day22(input: List<String>) {
private val cubes: List<Cuboid> = input.map { Cuboid.of(it) }
private val part1Cube = Cuboid(true, -50..50, -50..50, -50..50)
fun solvePart1(): Long =
solve(cubes.filter { it.intersects(part1Cube) })
fun solvePart2(): Long =
solve()
private fun solve(cubesToUse: List<Cuboid> = cubes): Long {
val volumes = mutableListOf<Cuboid>()
cubesToUse.forEach { cube ->
volumes.addAll(volumes.mapNotNull { it.intersect(cube) })
if (cube.on) volumes.add(cube)
}
return volumes.sumOf { it.volume() }
}
private class Cuboid(val on: Boolean, val x: IntRange, val y: IntRange, val z: IntRange) {
fun volume(): Long =
(x.size().toLong() * y.size().toLong() * z.size().toLong()) * if (on) 1 else -1
fun intersect(other: Cuboid): Cuboid? =
if (!intersects(other)) null
else Cuboid(!on, x intersect other.x, y intersect other.y, z intersect other.z)
fun intersects(other: Cuboid): Boolean =
x.intersects(other.x) && y.intersects(other.y) && z.intersects(other.z)
companion object {
private val pattern =
"""^(on|off) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)$""".toRegex()
fun of(input: String): Cuboid {
val (s, x1, x2, y1, y2, z1, z2) = pattern.matchEntire(input)?.destructured
?: error("Cannot parse input: $input")
return Cuboid(
s == "on",
x1.toInt()..x2.toInt(),
y1.toInt()..y2.toInt(),
z1.toInt()..z2.toInt(),
)
}
}
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 2,048 | advent-2021-kotlin | Apache License 2.0 |
src/main/kotlin/g2601_2700/s2699_modify_graph_edge_weights/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2601_2700.s2699_modify_graph_edge_weights
// #Hard #Heap_Priority_Queue #Graph #Shortest_Path
// #2023_07_29_Time_1592_ms_(40.00%)_Space_65.3_MB_(60.00%)
import java.util.PriorityQueue
class Solution {
private inner class Edge(var s: Int, var d: Int, var wt: Int)
private lateinit var g: Array<ArrayList<Edge>?>
private var n = 0
private var t = 0
fun modifiedGraphEdges(
n: Int,
edges: Array<IntArray>,
source: Int,
destination: Int,
target: Int
): Array<IntArray> {
this.n = n
g = arrayOfNulls(n)
t = target
for (i in 0 until n) {
g[i] = ArrayList()
}
for (e in edges) {
val s = e[0]
val d = e[1]
val wt = e[2]
if (wt == -1) continue
g[s]!!.add(Edge(s, d, wt))
g[d]!!.add(Edge(d, s, wt))
}
val inc = shortestPath(source, destination)
if (inc != -1 && inc < target) return Array(0) { IntArray(0) }
if (inc == target) {
ntomax(edges)
return edges
}
for (e in edges) {
if (e[2] == -1) {
e[2] = 1
val s = e[0]
val d = e[1]
val wt = e[2]
g[s]!!.add(Edge(s, d, wt))
g[d]!!.add(Edge(d, s, wt))
val cost = shortestPath(source, destination)
if (cost == -1) continue
if (cost < target) {
e[2] = target - cost + 1
ntomax(edges)
return edges
}
if (cost == target) {
ntomax(edges)
return edges
}
}
}
return Array(0) { IntArray(0) }
}
private fun ntomax(edges: Array<IntArray>) {
for (e in edges) {
if (e[2] == -1) {
e[2] = 1000000000
}
}
}
private inner class Pair(var s: Int, var cost: Int) : Comparable<Pair?> {
override operator fun compareTo(other: Pair?): Int {
return cost - other!!.cost
}
}
private fun shortestPath(s: Int, d: Int): Int {
val q = PriorityQueue<Pair>()
q.add(Pair(s, 0))
val vis = BooleanArray(n)
while (q.isNotEmpty()) {
val rem = q.remove()
vis[rem.s] = true
if (rem.s == d) return rem.cost
for (e in g[rem.s]!!) {
if (!vis[e.d]) {
q.add(Pair(e.d, rem.cost + e.wt))
}
}
}
return -1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,687 | LeetCode-in-Kotlin | MIT License |
src/Day13.kt | Jintin | 573,640,224 | false | {"Kotlin": 30591} | fun main() {
class Container {
var items: MutableList<Container>? = null
var value: Int = -1
var parent: Container? = null
fun addContainer(container: Container) {
if (items == null) {
items = mutableListOf()
}
items?.add(container)
}
}
fun parse(data: String): Container {
val root = Container()
var current = root
var value = -1
data.forEach {
when (it) {
'[' -> {
val next = Container()
current.addContainer(next)
next.parent = current
current = next
}
']' -> {
if (value != -1) {
current.addContainer(Container().also { it.value = value })
}
value = -1
current = current.parent!!
}
',' -> {
if (value != -1) {
current.addContainer(Container().also { it.value = value })
}
value = -1
}
else -> {
if (value == -1) {
value = 0
}
value = value * 10 + (it - '0')
}
}
}
return root
}
fun wrap(container: Container): Container {
return Container().also {
it.items = mutableListOf(Container().also { it.value = container.value })
}
}
fun compare(left: Container?, right: Container?): Int {
if (left == null && right == null) {
return 0
}
if (left == null) {
return -1
}
if (right == null) {
return 1
}
return if (left.items == null && right.items == null) {
left.value - right.value
} else if (left.items == null) {
compare(wrap(left), right)
} else if (right.items == null) {
compare(left, wrap(right))
} else {
var index = 0
while (index < left.items!!.size && index < right.items!!.size) {
val result = compare(left.items!![index], right.items!![index])
if (result != 0) {
return result
}
index++
}
left.items!!.size - right.items!!.size
}
}
fun part1(input: List<String>): Int {
var count = 0
input.windowed(2, step = 3).forEachIndexed { index, strings ->
val left = parse(strings[0])
val right = parse(strings[1])
val result = compare(left, right)
if (result < 0) {
count += index + 1
}
}
return count
}
fun part2(input: List<String>): Int {
val two = parse("[[2]]")
val six = parse("[[6]]")
val list =
input.asSequence().filter { it.isNotEmpty() }.map { parse(it) }.plus(two).plus(six).sortedWith { a1, a2 ->
compare(a1, a2)
}.toList()
return (list.indexOfFirst { compare(it, two) == 0 } + 1) * (list.indexOfFirst { compare(it, six) == 0 } + 1)
}
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 4aa00f0d258d55600a623f0118979a25d76b3ecb | 3,444 | AdventCode2022 | Apache License 2.0 |
src/main/kotlin/Day18.kt | pavittr | 317,532,861 | false | null | import java.io.File
import java.nio.charset.Charset
fun main() {
fun calc(ops: List<String> ) : Long {
val init = ops.take(1).first().toLong()
val output = ops.drop(1).windowed(2, 2, false)
.map { Pair(it[0], it[1].toInt()) }.fold(init) {acc, op ->
when(op.first) {
"+" -> acc + op.second
"*" -> acc * op.second
else -> 0
}
}
return output
}
fun sumUp(input: String, f : (List<String>) -> Long) : Long {
var runningSum = input
val regex = Regex("\\(([^()]+)\\)")
while (regex.find(runningSum) != null) {
val thisMatch = regex.find(runningSum)
val replacement = thisMatch?.groupValues?.get(1)?.split(" ")?.let { "" + f(it) } ?: "0"
if (thisMatch != null) {
runningSum = runningSum.replaceRange(thisMatch.range, replacement)
}
}
return f(runningSum.split(" "))
}
fun part1(inputFile: String) {
val input = File(inputFile).readLines(Charset.defaultCharset())
println(input.map { sumUp(it, ::calc) }.sum())
}
fun addFirstSumUp(ops: List<String>) : Long {
var withPlusses = ops.toMutableList()
while (withPlusses.contains("+")) {
val nextPlus = withPlusses.indexOfFirst { it == "+"}
val firstOp = withPlusses[nextPlus -1].toLong()
val secondOp = withPlusses[nextPlus + 1].toLong()
withPlusses.removeAt(nextPlus - 1)
withPlusses.removeAt(nextPlus - 1)
withPlusses.removeAt(nextPlus - 1)
withPlusses.add(nextPlus-1, "" + (firstOp.plus(secondOp)))
}
return calc(withPlusses)
}
part1("test/day18")
part1("puzzles/day18")
fun part2(inputFile: String) {
val input = File(inputFile).readLines(Charset.defaultCharset())
input.forEach {
println(sumUp(it, ::addFirstSumUp))
}
println(input.map { sumUp(it, ::addFirstSumUp) }.sum())
}
part2("test/day18")
part2("puzzles/day18")
}
| 0 | Kotlin | 0 | 0 | 3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04 | 2,152 | aoc2020 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindMedianSortedArrays.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 4. Median of Two Sorted Arrays
* @see <a href="https://leetcode.com/problems/median-of-two-sorted-arrays">Source</a>
*/
fun interface FindMedianSortedArrays {
operator fun invoke(nums1: IntArray, nums2: IntArray): Double
}
class FindMedianSortedArraysBS : FindMedianSortedArrays {
override fun invoke(nums1: IntArray, nums2: IntArray) = (nums1 to nums2).findMedianSortedArrays()
private fun Pair<IntArray, IntArray>.findMedianSortedArrays(): Double {
val m = first.size
val n = second.size
val l = m.plus(n).plus(1).div(2)
val r = m.plus(n).plus(2).div(2)
val local = findKth(first, 0, second, 0, l) + findKth(first, 0, second, 0, r)
return local.div(2.0)
}
private fun findKth(nums1: IntArray, aStart: Int, nums2: IntArray, bStart: Int, k: Int): Double {
if (aStart >= nums1.size) {
return nums2[bStart + k - 1].toDouble()
}
if (bStart >= nums2.size) {
return nums1[aStart + k - 1].toDouble()
}
if (k == 1) {
return nums1[aStart].coerceAtMost(nums2[bStart]).toDouble()
}
val aMid = aStart + k / 2 - 1
val bMid = bStart + k / 2 - 1
val aVal = if (aMid >= nums1.size) Int.MAX_VALUE else nums1[aMid]
val bVal = if (bMid >= nums2.size) Int.MAX_VALUE else nums2[bMid]
return if (aVal <= bVal) {
findKth(nums1, aMid + 1, nums2, bStart, k - k / 2)
} else {
findKth(nums1, aStart, nums2, bMid + 1, k - k / 2)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,202 | kotlab | Apache License 2.0 |
src/Day04.kt | ElenaRgC | 572,898,962 | false | null | fun main() {
fun part1(input: List<String>): Int {
val rangos = input
.map { it.split(",") }
.flatMap { it.map { it.split("-") } }
.flatMap { it.map { it.toInt() } }
var paresContenidos = 0
var inicioRango1 = 0
var finRango1 = 0
var inicioRango2 = 0
var finRango2 = 0
var i = 3
while (i < rangos.size) {
inicioRango1 = rangos[i-3]
finRango1 = rangos[i-2]
inicioRango2 = rangos[i-1]
finRango2 = rangos[i]
if ((inicioRango1 <= inicioRango2 && finRango1 >= finRango2) ||(inicioRango2 <= inicioRango1 && finRango2 >= finRango1)) {
paresContenidos++
}
i += 4
}
return paresContenidos
}
fun part2(input: List<String>): Int {
val rangos = input
.map { it.split(",") }
.flatMap { it.map { it.split("-") } }
.flatMap { it.map { it.toInt() } }
var paresContenidos = 0
var inicioRango1 = 0
var finRango1 = 0
var inicioRango2 = 0
var finRango2 = 0
var i = 3
while (i < rangos.size) {
inicioRango1 = rangos[i-3]
finRango1 = rangos[i-2]
inicioRango2 = rangos[i-1]
finRango2 = rangos[i]
if ((inicioRango2 in inicioRango1..finRango1)||(inicioRango1 in inicioRango2..finRango2)||(finRango1 in inicioRango2..finRango2)||(finRango2 in inicioRango1..finRango1)) {
paresContenidos++
}
i += 4
}
return paresContenidos
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b7505e891429970c377f7b45bfa8b5157f85c457 | 1,929 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | fun main() {
fun find(c: Char, map: List<String>): Pair<Int, Int> {
var position = Pair(-1, -1)
for (y in map.indices) {
for (x in map[y].indices) {
if (map[y][x] == c) {
position = Pair(x, y)
}
}
}
return position
}
fun findAll(c: Char, map: List<String>): MutableList<Pair<Int, Int>> {
val result = mutableListOf<Pair<Int, Int>>()
for (y in map.indices) {
for (x in map[y].indices) {
if (map[y][x] == c) {
result.add(Pair(x, y))
}
}
}
return result
}
fun part1(input: List<String>): Int {
// input equals map
// find S
val start = find('S', input)
val end = find('E', input)
val heightmap = input.toMutableList().map { it.toCharArray() }
heightmap[start.second][start.first] = 'a'
heightmap[end.second][end.first] = 'z'
// then check out, where we can go
val possibleMoves = ArrayDeque<Pair<Int, Int>>()
possibleMoves.add(start)
val distanceMap = Array(heightmap.size) { Array(heightmap[0].size) { Int.MAX_VALUE } }
distanceMap[start.second][start.first] = 0
while (possibleMoves.size > 0) {
println(possibleMoves)
// get next step
val step = possibleMoves.removeFirst()
// work out actual length of path so far
val distance = distanceMap[step.second][step.first]
// try all four directions
// don't go, if - on border - or already visited and distance is shorter or equal
// also don't go, if height is more than 1 difference up
// north
if (step.second != 0 && distance + 1 < distanceMap[step.second - 1][step.first]) {
if (heightmap[step.second][step.first].inc() >= heightmap[step.second - 1][step.first]) {
possibleMoves.add(Pair(step.first, step.second - 1))
distanceMap[step.second - 1][step.first] = distance + 1
}
}
// south
if (step.second != heightmap.lastIndex && distance + 1 < distanceMap[step.second + 1][step.first]) {
if (heightmap[step.second][step.first].inc() >= heightmap[step.second + 1][step.first]) {
possibleMoves.add(Pair(step.first, step.second + 1))
distanceMap[step.second + 1][step.first] = distance + 1
}
}
// east
if (step.first != 0 && distance + 1 < distanceMap[step.second][step.first - 1]) {
if (heightmap[step.second][step.first].inc() >= heightmap[step.second][step.first - 1]) {
possibleMoves.add(Pair(step.first - 1, step.second))
distanceMap[step.second][step.first - 1] = distance + 1
}
}
// west
if (step.first != input[0].lastIndex && distance + 1 < distanceMap[step.second][step.first + 1]) {
if (heightmap[step.second][step.first].inc() >= heightmap[step.second][step.first + 1]) {
possibleMoves.add(Pair(step.first + 1, step.second))
distanceMap[step.second][step.first + 1] = distance + 1
}
}
}
// put possibilities on stack
// create a map with distances from start
// revisit places only, if reachable within shorter distance
// else drop when revisited
println(distanceMap[end.second][end.first])
return distanceMap[end.second][end.first]
}
fun part2(input: List<String>): Int {
val start = find('S', input)
val end = find('E', input)
val heightmap = input.toMutableList().map { it.toCharArray() }
heightmap[start.second][start.first] = 'a'
heightmap[end.second][end.first] = 'z'
// then check out, where we can go
val possibleMoves = ArrayDeque<Pair<Int, Int>>()
possibleMoves.add(start)
possibleMoves.addAll(findAll('a', input))
val distanceMap = Array(heightmap.size) { Array(heightmap[0].size) { Int.MAX_VALUE } }
possibleMoves.forEach {
distanceMap[it.second][it.first] = 0
}
while (possibleMoves.size > 0) {
println(possibleMoves)
// get next step
val step = possibleMoves.removeFirst()
// work out actual length of path so far
val distance = distanceMap[step.second][step.first]
// try all four directions
// don't go, if - on border - or already visited and distance is shorter or equal
// also don't go, if height is more than 1 difference up
// north
if (step.second != 0 && distance + 1 < distanceMap[step.second - 1][step.first]) {
if (heightmap[step.second][step.first].inc() >= heightmap[step.second - 1][step.first]) {
possibleMoves.add(Pair(step.first, step.second - 1))
distanceMap[step.second - 1][step.first] = distance + 1
}
}
// south
if (step.second != heightmap.lastIndex && distance + 1 < distanceMap[step.second + 1][step.first]) {
if (heightmap[step.second][step.first].inc() >= heightmap[step.second + 1][step.first]) {
possibleMoves.add(Pair(step.first, step.second + 1))
distanceMap[step.second + 1][step.first] = distance + 1
}
}
// east
if (step.first != 0 && distance + 1 < distanceMap[step.second][step.first - 1]) {
if (heightmap[step.second][step.first].inc() >= heightmap[step.second][step.first - 1]) {
possibleMoves.add(Pair(step.first - 1, step.second))
distanceMap[step.second][step.first - 1] = distance + 1
}
}
// west
if (step.first != input[0].lastIndex && distance + 1 < distanceMap[step.second][step.first + 1]) {
if (heightmap[step.second][step.first].inc() >= heightmap[step.second][step.first + 1]) {
possibleMoves.add(Pair(step.first + 1, step.second))
distanceMap[step.second][step.first + 1] = distance + 1
}
}
}
// put possibilities on stack
// create a map with distances from start
// revisit places only, if reachable within shorter distance
// else drop when revisited
println(distanceMap[end.second][end.first])
return distanceMap[end.second][end.first]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12-TestInput")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12-Input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 7,109 | AoC-2022-12-01 | Apache License 2.0 |
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day03/Day03.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2022.day03
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun part1(input: List<String>): Long {
return input
.asSequence()
.map { line -> line.take((line.length / 2)) to line.takeLast(line.length / 2) }
.map { line -> line.first.toSet().intersect(line.second.toSet()) }
.map { intersects -> intersects.toList() }
.flatten()
.map { c: Char ->
if (c.isLowerCase()) c.code.toLong().minus(96)
else c.code.toLong().minus(38)
}
.sum()
}
fun part2(input: List<String>): Long {
return input
.asSequence()
.map { it.toSet() }
.windowed(size = 3, step = 3)
.map { sets: List<Set<Char>> -> sets.reduce { acc, chars -> acc.intersect(chars) } }
.flatten()
.map { c: Char ->
if (c.isLowerCase()) c.code.toLong().minus(96)
else c.code.toLong().minus(38)
}
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day03_test")
check(part1(testInput) == 157L)
check(part2(testInput) == 70L)
val input = Input.readInput("Day03")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 1,530 | AOC | Apache License 2.0 |
kotlin/src/com/leetcode/152_MaximumProductSubarray.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* Building 2d matrix with products, where products[i][j] is a product from j to i
*
* Time complexity: O(n^2), Space complexity: O(n^2)
*/
private class Solution152 {
fun maxProduct(nums: IntArray): Int {
if (nums.isEmpty()) return 0
var maxProduct: Int = nums[0]
val products = Array(nums.size) { IntArray(nums.size) }
for (i in products.indices) {
for (j in products[i].indices) {
if (j > i) break
else if (j == i) {
products[i][j] = nums[i]
maxProduct = max(maxProduct, products[i][j])
} else {
products[i][j] = products[i - 1][j] * nums[i]
maxProduct = max(maxProduct, products[i][j])
}
}
}
return maxProduct
}
}
/**
* Basically we just multiply everything with two traversals: forwards and backwards
* If we will face 0 we reset our multiplicator.
* The magic is hidden in multipling negative values. Let's consider we have no zeros.
* Then if we will have even negative numbers we just need to multiply everything
* If we will have odd negative numbers we need to multiply everything
* before the last negative or after first negative number
*
* Now if we will have zeros then each of subarray with non zeroes value is a
* subexample of the algorithm for non zero array
*
* Time complexity: O(n), Space complexity: O(1)
*/
private class Solution152Linear {
fun maxProduct(nums: IntArray): Int {
if (nums.isEmpty()) return 0
var result: Int = Int.MIN_VALUE
var product: Int = 1
for (i in 0..nums.lastIndex) {
product *= nums[i]
result = max(result, product)
if (product == 0) product = 1
}
product = 1
for (i in nums.lastIndex downTo 0) {
product *= nums[i]
result = max(result, product)
if (product == 0) product = 1
}
return result
}
}
fun main() {
println(Solution152Linear().maxProduct(intArrayOf(2, 3, -2, 4)))
} | 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 2,201 | problemsolving | Apache License 2.0 |
src/main/kotlin/days/Day11.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
class Day11 : Day(11) {
override fun partOne(): Any {
val monkeys = parseMonkeys().map { monkeyPartTwo ->
MonkeyPartOne(
monkeyPartTwo.id,
monkeyPartTwo.items.map { it.entries.first().value }.let { ArrayDeque(it) },
monkeyPartTwo.operation,
monkeyPartTwo.test
)
}
repeat(20) {
monkeys.forEach { monkey ->
monkey.pass(3).forEach { (item, to) -> monkeys[to].receive(item) }
}
}
return monkeys.sortedByDescending { it.inspections }.take(2)
.let { (top, second) -> top.inspections * second.inspections }
}
override fun partTwo(): Any {
val monkeys = parseMonkeys()
repeat(10_000) {
monkeys.forEach { monkey ->
monkey.pass().forEach { (item, to) -> monkeys[to].receive(item) }
}
}
return monkeys.sortedByDescending { it.inspections }.take(2)
.let { (top, second) -> top.inspections * second.inspections }
}
data class MonkeyPartOne(val id: Int, val items: ArrayDeque<Long>, val operation: (Long) -> Long, val test: Test) {
var inspections: Long = 0
private set
fun pass(worryFactor: Int): List<Pair<Long, Int>> = items.map { item ->
inspections++
val newItem = operation(item) / worryFactor
newItem to
if (newItem % test.divider == 0L) test.ifTrueTo
else test.ifFalseTo
}.also { items.clear() }
fun receive(item: Long) {
items.addLast(item)
}
}
data class MonkeyPartTwo(val id: Int, val items: ArrayDeque<Item>, val operation: (Long) -> Long, val test: Test) {
var inspections: Long = 0
private set
fun pass(): List<Pair<Item, Int>> = items.map { item ->
inspections++
val newItem = Item(item.value.mapValues { (divider, value) -> (operation(value)) % divider })
newItem to
if (newItem.getValue(test.divider) % test.divider == 0L) test.ifTrueTo
else test.ifFalseTo
}.also { items.clear() }
fun receive(item: Item) {
items.addLast(item)
}
}
data class Test(val divider: Int, val ifTrueTo: Int, val ifFalseTo: Int)
data class Item(val value: Map<Int, Long>) : Map<Int, Long> by value {
companion object {
fun init(initValue: Long, dividers: List<Int>): Item {
return Item(dividers.associateWith { initValue })
}
}
}
private fun parseMonkeys(): Array<MonkeyPartTwo> {
val monkeyBlocks = inputList.map(String::trim).chunked(7)
val dividers = monkeyBlocks.map { it[3].removePrefix("Test: divisible by ").toInt() }
return monkeyBlocks.map { monkeyList ->
val monkeyId = monkeyList[0].removePrefix("Monkey ").dropLast(1).toInt()
MonkeyPartTwo(
id = monkeyId,
items = monkeyList[1].removePrefix("Starting items: ")
.split(", ")
.map { Item.init(it.toLong(), dividers) }
.let(::ArrayDeque),
operation = monkeyList[2].removePrefix("Operation: new = ")
.split(" ")
.let { (left, opString, right) ->
val operand: (Long, Long) -> Long = when (opString) {
"+" -> Long::plus
"*" -> Long::times
else -> throw IllegalArgumentException("Unsupported operand: $opString")
}
{ x: Long ->
operand(
(if (left == "old") x else left.toLong()),
(if (right == "old") x else right.toLong())
)
}
},
test = Test(
divider = dividers[monkeyId],
ifTrueTo = monkeyList[4].removePrefix("If true: throw to monkey ").toInt(),
ifFalseTo = monkeyList[5].removePrefix("If false: throw to monkey ").toInt()
)
)
}.toTypedArray()
}
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 4,398 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/Day16.kt | SergeiMikhailovskii | 573,781,461 | false | {"Kotlin": 32574} | fun main() {
val timeLimit = 26
class Valve(
val rate: Int,
val tunnels: List<String>,
)
class PathB(
val valvesMe: List<Valve>,
val valvesElephant: List<Valve>,
/**
* Key - valve
* value - opened time
*/
val opened: Map<Valve, Int>
) {
val total: Int
get() = opened.map { (valve, i) -> (timeLimit - i) * valve.rate }.sum()
}
val input = readInput("Day16_test")
val regex = "Valve (\\w+?) has flow rate=(\\d+?); tunnels? leads? to valves? (.+)".toRegex()
val valves = input.associate {
val (name, rate, tunnelsStr) = regex.matchEntire(it)!!.destructured
name to Valve(rate.toInt(), tunnelsStr.split(", "))
}
val maxOpenedValves = valves.values.count { it.rate > 0 }
val start = valves["AA"]!!
val startPath = PathB(
valvesMe = listOf(start),
valvesElephant = listOf(start),
opened = hashMapOf()
)
var allPaths = listOf(startPath)
var bestPath = startPath
var time = 1
while (time < timeLimit) {
val newPaths = mutableListOf<PathB>()
for (currentPath in allPaths) {
if (currentPath.opened.size == maxOpenedValves) continue
val currentLastMe = currentPath.valvesMe.last()
val currentValvesMe = currentPath.valvesMe
val currentLastElephant = currentPath.valvesElephant.last()
val currentValvesElephant = currentPath.valvesElephant
val openMe = currentLastMe.rate > 0 && !currentPath.opened.containsKey(currentLastMe)
val openElephant = currentLastElephant.rate > 0 && !currentPath.opened.containsKey(currentLastElephant)
if (openMe || openElephant) {
val opened = currentPath.opened.toMutableMap()
val possibleValvesMe = if (openMe) {
opened[currentLastMe] = time
listOf(currentValvesMe + currentLastMe)
} else {
currentLastMe.tunnels.map {
val valve = valves[it]!!
val possibleValves = currentValvesMe + valve
possibleValves
}
}
val possibleValvesElephant = if (openElephant) {
opened[currentLastElephant] = time
listOf(currentValvesElephant + currentLastElephant)
} else {
currentLastElephant.tunnels.map {
val valve = valves[it]!!
val possibleValves = currentValvesElephant + valve
possibleValves
}
}
for (me in possibleValvesMe) {
for (elephant in possibleValvesElephant) {
val possibleNewPath = PathB(me, elephant, opened)
newPaths += possibleNewPath
}
}
}
val combinedLeads = currentLastMe.tunnels.map { me ->
currentLastElephant.tunnels.map { elephant ->
me to elephant
}
}.flatten()
.filter { (a, b) -> a != b }
val possiblePaths = combinedLeads.map { (me, elephant) ->
val valveMe = valves[me]!!
val valveElephant = valves[elephant]!!
val possibleValvesMe = currentValvesMe + valveMe
val possibleValvesElephant = currentValvesElephant + valveElephant
val possiblePath = PathB(possibleValvesMe, possibleValvesElephant, currentPath.opened)
possiblePath
}
newPaths.addAll(possiblePaths)
}
allPaths = newPaths.sortedByDescending { it.total }.take(200000)
if (allPaths.first().total > bestPath.total) {
bestPath = allPaths.first()
}
time++
}
println(bestPath.total)
} | 0 | Kotlin | 0 | 0 | c7e16d65242d3be6d7e2c7eaf84f90f3f87c3f2d | 4,040 | advent-of-code-kotlin | Apache License 2.0 |
src/Day01.kt | ostersc | 572,991,552 | false | {"Kotlin": 46059} | fun main() {
fun part1(input: List<String>): Int {
return input.fold(Pair(0, 0)) { max, curr ->
val subTotal = if (curr.isEmpty()) max.second else max.second + curr.toInt()
Pair(if (max.first > subTotal) max.first else subTotal, if (curr.isEmpty()) 0 else subTotal)
}.first
}
fun part2(input: List<String>): Int {
return input.fold(arrayListOf(0)) { sums, curr ->
if (curr.isEmpty()) {
sums.add(0)
sums
} else {
sums[sums.lastIndex] += curr.toInt()
sums
}
}.sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9 | 942 | advent-of-code-2022 | Apache License 2.0 |
src/day07/Day07.kt | sanyarajan | 572,663,282 | false | {"Kotlin": 24016} | package day07
import readInput
// class to represent an ElfFile that has a name and size
class ElfFile(private val name: String, val size: Int) {
override fun toString(): String {
return "$name (file, size=$size)"
}
}
// class to represent a folder that has a name and a list of ElfFiles and Folders
class Directory(val name: String, val parent: Directory? = null) {
val files = mutableListOf<ElfFile>()
val folders = mutableListOf<Directory>()
override fun toString(): String {
return "$name (dir, size=${getSize()})"
}
fun getSize(): Int {
var size = 0
files.forEach { size += it.size }
folders.forEach { size += it.getSize() }
return size
}
@Suppress("unused", "MemberVisibilityCanBePrivate")
fun printTree(indent: String = "") {
println("$indent- $this")
files.forEach { println("$indent - $it") }
folders.forEach { it.printTree("$indent ") }
}
}
fun main() {
fun sumSizesOfAllFoldersAndSubFolders(folder: Directory, maxSize: Int): Int {
var size = 0
folder.folders.forEach { size += sumSizesOfAllFoldersAndSubFolders(it, maxSize) }
if (folder.getSize() < maxSize) {
size += folder.getSize()
}
return size
}
fun getListOfDirectoriesBigEnough(folder: Directory, maxSize: Int): List<Directory> {
val list = mutableListOf<Directory>()
folder.folders.forEach { list.addAll(getListOfDirectoriesBigEnough(it, maxSize)) }
if (folder.getSize() >= maxSize) {
list.add(folder)
}
return list
}
@Suppress("ControlFlowWithEmptyBody")
fun getRootOfDirectoryTree(input: List<String>): Directory {
val root = Directory("/")
var currentDir = root
input.forEach { line ->
if (line == "$ cd /") {
} else if (!line.startsWith("$")) {
// file listing
val parts = line.split(" ")
if (parts[0] == "dir") {
// directory listing
val dir = Directory(parts[1], currentDir)
currentDir.folders.add(dir)
} else {
// file listing
val file = ElfFile(parts[1], parts[0].toInt())
currentDir.files.add(file)
}
} else if (line == "$ cd ..") {
currentDir = currentDir.parent!!
} else if (line.startsWith("$ cd ")) {
val dirName = line.substring(5)
currentDir = currentDir.folders.first { it.name == dirName }
}
}
return root
}
fun part1(input: List<String>): Int {
val root = getRootOfDirectoryTree(input)
// root.printTree()
return sumSizesOfAllFoldersAndSubFolders(root, 100000)
}
fun part2(input: List<String>): Int {
val totalSpace = 70000000
val desiredSpace = 30000000
val root = getRootOfDirectoryTree(input)
val unusedSpace = totalSpace - root.getSize()
val spaceToFree = desiredSpace - unusedSpace
return getListOfDirectoriesBigEnough(root, spaceToFree).minByOrNull { it.getSize() }!!.getSize()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day07/Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("day07/day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e23413357b13b68ed80f903d659961843f2a1973 | 3,571 | Kotlin-AOC-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.