path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day14.kt | syncd010 | 324,790,559 | false | null | class Day14: Day {
data class ChemSpec(val element: String, var quantity: Long)
private fun convert(input: List<String>) : Map<ChemSpec, List<ChemSpec>> {
return input.associate { line: String ->
val spec = line.split(" => ")
val outElement = spec[1].split(" ")
val inList = spec[0].split(", ")
Pair(ChemSpec(outElement[1], outElement[0].toLong()), inList.map {
val inElement = it.split(" ")
ChemSpec(inElement[1], inElement[0].toLong()) })
}
}
private fun calcOre(reactions: Map<ChemSpec, List<ChemSpec>>,
goal: ChemSpec,
initialSurplus: Map<String, Long>): Pair<Long, Map<String, Long>> {
val surplus = initialSurplus.toMutableMap()
val toProduce = mutableListOf(goal)
var totalOre = 0L
while (toProduce.size > 0) {
val product = toProduce.removeAt(0)
if (product.element == "ORE") {
totalOre += product.quantity
continue
}
if (product.quantity <= surplus[product.element] ?: 0) {
surplus[product.element] = surplus[product.element]!! - product.quantity
continue
}
product.quantity -= (surplus[product.element] ?: 0)
val recipeKey = reactions.keys.find { it.element == product.element }!!
val batches = ceil(product.quantity, recipeKey.quantity)
surplus[product.element] = batches * recipeKey.quantity - product.quantity
toProduce.addAll(reactions[recipeKey]!!.map {
ChemSpec(it.element, batches * it.quantity)
})
}
return Pair(totalOre, surplus)
}
override fun solvePartOne(input: List<String>): Long {
return calcOre(convert(input), ChemSpec("FUEL", 1), emptyMap()).first
}
override fun solvePartTwo(input: List<String>): Long {
val reactions = convert(input)
var surplus = emptyMap<String, Long>()
var totalOre = 1000000000000L
var fuel = 0L
var goalFuel = 100000L
while (goalFuel > 0) {
val (usedOre, newSurplus) = calcOre(reactions, ChemSpec("FUEL", goalFuel), surplus)
if (usedOre <= totalOre) {
totalOre -= usedOre
surplus = newSurplus
fuel += goalFuel
} else {
goalFuel /= 2
}
}
return fuel
}
} | 0 | Kotlin | 0 | 0 | 11c7c7d6ccd2488186dfc7841078d9db66beb01a | 2,611 | AoC2019 | Apache License 2.0 |
src/main/kotlin/Day03.kt | robfletcher | 724,814,488 | false | {"Kotlin": 18682} | import kotlin.math.max
import kotlin.math.min
class Day03 : Puzzle {
override fun test() {
val input = """
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...\$.*....
.664.598..""".trimIndent()
assert(part1(input.lineSequence()) == 4361)
assert(part2(input.lineSequence()) == 467835)
}
fun List<String>.isPartNumber(x: IntRange, y: Int): Boolean {
val xRange = max(0, x.first - 1)..min(get(y).lastIndex, x.last + 1)
val yRange = max(0, y - 1)..min(lastIndex, y + 1)
return yRange.any { y ->
xRange.any { x ->
this[y][x].let { !it.isDigit() && it != '.' }
}
}
}
override fun part1(input: Sequence<String>) =
input.toList()
.run {
mapIndexed { y, line ->
Regex("""\d+""").findAll(line)
.filter { isPartNumber(it.range, y) }
.map { it.value.toInt() }
.sum()
}
}
.reduce(Int::plus)
fun List<String>.adjacentNumbers(x: Int, y: Int): Collection<Int> {
val xRange = max(0, x - 1)..min(get(y).lastIndex, x + 1)
val yRange = max(0, y - 1)..min(lastIndex, y + 1)
return slice(yRange)
.flatMap { line ->
Regex("""\d+""")
.findAll(line)
.filter { match -> match.range.any { it in xRange } }
.map { it.value.toInt() }
}
}
fun List<String>.gearRatio(x: Int, y: Int) =
when (this[y][x]) {
'*' -> adjacentNumbers(x, y).run { if (size < 2) 0 else reduce(Int::times) }
else -> 0
}
override fun part2(input: Sequence<String>) =
input.toList()
.run {
mapIndexed { y, line ->
line.indices.sumOf { x -> gearRatio(x, y) }
}
}
.reduce(Int::plus)
} | 0 | Kotlin | 0 | 0 | cf10b596c00322ea004712e34e6a0793ba1029ed | 1,810 | aoc2023 | The Unlicense |
src/main/kotlin/dev/tasso/adventofcode/_2022/day07/Day07.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2022.day07
import dev.tasso.adventofcode.Solution
class Day07 : Solution<Int> {
override fun part1(input: List<String>): Int =
input.asSequence()
.chunkedByCommand()
.drop(1)
.fold(FileSystemNode("/", "dir")) { currNode , command ->
if(command.first().startsWith("$ cd", 0)) {
val dirName = command.first().replaceFirst("$ cd ", "")
if(dirName == "..") {
currNode.parent!!
} else {
currNode.children.first { it.name == dirName }
}
} else {
command.drop(1).forEach {
val fileInfo = it.split(" ")
if(!fileInfo[0].startsWith("dir", 0)) {
val newNode = FileSystemNode(fileInfo[1], "file", fileInfo[0].toInt())
currNode.addChild(newNode)
} else {
val newNode = FileSystemNode(fileInfo[1], "dir")
currNode.addChild(newNode)
}
}
currNode
}
}.getRootNode()
.getSmallDirsSize()
override fun part2(input: List<String>): Int =
input.asSequence()
.chunkedByCommand()
.drop(1)
.fold(FileSystemNode("/", "dir")) { currNode , command ->
if(command.first().startsWith("$ cd", 0)) {
val dirName = command.first().replaceFirst("$ cd ", "")
if(dirName == "..") {
currNode.parent!!
} else {
currNode.children.first { it.name == dirName }
}
} else {
command.drop(1).forEach {
val fileInfo = it.split(" ")
if(!fileInfo[0].startsWith("dir", 0)) {
val newNode = FileSystemNode(fileInfo[1], "file", fileInfo[0].toInt())
currNode.addChild(newNode)
} else {
val newNode = FileSystemNode(fileInfo[1], "dir")
currNode.addChild(newNode)
}
}
currNode
}
}.getRootNode()
.getDirSizes()
.filter { it > 358913 }
.min()
private fun Sequence<String>.chunkedByCommand(): Sequence<List<String>> = sequence {
val subList = mutableListOf(this@chunkedByCommand.first())
for (element in this@chunkedByCommand.drop(1)) {
if (element.startsWith("$")) {
yield(subList)
subList.clear()
}
subList += element
}
if (subList.isNotEmpty()) yield(subList)
}
private class FileSystemNode(val name: String, val type: String, var size: Int = 0){
var parent:FileSystemNode? = null
val children:MutableList<FileSystemNode> = mutableListOf()
fun addChild(newNode:FileSystemNode){
newNode.parent = this
children.add(newNode)
var currNode = newNode
while(currNode.parent != null) {
currNode = currNode.parent!!
currNode.size += newNode.size
}
}
fun getRootNode() : FileSystemNode {
var currNode = this
while(currNode.parent != null) {
currNode = currNode.parent!!
}
return currNode
}
fun getSmallDirsSize(): Int {
val currSize = if(this.type == "dir" && this.size <= 100000) this.size else 0
return currSize + this.children.sumOf { it.getSmallDirsSize() }
}
fun getDirSizes(): Set<Int> {
return (if(this.type == "dir") setOf(this.size) else emptySet()) + this.children.flatMap { it.getDirSizes() }.toSet()
}
}
} | 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 4,218 | advent-of-code | MIT License |
src/test/kotlin/Solution001.kt | cia-exe | 331,877,092 | false | null | import org.junit.jupiter.api.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.api.TestMethodOrder
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation
import java.util.*
import java.util.AbstractMap.SimpleEntry
internal class Solution410 {
@Test
fun go() {
// Input: nums = [7,2,5,10,8], m = 2
// Output: 18
// Explanation:
// There are four ways to split nums into two subarrays.
// The best way is to split it into [7,2,5] and [10,8],
// where the largest sum among the two subarrays is only 18.
println(splitArray(intArrayOf(7, 2, 5, 10, 8), 2))
}
fun splitArray(nums: IntArray, g: Int): Int {
var s = Int.MIN_VALUE
var e = 0
var m: Int // start , end, mid
nums.forEach {
if (s < it) s = it
e += it
}
var sp_num = 0
var sp_sum = 0
fun spilt(max: Int) {
sp_num = 1
sp_sum = Int.MIN_VALUE
var sum = 0
nums.forEach {
if (sum + it > max) {
sp_num++
if (sp_sum < sum) sp_sum = sum
sum = it
} else sum += it
}
if (sp_sum < sum) sp_sum = sum
}
// spilt(nums,18); // for debug
// return sp_num*1000 + sp_sum;
while (s < e) {
m = (s + e) / 2
spilt(m)
System.out.printf("%d,%d,%d,%d,%d%n", s, e, m, sp_num, sp_sum)
if (sp_num <= g) e = sp_sum // m is too large
else s = m + 1 // m is too small, exclude it //m+1=(s+e)/2, m+1=s/2+e/2, s/2=m+1-e/2, s=2m+2-e
}
return e
}
}
internal class Solution347 {
@Test
fun go() {
println(topKFrequent(intArrayOf(40, 30, 20, 30, 20, 30, 10, 20, 30, 40, 50), 2).contentToString())
}
fun topKFrequent(nums: IntArray, k: Int): IntArray {
val map = HashMap<Int, Int>()
nums.forEach { map[it] = map.getOrDefault(it, 0) + 1 }
return map.toList().sortedByDescending { it.second }.take(k).map { it.first }.toIntArray()
}
}
internal class Solution347a {
@Test
fun go() {
println(topKFrequent(intArrayOf(40, 40, 40, 40, 30, 30, 30, 20, 20, 50), 3).contentToString())
}
fun topKFrequent(nums: IntArray, _k: Int): IntArray {
var k = _k
val map = HashMap<Int, Int>()
nums.forEach { map[it] = map.getOrDefault(it, 0) + 1 }
val q = PriorityQueue<Array<Int>> { a, b -> a[0] - b[0] } // min heap
for (i in 0 until k) q.offer(arrayOf(-1, -1))
for ((key, value) in map) {
q.offer(arrayOf(value, key))
q.poll()
}
val r = IntArray(k)
//for(var x:q) r[i++]=x[1]; // iteration q is un-ordered!!
while (q.size > 0) r[--k] = q.poll()[1]
return r
}
}
@ExtendWith(TimingExtension::class)
internal class TimingExtensionTests {
@Test
@Throws(Exception::class)
fun sleep20ms() {
Thread.sleep(20)
}
@Test
@Throws(Exception::class)
fun sleep50ms() {
// Arrays are optimized for primitives: there are separate IntArray, DoubleArray, CharArray etc.
// which are mapped to Java primitive arrays (int[], double[], char[]),
val arr = arrayOf(1, 2, 3) // Array<Int>
val arr3 = Array(3) { it } // Array<Int> [0, 1, 2]
println("arr3: ${arr3.contentToString()}")
println(arr) //[Ljava.lang.Integer;@17f62e33
println(arr.contentToString()) // [1, 2, 3]
val i = intArrayOf(1, 2, 3) // IntArray
val f = floatArrayOf(1f, 2f, 3f)
val c = charArrayOf('1', '2', '3')
println(i) //[I@76b1e9b8
println(i.contentToString()) // [1, 2, 3]
val l = listOf(1, 2, 3)
println(l) // [1, 2, 3]
//println(l.contentToString()) // list doesn't have contentToString
val lp = listOf(1 to 10, 2 to 20, 3 to 30)
println(lp) // [(1, 10), (2, 20), (3, 30)]
Thread.sleep(50)
}
}
@TestMethodOrder(OrderAnnotation::class)
@ExtendWith(TimingExtension::class)
internal class Solution692 {
@Test
@Order(0) // 1st function call will take more time to run
fun warmUp() {
println("warm Up...")
println(topKFrequent(arrayOf("a", "b", "c", "c", "b", "a", "d"), 3))
println(topKFrequent0(arrayOf("a", "b", "c", "c", "b", "a", "d"), 3))
println("warm Up...done")
}
// ["the","day","is","sunny","the","the","the","sunny","is","is"] 4
// Expected ["the","is","sunny","day"]
// ["i","love","leetcode","i","love","coding"] 3
// Expected ["i","love","coding"]
@Test
@Order(3)
fun go() {
val f = ::topKFrequent
println(f(arrayOf("the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is", "cday"), 4))
println(f(arrayOf("i", "love", "leetcode", "i", "love", "coding"), 4))
println(f(arrayOf("a", "b", "c", "c", "b", "a", "d"), 3))
}
@Test
@Order(2)
fun go0() {
val f = ::topKFrequent0
println(f(arrayOf("the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is", "cday"), 4))
println(f(arrayOf("i", "love", "leetcode", "i", "love", "coding"), 4))
println(f(arrayOf("a", "b", "c", "c", "b", "a", "d"), 3))
}
fun topKFrequent0(words: Array<String>, k: Int): List<String> {
val counts = words.groupBy { it }.map { it.key to it.value.size } // slower?
//Sort the words with the same frequency by their lexicographical order.
val q = PriorityQueue<Pair<String, Int>> { a, b -> // min heap
if (a.second == b.second) b.first.compareTo(a.first) // compare reversely so that 'a' > 'b'
else a.second.compareTo(b.second)
}
repeat(k) { q.offer(("?" to -1)) }
counts.forEach { q.offer(it); q.poll() }
return ArrayDeque<String>().apply { while (q.size > 0) offerFirst(q.poll().first) }.toList()
//return q.map { it.key } // iteration q is un-ordered!!
}
fun topKFrequent(words: Array<String>, k: Int): List<String> {
val counts = HashMap<String, Int>().apply { words.forEach { this[it] = getOrDefault(it, 0) + 1 } }
//val counts = words.groupBy { it }.mapValues { it.value.count() } // slower ?
//Sort the words with the same frequency by their lexicographical order.
val q = PriorityQueue<Map.Entry<String, Int>> { a, b -> // min heap
if (a.value == b.value) b.key.compareTo(a.key) // compare reversely so that 'a' > 'b'
else a.value.compareTo(b.value)
}
repeat(k) { q.offer(SimpleEntry("?", -1)) } //error: unresolved reference: SimpleEntry on leetcode
//q.addAll(buildMap { repeat(k) { put("??$it", -1) } }.entries)
counts.forEach { q.offer(it); q.poll() }
return ArrayDeque<String>().apply { while (q.size > 0) offerFirst(q.poll().key) }.toList()
}
}
internal class Solution1260 {
@Test
fun go() {
val data = arrayOf(
intArrayOf(1, 2, 3, 4, 5),
intArrayOf(11, 12, 13, 14, 15),
intArrayOf(21, 22, 23, 24, 25)
)
println(shiftGrid(data, 3))
println(shiftGrid4(data, 3))
println(shiftGrid0(data, 3))
}
fun shiftGrid4(g: Array<IntArray>, _k: Int): List<List<Int>> { //5ms (92.64%)
var k = _k
val y = g.size
val x = g[0].size
val total = x * y
k = (total - k % total) % total // check total=9, k=9
val ans = ArrayList<List<Int>>(y)
repeat(y) {
val l = IntArray(x)
repeat(x) {
l[it] = g[k / x][k % x]
k = (k + 1) % total
}
ans.add(l.toList())
}
return ans
}
fun shiftGrid(g: Array<IntArray>, _k: Int): List<List<Int>> { //3ms (98.84%)
var k = _k
val y = g.size
val x = g[0].size
val total = x * y
k = (total - k % total) % total // check total=9, k=9
val ans = ArrayList<List<Int>>(y)
repeat(y) {
val l = ArrayList<Int>(x)
ans.add(l)
repeat(x) {
l.add(g[k / x][k % x])
k = (k + 1) % total
}
}
return ans
}
fun shiftGrid0(grid: Array<IntArray>, _k: Int): List<List<Int>> { //8ms (65%)
var k = _k
k %= (grid.size * grid[0].size)
val g = grid.map { LinkedList(it.asList()) }
val q = ArrayDeque<Int>()
while (k-- > 0) {
for (l in g) q.offer(l.pollLast())
q.offerFirst(q.pollLast())
for (l in g) (l.offerFirst(q.poll()))
}
return g
}
}
internal class Solution17 {
@Test
fun go() {
// 0 <= digits.length <= 4
// digits[i] is a digit in the range ['2', '9'].
val a = letterCombinations("234")
println("${a.size}\n${a.joinToString("\n")}")
println(a) // [adg, adh, adi, aeg...]
}
val map = arrayOf(
charArrayOf('a', 'b', 'c'),
charArrayOf('d', 'e', 'f'),
charArrayOf('g', 'h', 'i'),
charArrayOf('j', 'k', 'l'),
charArrayOf('m', 'n', 'o'),
charArrayOf('p', 'q', 'r', 's'),
charArrayOf('t', 'u', 'v'),
charArrayOf('w', 'x', 'y', 'z')
)
fun letterCombinations(digits: String): List<String> {
val ans = ArrayList<String>()
if (digits.isEmpty()) return ans
val input = digits.toCharArray()
val sb = CharArray(digits.length)
fun dfs(level: Int) {
if (level == input.size) {
ans.add(String(sb))
return
}
for (d in map[input[level] - '2']) {
sb[level] = d
dfs(level + 1)
}
}
dfs(0)
return ans
}
}
class Solution289 {
// in: [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
// expected: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
@Test
fun go() {
val s = arrayOf(intArrayOf(0, 1, 0), intArrayOf(0, 0, 1), intArrayOf(1, 1, 1), intArrayOf(0, 0, 0))
println(s.joinToString { it.contentToString() })
gameOfLife(s)
println(s.joinToString { it.contentToString() })
}
fun gameOfLife(b: Array<IntArray>) {
val h = b.size
val w = b[0].size
fun check(y: Int, x: Int) = if (x in 0 until w && y in 0 until h) b[y][x] and 1 else 0
fun sum(y: Int, x: Int) = check(y, x - 1) + check(y, x + 1) +
check(y - 1, x - 1) + check(y - 1, x) + check(y - 1, x + 1) +
check(y + 1, x - 1) + check(y + 1, x) + check(y + 1, x + 1)
repeat(h) { y ->
repeat(w) { x ->
val s = sum(y, x)
val v = b[y][x]
if (v and 1 == 1) {
if (s in 2..3) b[y][x] = v or 2
} else if (s == 3) b[y][x] = v or 2
}
}
repeat(h) { y -> repeat(w) { b[y][it].apply { b[y][it] = this ushr 1 } } }
}
}
class Solution59 {
// 123
// 894
// 765
// 12
// 43
// 1 2 3 4
// 5 6 7 8
// 9 10 11 12
// 13 14 15 16
// 1 2 3 4
// 12 13 14 5
// 11 16 15 6
// 10 9 8 7
// 1 2 3 4 5
// 16 17 18 19 6
// 15 24 25 20 7
// 14 23 22 21 8
// 13 12 11 10 9
// Input: n = 3
// Output: [[1,2,3],[8,9,4],[7,6,5]]
// Input: n = 1
// Output: [[1]]
@Test
fun go() {
println(generateMatrix(1).joinToString { it.contentToString() })
println(generateMatrix(2).joinToString { it.contentToString() })
println(generateMatrix(3).joinToString { it.contentToString() })
println(generateMatrix(4).joinToString { it.contentToString() })
println(generateMatrix(5).joinToString { it.contentToString() })
}
fun generateMatrix(n: Int): Array<IntArray> {
val dir = arrayOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0))
val ans = Array(n) { IntArray(n) }
var idx = 0
var x = -1
var y = 0
var d = dir[0]
repeat(n * n) {
val ny = y + d[0]
val nx = x + d[1]
if (nx in 0 until n && ny in 0 until n && ans[ny][nx] == 0) {
x = nx; y = ny
} else { // If the next position is out of range or its value has already been set
d = dir[++idx % 4]
x += d[1]; y += d[0]
}
ans[y][x] = it + 1
}
return ans
}
}
class Solution19 {
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
var h: ListNode? = ListNode(0).apply { next = head }
var r = head
var l = head
repeat(n) { r = r?.next }
while (r?.next != null) {
r = r?.next
l = l?.next
}
l?.next = r
return head
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
class Solution700 {
fun searchBST(root: TreeNode?, v: Int): TreeNode? = root?.`val`?.run {
when {
this == v -> root
this > v -> searchBST(root.left, v)
else -> searchBST(root.right, v)
}
}
}
class Solution1383 {
@Test
fun go() {
val speed = intArrayOf(2, 10, 3, 1, 5, 8)
val efficiency = intArrayOf(5, 4, 3, 9, 7, 2)
println(maxPerformance(speed.size, speed, efficiency, 2)) // 60
println(maxPerformance(3, intArrayOf(3, 8, 2), intArrayOf(2, 7, 1), 2)) // 56
}
fun maxPerformance(n: Int, speed: IntArray, efficiency: IntArray, k: Int): Int {
val data = speed.mapIndexed { idx, s -> s to efficiency[idx] }.sortedByDescending { it.second }
val hp = PriorityQueue<Int>().apply { repeat(k) { offer(0) } }
var sum = 0L
var ans = 0L
data.forEach {
sum = sum + it.first - hp.poll()
hp.offer(it.first)
ans = ans.coerceAtLeast(it.second * sum)
}
return (ans % 1000000007L).toInt() // 1e9+7 is a Double!!!
}
}
class Solution110XXX { // wrong! it is a completed bin tree
// lv leaf
// 0 0 X!!
// 1 1 2^0
// 2 2 2^1
// 3 4 2^2
// 4 8 2^3
//
// leaf=2^(lv-1)
// inner=leaf-1;
// nodes= inner+leaf= 2*leaf-1 // completed tree
// balance nodes is in inner+1..nodes
// -> leaf..2*leaf-1
// -> 2^(lv-1) . 2^lv-1
fun isBalanced(root: TreeNode?): Boolean {
if (root == null) return true
var deep = 0
var count = 0
fun TreeNode.dfs(lvl: Int) {
if (deep < lvl) deep = lvl
count++
left?.dfs(lvl + 1)
right?.dfs(lvl + 1)
}
root.dfs(1)
val leaf = Math.pow(2.0, deep - 1.0).toInt()
return count in leaf until 2 * leaf // = count in leaf..2*leaf-1
}
}
class Solution110 {
fun isBalanced(root: TreeNode?): Boolean {
var balanced = true;
fun TreeNode?.depth(): Int {
if (!balanced) return 0
if (this == null) return 0
val l = left.depth()
val r = right.depth()
if (Math.abs(l - r) > 1) balanced = false
return Math.max(l, r) + 1
}
root?.depth()
return balanced
}
}
class Solution94 {
fun inorderTraversal(root: TreeNode?) =
mutableListOf<Int>().also {
fun TreeNode.dfs() {
left?.dfs()
it.add(`val`)
right?.dfs()
}
root?.dfs()
}
}
// This is NOT a Binary 'Search' Tree!!! So it's left might larger than right!!!
// e.g: 3
// 3 4
// 8 3 4 8
//
// root.val = min(root.left.val, root.right.val)
// so each node must <= all it's children, so the root is the smallest.
// compare 3 vals
// 1. val -> same as min(l.val, r.val)
// 2. if(val!=sub.val) sub.val
// 3. else 2ndMin(x) both l and r might equal!
// thus 1 is the 1st min, min(2,3) is the 2nd min
// ps: 1 <= Node.val <= 231 - 1, we can't use MAX_VAL if not found
class Solution671 {
@Test
fun go() {
findSecondMinimumValue(null)
}
fun findSecondMinimumValue(root: TreeNode?): Int = root.run {
if (this == null || left == null) return -1 // node has two or zero sub-node.
val l = left!!.`val`.let { if (it == `val`) findSecondMinimumValue(left) else it }
val r = right!!.`val`.let { if (it == `val`) findSecondMinimumValue(right) else it }
// val l = if (left!!.`val` == `val`) findSecondMinimumValue(left) else left!!.`val`
// val r = if (right!!.`val` == `val`) findSecondMinimumValue(right) else right!!.`val`
return if (l < 0) r else if (r < 0) l else Math.min(l, r)
// val l=(left!!.`val` == `val`) findSecondMinimumValue(left).let {
// if (it < 0) right!!.`val`
// else Math.min(it, right!!.`val`)
// }
// else findSecondMinimumValue(right).let {
// if (it < 0) left!!.`val`
// else Math.min(it, left!!.`val`)
// }
}
}
class Solution671X {
// This is NOT a Binary 'Search' Tree!!! So it's left might larger than right!!!
fun findSecondMinimumValue(root: TreeNode?): Int {
var ans = 0
val set = mutableSetOf<Int>()
fun TreeNode.dfs() {
left?.dfs()
if (ans > 0) return
set.add(`val`)
if (set.size == 2) {
ans = `val`
return
}
right?.dfs()
}
root?.dfs()
return ans
}
}
class Solution814 {
fun pruneTree(root: TreeNode?): TreeNode? {
// return sum of val
fun TreeNode.dfs(): Int = `val` +
(left?.dfs()?.also { if (it == 0) left = null } ?: 0) +
(right?.dfs()?.also { if (it == 0) right = null } ?: 0)
return if (root?.dfs() == 0) null else root
}
}
class Solution99 {
// try
// 2134 ->21 i>i+1: 1
// 3214 ->31 i>i+1: 21
// 1324 ->32 i>i+1: 2
// 4231 ->41 i>i+1: 21
fun recoverTree(root: TreeNode?): Unit {
var n1: TreeNode? = null
var n2: TreeNode? = null
var n3: TreeNode? = null
var prev = TreeNode(Int.MIN_VALUE)
fun TreeNode.dfs() {
left?.dfs()
if (prev.`val` > `val`) {
if (n1 == null) {
n1 = prev
n2 = this
} else n3 = this
}
prev = this
right?.dfs()
}
root?.dfs()
if (n3 == null) n3 = n2
val t = n1!!.`val`; n1?.`val` = n3!!.`val`; n3?.`val` = t //swap n1 and n3
}
}
class Solution705 {
class MyHashSet() {
// 0 <= key <= 10^6
// At most 10^4 calls will be made to add, remove, and contains.
private val table = IntArray(1000000 / Int.SIZE_BITS + 1)
fun add(key: Int) {
val i = key / Int.SIZE_BITS
val x = table[i]
table[i] = 1 shl key % Int.SIZE_BITS or x
}
fun remove(key: Int) {
val i = key / Int.SIZE_BITS
val x = table[i]
table[i] = (1 shl key % Int.SIZE_BITS).inv() and x
}
fun contains(key: Int): Boolean {
val i = key / Int.SIZE_BITS
val x = table[i]
return 1 shl key % Int.SIZE_BITS and x != 0 // x can < 0!
}
}
}
class Solution706 {
@Test
fun run() {
// ["MyHashMap","put","put","get","get","put","get","remove","get"]
// [[],[1,1],[2,2],[1],[3],[2,1],[2],[2],[2]]
// Expected [null,null,null,1,-1,null,1,null,-1]
MyHashMap().apply {
put(1, 1)
put(2, 2)
println(get(1)) //1
println(get(3)) //-1
put(2, 1)
println(get(2)) //1
remove(2)
println(get(2)) //-1
}
// java int=32, long=64
// c++:
// unix:LP64 int=32, long=longlong=pointer=64
// win:LLP64 int=long=32, longlong=pointer=64
println(Int.SIZE_BITS)
}
//0 <= key, value <= 10^6
//At most 10^4 calls will be made to put, get, and remove.
class MyHashMap {
private val size = 0x1fff //13bits= 8192
private val slot = arrayOfNulls<LinkedList<Pair<Int, Int>>>(size)
fun put(key: Int, value: Int) {
val idx = key xor key shr size xor key shr 2 * size
slot[idx].apply {
if (this == null) slot[idx] = LinkedList(listOf(key to value))
else {
removeIf { key == it.first }
add(key to value)
}
}
}
fun get(key: Int): Int {
val idx = key xor key shr size xor key shr 2 * size
return slot[idx]?.firstOrNull { it.first == key }?.second ?: -1
}
fun remove(key: Int) {
val idx = key xor key shr size xor key shr 2 * size
slot[idx]?.apply { //1633ms 6.5%, 1569ms 6.5%
iterator().apply {
while (hasNext()) { // remove FIRST elements if satisfy
if (next().first == key) {
remove()
break
}
}
}
if (size == 0) slot[idx] = null
}
// slot[idx]?.apply { //1718ms 6.5%, 1260ms 9.1%
// removeIf { it.first == key } // remove ALL elements if satisfy
// if (size == 0) slot[idx] = null
// }
}
}
//=========
class MyHashMap0 { //419ms 92%
private val map = mutableMapOf<Int, Int>()
fun put(key: Int, value: Int) = map.put(key, value)
fun get(key: Int): Int = map.getOrDefault(key, -1)
fun remove(key: Int) = map.remove(key)
}
} | 0 | Kotlin | 0 | 0 | 5e5731c1ca55c68eb40722c035d2d9e28c190281 | 22,193 | LeetCode | Apache License 2.0 |
src/main/kotlin/suggestions/KtSuggestions2.kt | hermannhueck | 46,933,495 | false | {"Java": 53536, "Scala": 43388, "Kotlin": 4114} | @file:JvmName("KtSuggestions2")
package suggestions
private val MAX_WORDS = 13
data class Suggestion2(val text: String) {
override fun toString() = text
}
private val INPUT = listOf("The", "moon", "is", "not", "a", "planet", "and", "also", "not", "a", "star", ".",
"But", ",", "I", "digress", "we", "people", "are", "so", "irrational", ".")
private val STOPWORDS = setOf("The", "a", "is")
fun main(args: Array<String>) {
makeSuggestions(maxWords(args), INPUT, STOPWORDS).forEach(::println)
}
private fun maxWords(args: Array<String>): Int {
if (args.isEmpty())
return MAX_WORDS
try {
val maxWords = Integer.parseInt(args[0])
return if (maxWords < 1) 1 else maxWords
} catch (e: NumberFormatException) {
return MAX_WORDS
}
}
private fun makeSuggestions(maxWords: Int,
words: List<String>,
stopWords: Set<String>): List<Suggestion2> {
val purged = words
.filter { e -> !stopWords.contains(e) }
.filter { e -> e.matches("\\w+".toRegex()) }
val maxWords2 = if (maxWords > purged.size) purged.size else maxWords
println("----- maxWords = " + maxWords2)
println("----- purged.size = " + purged.size)
println("----- purged = " + purged)
return suggestions(maxWords2, purged)
.map(::Suggestion2)
}
private fun suggestions(maxWords: Int, words: List<String>): List<String> =
(0..words.size - maxWords + 1 - 1)
.flatMap { index ->
combinations(index, maxWords, words)
}
private fun combinations(index: Int, maxWords: Int, words: List<String>): List<String> =
(index..index + maxWords - 1)
.map { i -> words[i] }
.fold(emptyList<String>()) { acc, word ->
if (acc.isEmpty())
listOf(word)
else
acc.plus("${acc.last()} $word")
}
| 0 | Java | 0 | 0 | 4ff6af70ecec5847652fb593b9d70cde7db5256d | 1,996 | BrainTwisters | Apache License 2.0 |
src/Day03.kt | haitekki | 572,959,197 | false | {"Kotlin": 24688} | fun main() {
fun part1(input: String): Int {
return input.lines().map {
Pair(
it.subSequence(0, it.length/2),
it.subSequence(it.length/2, it.length)
).let { pair ->
var number = 0
for (fChar in pair.first) {
for (sChar in pair.second) {
when (fChar.compareTo(sChar)) {
0 -> {
number =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(fChar)+1
break
}
}
}
if (number > 0) break
}
number
}
}.sum()
}
fun part2(input: String): Int {
return input.lines().chunked(3).map {
var charList: CharSequence = ""
for (charF in it[0]) {
for (charS in it[1]) {
when (charF.compareTo(charS)) {
0 -> charList = "$charList + $charF"
}
}
}
var number = 0
for (charL in charList) {
for (charT in it [2]) {
when (charL.compareTo(charT)) {
0 -> {
number =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(charL)+1
break
}
}
}
}
number
}.sum()
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b7262133f9115f6456aa77d9c0a1e9d6c891ea0f | 1,774 | aoc2022 | Apache License 2.0 |
src/Day03.kt | bromhagen | 572,988,081 | false | {"Kotlin": 3615} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
line.substring(0, line.length/2).toSet()
.intersect(line.substring(line.length/2).toSet())
.map { char ->
char.code - if (char.isUpperCase()) 38 else 96
}
.first()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf {
it[0].toSet().intersect(it[1].toSet()).intersect(it[2].toSet()).map { char ->
char.code - if (char.isUpperCase()) 38 else 96
}.first()
}
}
// 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 | 0ee6d96e790d9ebfab882351b3949c9ba372cb3e | 885 | advent-of-code | Apache License 2.0 |
src/aoc2017/kot/Day03.kt | Tandrial | 47,354,790 | false | null | package aoc2017.kot
import itertools.cartProd
object Day03 {
fun partOne(input: Int): Int {
val size = Math.ceil(Math.sqrt(input.toDouble())).toInt()
val start: Pair<Int, Int> = Pair(size / 2, size / 2)
var len = 1
var x = start.first
var y = start.second
var value = 1
loop@ while (true) {
for ((x_off, y_off) in listOf(Pair(1, -1), Pair(-1, 1))) {
for (idx in 0 until len) {
value++
x += x_off
if (value == input) {
break@loop
}
}
for (idx in 0 until len) {
value++
y += y_off
if (value == input) {
break@loop
}
}
len++
}
}
return Math.abs(x - start.first) + Math.abs(y - start.second)
}
fun partTwo(input: Int): Int {
val size = Math.ceil(Math.sqrt(input.toDouble())).toInt()
val grid = Array(size) { IntArray(size) }
var x = size / 2
var y = size / 2
var len = 1
grid[x][y] = 1
while (true) {
for ((x_off, y_off) in listOf(Pair(1, -1), Pair(-1, 1))) {
for (idx in 0 until len) {
x += x_off
grid[x][y] = getValue(grid, x, y)
if (grid[x][y] >= input) {
return grid[x][y]
}
}
for (idx in 0 until len) {
y += y_off
grid[x][y] = getValue(grid, x, y)
if (grid[x][y] >= input) {
return grid[x][y]
}
}
len++
}
}
}
private fun getValue(grid: Array<IntArray>, x: Int, y: Int): Int {
return (-1..1).cartProd(2).map { grid[x + it[0]][y + it[1]] }.sum()
}
}
fun main(args: Array<String>) {
val input = 361527
println("Part One = ${Day03.partOne(input)}")
println("Part Two = ${Day03.partTwo(input)}")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 1,805 | Advent_of_Code | MIT License |
src/day21/d21_2.kt | svorcmar | 720,683,913 | false | {"Kotlin": 49110} | import kotlin.math.*
val weapons = listOf(
Item("Dagger", 8, 4, 0),
Item("Shortsword", 10, 5, 0),
Item("Warhammer", 25, 6, 0),
Item("Longsword", 40, 7, 0),
Item("Greataxe", 74, 8, 0)
)
val armors = listOf(
Item("Leather", 13, 0, 1),
Item("Chainmail", 31, 0, 2),
Item("Splintmail", 53, 0, 3),
Item("Bandedmail", 75, 0, 4),
Item("Platemail", 102, 0, 5)
) + Item("No armor", 0, 0, 0)
val rings = listOf(
Item("Damage +1", 25, 1, 0),
Item("Damage +2", 50, 2, 0),
Item("Damage +3", 100, 3, 0),
Item("Defense +1", 20, 0, 1),
Item("Defense +2", 40, 0, 2),
Item("Defense +3", 80, 0, 3)
) + Item("No ring", 0, 0, 0) + Item("No ring 2", 0, 0, 0)
data class Item(val label: String, val cost: Int, val damage: Int, val armor: Int)
data class Setup(val cost: Int, val damage: Int, val armor: Int)
fun main() {
val hp = 100
val input = ""
val (bossHp, bossDmg, bossArmor) = input.lines().map { it.split(" ").last().toInt() }.let { Triple(it[0], it[1], it[2]) }
val setups = mutableListOf<Setup>()
for (weapon in weapons) {
for (armor in armors) {
for (ring1 in rings) {
for (ring2 in rings) {
if (ring1 != ring2) {
setups.add(Setup(
weapon.cost + armor.cost + ring1.cost + ring2.cost,
weapon.damage + armor.damage + ring1.damage + ring2.damage,
weapon.armor + armor.armor + ring1.armor + ring2.armor,
))
}
}
}
}
}
setups.sortBy { -it.cost }
for (setup in setups) {
val playerTurns = ceil((hp.toDouble() / max(bossDmg - setup.armor, 1))).toInt()
val bossTurns = ceil((bossHp.toDouble() / max(setup.damage - bossArmor, 1))).toInt()
if (playerTurns < bossTurns) {
println(setup.cost)
break
}
}
}
| 0 | Kotlin | 0 | 0 | cb097b59295b2ec76cc0845ee6674f1683c3c91f | 1,803 | aoc2015 | MIT License |
src/test/kotlin/Day03.kt | christof-vollrath | 317,635,262 | false | null | import io.kotest.core.datatest.forAll
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
/*
--- Day 3: Toboggan Trajectory ---
See https://adventofcode.com/2020/day/3
*/
fun parseTreeArray(input: String): TobogganTreeArray = TobogganTreeArray(
input.split("\n").map {
it.trim().toList()
}
)
class TobogganTreeArray(val array: List<List<Char>>) {
operator fun get(x: Int, y: Int) = array[y][x % array[y].size]
fun countTrees(dx: Int = 3, dy: Int = 1) = (0 until size / dy).map { i ->
get(i * dx, i * dy)
}
.count { it == '#' }
fun multiplySlopeCounts(slopes: List<List<Int>>) = slopes.map { slope ->
val (dx, dy) = slope
countTrees(dx, dy)
}.fold(1L) { m, count -> m * count }
val size get() = array.size
}
val simpleExample = """
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
""".trimIndent()
class Day03_Part1_Example : FunSpec({
val treeArray = parseTreeArray(simpleExample)
context("parse") {
test("should be parsed correctly") {
treeArray.size shouldBe 11
treeArray[0, 1] shouldBe '#'
}
}
context("get") {
test("pattern should be repeated to the right") {
treeArray[11, 0] shouldBe '.'
treeArray[30, 10] shouldBe '#'
}
}
context("count trees") {
val count = treeArray.countTrees()
test("should have counted trees") {
count shouldBe 7
}
}
})
class Day03_Part1: FunSpec({
val input = readResource("day03Input.txt")!!
val treeArray = parseTreeArray(input)
val count = treeArray.countTrees()
test("solution") {
count shouldBe 292
}
})
val slopes = listOf(
listOf(1, 1),
listOf(3, 1),
listOf(5, 1),
listOf(7, 1),
listOf(1, 2),
)
class Day03_Part2_Example : FunSpec({
val treeArray = parseTreeArray(simpleExample)
context("count trees with different slopes") {
data class SlopeTestCase(val dx: Int, val dy: Int, val expected: Int)
context("count chars") {
forAll(
SlopeTestCase(1, 1, 2),
SlopeTestCase(3, 1, 7),
SlopeTestCase(5, 1, 3),
SlopeTestCase(7, 1, 4),
SlopeTestCase(1, 2, 2),
) { (dx, dy, expected) ->
val count = treeArray.countTrees(dx, dy)
count shouldBe expected
}
}
val count = treeArray.countTrees()
test("should have counted trees") {
count shouldBe 7
}
}
context("multiply tree count") {
val multipliedCounts = treeArray.multiplySlopeCounts(slopes)
multipliedCounts shouldBe 336
}
})
class Day03_Part2: FunSpec({
val input = readResource("day03Input.txt")!!
val treeArray = parseTreeArray(input)
val multipliedCounts = treeArray.multiplySlopeCounts(slopes)
test("solution") {
multipliedCounts shouldBe 9354744432L
}
})
| 1 | Kotlin | 0 | 0 | 8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8 | 3,146 | advent_of_code_2020 | Apache License 2.0 |
src/Day12.kt | carotkut94 | 572,816,808 | false | {"Kotlin": 7508} | fun main() {
val input = readInput("Day12")
lateinit var start: Pair<Int, Int> // starting indexes
lateinit var end: Pair<Int, Int> // target indexes
val allA: MutableList<Pair<Int, Int>> = mutableListOf() // all positions with minimum elevation
val grid = buildList {
input.forEach {
add(it.toCharArray())
}
}.toMutableList()
grid.forEachIndexed { i, row ->
row.forEachIndexed { j, value ->
when (value) {
'S' -> {
start = i to j
allA.add(i to j)
grid[i][j] = 'a' // let's mark S as 'a' so that while traversing we don't have to do any special handling for 'S' on + -
}
'E' -> {
end = i to j
grid[i][j] = 'z' // AS E is max, and z is also max, replace E with z, so that we don't need special handling for E when handling operations + - and store the location of E as end
}
'a' -> {
allA.add(i to j) // store all minimum points to solve for part 2
}
}
}
}
fun traverse(grid: MutableList<CharArray>, start: Pair<Int, Int>, end: Pair<Int, Int>): Int {
val moves = listOf(0 to 1, 1 to 0, 0 to -1, -1 to 0)
val q = ArrayDeque<Pair<Pair<Int, Int>, Int>>()
q.add(start to 0)
val visited = mutableSetOf<Pair<Int, Int>>()
while (q.iterator().hasNext()) {
val (position, distance) = q.removeFirst()
if (position == end) {
return distance
}
if (!visited.contains(position)) {
visited.add(position)
val (x, y) = position
moves.forEach { (dx, dy) ->
if (x + dx in 0 until grid.size && (y + dy) in 0 until grid[0].size && (grid[x + dx][y + dy].code - grid[x][y].code) <= 1) {
q.add(element = ((x + dx) to (y + dy)) to distance + 1)
}
}
}
}
return Int.MAX_VALUE
}
println(traverse(grid, start, end))
val allStart = buildList {
allA.forEach {
add(traverse(grid, it, end))
}
}.min()
print(allStart)
} | 0 | Kotlin | 0 | 0 | ef3dee8be98abbe7e305e62bfe8c7d2eeff808ad | 2,336 | aoc-2022 | Apache License 2.0 |
src/Day15/December15.kt | Nandi | 47,216,709 | false | null | package Day15
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.stream.Stream
/**
* Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right
* balance of ingredients.
*
* Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you
* could use to finish the recipe (your puzzle input) and their properties per teaspoon:
*
* - capacity (how well it helps the cookie absorb milk)
* - durability (how well it keeps the cookie intact when full of milk)
* - flavor (how tasty it makes the cookie)
* - texture (how it improves the feel of the cookie)
* - calories (how many calories it adds to the cookie)
*
* You can only measure ingredients in whole-teaspoon amounts accurately, and you have to be accurate so you can
* reproduce your results in the future. The total score of a cookie can be found by adding up each of the properties
* (negative totals become 0) and then multiplying together everything except calories.
*
* Part 1
*
* Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie
* you can make?
*
* Part 2
*
* Your cookie recipe becomes wildly popular! Someone asks if you can make another recipe that has exactly 500 calories
* per cookie (so they can use it as a meal replacement). Keep the rest of your award-winning process the same (100
* teaspoons, same ingredients, same scoring system).
*
* Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie
* you can make with a calorie total of 500?
*
* Created by Simon on 16/12/2015.
*/
data class Ingredient(val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int, var amount: Int = 0)
class December15 {
fun main() {
val lines = loadFile("src/Day15/15.dec_input.txt")
var ingredientList = arrayListOf<Ingredient>()
for (line in lines) {
val (name, ingredients) = line.split(":")
if (name !is String || ingredients !is String) return
val (capacity, durability, flavor, texture, calories) = ingredients.replace(Regex(" \\w+ "), "").split(",")
if (capacity !is String || durability !is String || flavor !is String || texture !is String || calories !is String) return
ingredientList.add(Ingredient(name, capacity.toInt(), durability.toInt(), flavor.toInt(), texture.toInt(), calories.toInt()))
}
val combinations = arrayListOf<List<Int>>()
val counts = ingredientList.map { i -> 0 }.toArrayList()
combinations(100, 0, combinations, counts)
val answer1 = combinations
.asSequence()
.map { amounts -> sumAll(ingredientList, amounts) }
.max()
val answer2 = combinations
.asSequence()
.filter { amounts -> sum(ingredientList, amounts, { i: Ingredient -> i.calories }) == 500 }
.map { amounts -> sumAll(ingredientList, amounts) }
.max();
println("The best cookie is has a score of $answer1")
println("The best cookie with exactly 500 calories has a score of $answer2")
}
private fun combinations(target: Int, index: Int, results: ArrayList<List<Int>>, list: ArrayList<Int>) {
for (i in 0..target) {
val newList = list.toArrayList()
newList[index] = i
if (index < list.size - 1 && newList.subList(0, index).asSequence().sumBy { v -> v } <= target) {
combinations(target, index + 1, results, newList)
}
if (index == list.size - 1 && newList.asSequence().sumBy { v -> v } == target) {
results.add(newList)
}
}
}
fun sumAll(list: List<Ingredient>, amounts: List<Int>): Int {
return sum(list, amounts, { i: Ingredient -> i.capacity }) *
sum(list, amounts, { i: Ingredient -> i.durability }) *
sum(list, amounts, { i: Ingredient -> i.flavor }) *
sum(list, amounts, { i: Ingredient -> i.texture })
}
fun sum(list: List<Ingredient>, amounts: List<Int>, property: (Ingredient) -> Int): Int {
var sum = 0
for (i in 0..list.size - 1) {
sum += property.invoke(list[i]) * amounts[i]
}
return Math.max(sum, 0)
}
fun loadFile(path: String): Stream<String> {
val input = Paths.get(path)
val reader = Files.newBufferedReader(input)
return reader.lines()
}
}
fun main(args: Array<String>) {
December15().main()
} | 0 | Kotlin | 0 | 0 | 34a4b4c0926b5ba7e9b32ca6eeedd530f6e95bdc | 4,794 | adventofcode | MIT License |
src/Day02.kt | olezhabobrov | 572,687,414 | false | {"Kotlin": 27363} | fun main() {
fun part1(input: List<String>): Int =
input.sumOf { line ->
val (a, b) = line.split(" ")
when (b) {
"X" -> 1 + when (a) {
"A" -> 3
"B" -> 0
"C" -> 6
else -> error("")
}
"Y" -> 2 + when (a) {
"A" -> 6
"B" -> 3
"C" -> 0
else -> error("")
}
"Z" -> 3 + when (a) {
"A" -> 0
"B" -> 6
"C" -> 3
else -> error("")
}
else -> error("Shouldn't be here")
}
}
fun part2(input: List<String>): Int =
input.sumOf { line ->
val (a, b) = line.split(" ")
when (b) {
"X" -> 0 + when (a) {
"A" -> 3
"B" -> 1
"C" -> 2
else -> error("")
}
"Y" -> 3 + when (a) {
"A" -> 1
"B" -> 2
"C" -> 3
else -> error("")
}
"Z" -> 6 + when (a) {
"A" -> 2
"B" -> 3
"C" -> 1
else -> error("")
}
else -> error("Shouldn't be here")
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 31f2419230c42f72137c6cd2c9a627492313d8fb | 1,800 | AdventOfCode | Apache License 2.0 |
src/Day01.kt | Redstonecrafter0 | 571,787,306 | false | {"Kotlin": 19087} |
fun main() {
fun parse(input: List<String>): List<Int> {
val separators = listOf(-1) + input.withIndex().filter { it.value == "" }.map { it.index } + (input.lastIndex + 1)
val elves = separators.windowed(2).map { input.subList(it[0] + 1, it[1]) }
return elves.map { it.sumOf { i -> i.toInt() } }
}
fun part1(input: List<String>): Int {
val sums = parse(input)
return sums.max()
}
fun part2(input: List<String>): Int {
val sortedSums = parse(input).sortedBy { it }.reversed()
return sortedSums.subList(0, 3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858 | 843 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2021/Day12.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day12: AdventDay(2021, 12) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day12()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun parseCave(input: List<String>): Map<Cave, List<Cave>> {
return input.map { it.split("-") }.flatMap { (left, right) ->
listOf(Cave(left) to Cave(right), Cave(right) to Cave(left))
}.groupBy({ it.first}, {it.second})
}
fun solve(graph: Map<Cave, List<Cave>>, cave: Cave = Cave("start"), visited: Set<Cave> = hashSetOf(cave), canVisitTwice: Boolean = false): Int {
return graph[cave]!!.sumOf { destination ->
when {
destination.end -> 1
destination.start -> 0
destination.big -> solve(graph, destination, visited + destination, canVisitTwice)
destination !in visited -> solve(graph, destination, visited + destination, canVisitTwice)
canVisitTwice -> solve(graph, destination, visited + destination, false)
else -> 0
}
}
}
fun part1(): Int {
return solve(inputGraph)
}
val inputGraph = parseCave(inputAsLines)
fun part2(): Int {
return solve(inputGraph, canVisitTwice = true)
}
data class Cave(val id: String) {
val big: Boolean = id[0].isUpperCase()
val start = id == "start"
val end = id == "end"
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 1,653 | adventofcode | MIT License |
src/Day03.kt | xiaofeiMophsic | 575,326,884 | false | null |
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val half = it.length / 2
val firstComp = it.substring(0, half)
val secondComp = it.substring(half)
val result: Int = firstComp.find { c -> secondComp.contains(c, false) }?.let { common ->
if (common.isUpperCase()) {
common.code - 'A'.code + 27
} else {
common.code - 'a'.code + 1
}
} ?: 0
result
}
}
fun part2(input: List<String>): Int {
val rucksacks = input.foldIndexed(mutableListOf<MutableList<String>>()) {index, lists, current ->
if (index % 3 == 0) {
lists.add(mutableListOf())
}
lists.lastOrNull()?.add(current) ?: run {
lists.add(mutableListOf<String>().apply {
this + current
})
}
lists
}
return rucksacks.sumOf { rucksack ->
rucksack.fold(mutableSetOf<Char>()) { acc, current->
if (acc.isEmpty()) {
acc += current.toSet()
acc
} else {
acc.intersect(current.toSet()).toMutableSet()
}
}.map { common->
if (common.isUpperCase()) {
common.code - 'A'.code + 27
} else {
common.code - 'a'.code + 1
}
}.singleOrNull() ?: 0
}
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 13e5063928c0eb6416ce266e2083816ca78b8240 | 1,683 | aoc-kotlin | Apache License 2.0 |
src/day14/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day14
import Coord
import day06.main
import readInput
fun main() {
operator fun Coord.rangeTo(other: Coord) = (minOf(first, other.first)..maxOf(first, other.first)).flatMap { x ->
(minOf(second, other.second)..maxOf(second, other.second)).map { y -> Coord(x, y) }
}
fun String.toCoord() = split(",").map(String::toInt).let { (x, y) -> Coord(x, y) }
fun String.toCorners() = split(" -> ").map(String::toCoord)
fun parse(input: List<String>): Pair<Set<Coord>, Int> =
input.flatMap { it.toCorners().zipWithNext { a, b -> a..b }.flatten() }.toSet()
.let { coord -> coord to coord.maxOf(Coord::second) }
fun part1(initial: Set<Coord>, max: Int) = generateSequence(initial) { current ->
generateSequence(Coord(500, 0)) { sand ->
listOf(
sand.copy(second = sand.second + 1),
sand.copy(first = sand.first - 1, second = sand.second + 1),
sand.copy(first = sand.first + 1, second = sand.second + 1)
).firstOrNull {
it !in current && it.second <= max
}
}.last().takeIf {
it.second < max
}?.let {
current + it
}
}.count() - 1
fun part2(initial: Set<Coord>, max: Int) =
generateSequence(Pair(initial, setOf(Coord(500, 0)))) { (current, newSand) ->
fun isRock(coord: Coord) = coord in initial || coord.second == (max + 2)
buildSet {
newSand.forEach { sand ->
sand.copy(second = sand.second + 1).takeUnless(::isRock)?.let(::add)
sand.copy(first = sand.first - 1, second = sand.second + 1).takeUnless(::isRock)?.let(::add)
sand.copy(first = sand.first + 1, second = sand.second + 1).takeUnless(::isRock)?.let(::add)
}
}.takeIf { it.isNotEmpty() }?.let { (current + newSand) to it }
}.last().first.size - initial.size
val (input, max) = parse(readInput(::main.javaClass.packageName))
println("Part1=\n" + part1(input, max))
println("Part2=\n" + part2(input, max))
} | 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 2,136 | AOC2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day13.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.IntNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
private val objectMapper = jacksonObjectMapper()
sealed class Comp {
abstract operator fun compareTo(right: Comp): Int
data class Integer(val n: Int): Comp() {
override operator fun compareTo(right: Comp) = when(right) {
is Integer -> n.compareTo(right.n)
is Array -> Array(listOf(this)).compareTo(right)
}
override fun toString() = n.toString()
}
data class Array(val contents: List<Comp>): Comp() {
override fun compareTo(right: Comp): Int = when (right) {
is Integer -> this.compareTo(Array(listOf(right)))
is Array -> when {
right.contents.isEmpty() && this.contents.isEmpty() -> 0
right.contents.isEmpty() -> 1
contents.isEmpty() -> -1
contents.first().compareTo(right.contents.first()) == 0 -> tail().compareTo(right.tail())
else -> contents.first().compareTo(right.contents.first())
}
}
private fun tail() = Array(contents.drop(1))
override fun toString() = contents.toString()
}
}
fun main() {
val testInput = """[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]""".split("\n")
fun parseRow(it: String): Comp {
val arr: ArrayNode = objectMapper.readValue(it)
return arr.toComp()
}
fun part1(input: List<String>): Int {
return blocksOfLines(input).withIndex().sumOf { (index, block) ->
val (left, right) = block.map { parseRow(it) }
if (left < right) index + 1 else 0
}
}
fun part2(input: List<String>): Int {
val specials = listOf("[[2]]", "[[6]]")
val sorted = (input + specials)
.filter(String::isNotBlank)
.map(::parseRow)
.sortedWith { x, y -> x.compareTo(y) }
val dividers = sorted.indices.filter { sorted[it].toString() in specials }
.map { it + 1}
return dividers.reduce(Int::times)
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 13)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 13).toList()
println(part1(puzzleInput))
println(part2(testInput))
println(part2(puzzleInput))
}
private fun JsonNode.toComp(): Comp = when (this) {
is ArrayNode -> toComp()
is IntNode -> toComp()
else -> throw UnsupportedOperationException("Unexpected node: $this")
}
private fun ArrayNode.toComp(): Comp {
return Comp.Array(this.map { it.toComp() })
}
private fun IntNode.toComp(): Comp {
return Comp.Integer(intValue())
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 3,125 | aoc-2022-kotlin | Apache License 2.0 |
src/day07/Day07.kt | EdwinChang24 | 572,839,052 | false | {"Kotlin": 20838} | package day07
import readInput
fun main() {
part1()
part2()
}
fun part1() = common { sizes ->
println(sizes.sumOf { if (it <= 100000) it else 0 })
}
fun part2() = common { sizes ->
val currentFree = 70000000 - sizes.max()
println(sizes.filter { currentFree + it >= 30000000 }.min())
}
fun common(andThen: (sizes: MutableList<Int>) -> Unit) {
val input = readInput(7)
class Thing(
val dir: Boolean,
val contents: MutableList<Thing>?,
val outer: Thing?,
val size: Int?
)
val root = Thing(true, mutableListOf(), null, null)
var pwd = root
var running = ""
for (line in input) {
fun handleNextCommand() {
if (line.removePrefix("$ ").startsWith("cd")) {
pwd = if (line.endsWith("..")) {
pwd.outer ?: pwd
} else {
pwd.contents!!.add(Thing(true, mutableListOf(), pwd, null))
pwd.contents!!.last()
}
} else if (line.removePrefix("$ ").startsWith("ls")) {
running = "ls"
}
}
when (running) {
"" -> handleNextCommand()
"ls" -> {
if (line.startsWith("$")) {
handleNextCommand()
} else {
val things = line.split(" ")
if (things[0] == "dir") {
pwd.contents!!.add(Thing(true, mutableListOf(), pwd, null))
} else {
pwd.contents!!.add(Thing(false, null, pwd, things[0].toInt()))
}
}
}
}
}
val sizes = mutableListOf<Int>()
fun Thing.size(): Int = if (dir) {
var total = 0
for (thing in contents!!) total += thing.size()
total
} else {
size!!
}.also { if (dir) sizes += it }
root.size()
andThen(sizes)
}
| 0 | Kotlin | 0 | 0 | e9e187dff7f5aa342eb207dc2473610dd001add3 | 1,958 | advent-of-code-2022 | Apache License 2.0 |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day2/Day2.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day2
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2023.DayOf2023
/**
* See [Year 2023, Day 2](https://adventofcode.com/2023/day/2)
*/
object Day2 : DayOf2023(2) {
private val GAME_PATTERN = "Game \\d+: ".toRegex()
override fun first(): Any? {
return minCubes()
.withIndex()
.filter { (_, map) ->
map.getOrDefault("red", 0) <= 12 && map.getOrDefault("green", 0) <= 13 && map.getOrDefault("blue", 0) <= 14
}
.sumOf { it.index + 1 }
}
override fun second(): Any? {
return minCubes()
.sumOf { map ->
map.getOrDefault("red", 0) * map.getOrDefault("green", 0) * map.getOrDefault("blue", 0)
}
}
private fun minCubes() = lines
.asSequence()
.map { line -> line.replace(GAME_PATTERN, "") }
.map { line -> line.split("; ") }
.map { series ->
series
.map { cubes ->
cubes.split(", ")
.map { it.split(" ").toPair() }
.associate { it.second to it.first.toInt() }
}
.fold(emptyMap<String, Int>()) { acc, value ->
(acc.toList() + value.toList())
.groupBy { it.first }
.mapValues { colors -> colors.value.maxOf { it.second } }
}
}
}
fun main() = SomeDay.mainify(Day2)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,340 | adventofcode | MIT License |
src/main/kotlin/com/chriswk/aoc/advent2022/Day7.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2022
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day7: AdventDay(2022, 7) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day7()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun parseCommands(input: List<String>): MutableMap<String, Directory> {
val directories : MutableMap<String, Directory> = mutableMapOf()
var currentDir : Directory? = null
input.forEach { line ->
if (line.startsWith("$")) {
val args = line.split(" ")
when (args[1]) {
"cd" -> {
currentDir = when (args[2]) {
"/" -> {
directories.computeIfAbsent("/") { path -> Directory(path = "/") }
}
".." -> {
currentDir?.parent ?: directories["/"]
}
else -> {
val key = path(currentDir!!.path, args[2])
currentDir = directories.computeIfAbsent(key) { path ->
Directory(
path = path,
parent = currentDir ?: directories["/"]
)
}
currentDir
}
}
}
"ls" -> {}
}
}
else if (line.startsWith("dir")) {
val (_, name) = line.split(" ")
val key = path(currentDir!!.path, name)
val dir = directories.computeIfAbsent(key) { Directory(path = it, parent = currentDir!!) }
currentDir!!.folders[name] = dir
} else {
val (size, name) = line.split(" ")
val file = File(size.toLong(10), name)
currentDir!!.files.add(file)
}
}
return directories
}
fun path(folder: String, file: String): String {
return listOf(folder, file).joinToString(separator = "/").replace("//", "/")
}
fun foldersSmallerThan(bytes: Long, tree: Map<String, Directory>): List<Long> {
return tree.values.asSequence().map { it.fileSize() }.filter { it < bytes }.toList()
}
fun candidateSize(folders: List<Long>, totalSize: Long, requiredSize: Long): Long {
val fileSizes = folders.sorted()
val freeSpace = totalSize - fileSizes.last()
val missingSpace = requiredSize - freeSpace
return fileSizes.first { it > missingSpace }
}
fun part1(): Long {
return foldersSmallerThan(100000L, parseCommands(inputAsLines)).sum()
}
fun part2(): Long {
return candidateSize(parseCommands(inputAsLines).values.map { it.fileSize() }, 70000000, 30000000)
}
data class Directory(val path: String, val parent: Directory? = null, val files: MutableSet<File> = mutableSetOf(), val folders: MutableMap<String, Directory> = mutableMapOf()) {
fun fileSize(): Long {
val fileSize = files.sumOf { it.size }
val folderSize = folders.values.map { it.fileSize() }
return fileSize + folderSize.sum()
}
override fun toString(): String {
return "Directory(path='$path')"
}
}
data class File(val size: Long, val name: String)
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 3,814 | adventofcode | MIT License |
src/Day10.kt | coolcut69 | 572,865,721 | false | {"Kotlin": 36853} | fun main() {
fun createRegister(inputs: List<String>): Register {
val register = Register()
for (s in inputs) {
if (s == "noop") {
register.addInstruction(Instruction("noop", 0))
} else {
register.addInstruction(Instruction("addx", s.split(" ")[1].toInt()))
}
}
return register
}
fun part1(inputs: List<String>): Int {
val register = createRegister(inputs)
val signalStrengths: MutableList<Int> = ArrayList()
for (i in 20..220 step 40) {
signalStrengths.add(register.valueAt(i) * i)
}
return signalStrengths.sum()
}
fun part2(inputs: List<String>): Int {
val register = createRegister(inputs)
for (i in 0..220 step 40) {
var display = ""
for (cycle in i..i + 39) {
val valueAt = register.valueAt(cycle + 1)
if (cycle - i == valueAt || cycle - i == valueAt + 1 || cycle - i == valueAt - 1) {
display += "#"
} else {
display += "."
}
}
println(display)
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == 0)
val input = readInput("Day10")
// println(part1(input))
check(part1(input) == 15680)
println(part2(input))
// check(part2(input) == 0)
}
class Register {
private val instructions: MutableList<Instruction> = ArrayList()
private val registerX: MutableList<Int> = ArrayList()
init {
registerX.add(1)
}
fun valueAt(pos: Int): Int {
return registerX.subList(0, pos).sum()
}
fun addInstruction(instruction: Instruction) {
this.instructions.add(instruction)
if (instruction.action == "noop") {
registerX.add(0)
} else {
registerX.add(0)
registerX.add(instruction.number)
}
}
}
data class Instruction(val action: String, val number: Int)
| 0 | Kotlin | 0 | 0 | 031301607c2e1c21a6d4658b1e96685c4135fd44 | 2,188 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day09.kt | arhor | 572,349,244 | false | {"Kotlin": 36845} | fun main() {
val input = readInput {}
println("Part 1: " + solvePuzzle(input, tailSize = 1))
println("Part 2: " + solvePuzzle(input, tailSize = 9))
}
private fun solvePuzzle(input: List<String>, tailSize: Int): Int {
val rope = MutableList(1 + tailSize) { Point(0, 0) }
val visited = HashSet<Point>().apply { add(rope.last()) }
for (line in input) {
val (direction, steps) = line.split(" ").let { it[0] to it[1].toInt() }
repeat(times = steps) {
for ((index, curr) in rope.withIndex()) {
rope[index] = if (index == 0) {
when (direction) {
"U" -> curr.copy(y = curr.y + 1)
"R" -> curr.copy(x = curr.x + 1)
"D" -> curr.copy(y = curr.y - 1)
"L" -> curr.copy(x = curr.x - 1)
else -> throw IllegalStateException("Unsupported direction: $direction")
}
} else {
val prev = rope[index - 1]
if (curr !in prev.adjacentPoints()) {
curr.enclosedTo(prev).also {
if (index == rope.lastIndex) {
visited += it
}
}
} else {
curr
}
}
}
}
}
return visited.size
}
| 0 | Kotlin | 0 | 0 | 047d4bdac687fd6719796eb69eab2dd8ebb5ba2f | 1,476 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | enum class Sign(val value: Int, val symbol: Char) {
rock(1, 'A'),
paper(2, 'B'),
scissors(3, 'C');
companion object {
infix fun from(value: Int): Sign {
return Sign.values().first { it.value == value }
}
infix fun from(symbol: Char): Sign {
return Sign.values().first { it.symbol == symbol }
}
infix fun from2(symbol: Char): Sign {
return from(symbol - ('X' - 'A'))
}
}
}
enum class WinLoseDraw(val symbol: Char, val score: Int, val adj: Int) {
lose('X', 0, 2),
draw('Y', 3, 0),
win('Z', 6, 1);
companion object {
infix fun from(symbol: Char): WinLoseDraw {
return WinLoseDraw.values().first { it.symbol == symbol }
}
fun with(them:Sign, us:Sign): WinLoseDraw {
val adj = (us.value - them.value + 3) % 3
return WinLoseDraw.values().first { it.adj == adj }
}
}
fun signWith(sign: Sign): Sign {
val value = (sign.ordinal + this.adj) % 3 + 1
return Sign from value
}
}
fun main() {
fun usAndThem1(line: String): Pair<Sign, Sign> {
return Pair(Sign from line[0] , Sign from2 line[2])
}
fun usAndThem2(line: String): Pair<Sign, Sign> {
val them = Sign from line[0]
val us = WinLoseDraw.from(line[2]).signWith(them)
return Pair(them, us)
}
fun score(them: Sign, us: Sign): Int {
val wld = WinLoseDraw.with(them, us)
return us.value + wld.score
}
fun part1(input: List<String>): Int {
var total_score = 0
for (line in input) {
val (them, us) = usAndThem1(line)
total_score += score(them, us)
}
return total_score
}
fun part2(input: List<String>): Int {
var total_score = 0
for (line in input) {
val (them, us) = usAndThem2(line)
total_score += score(them, us)
}
return total_score
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("1-input")
// check(part1(testInput) == 1)
val input = readInput("day2")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 2,249 | 2022-aoc-kotlin | Apache License 2.0 |
src/day17/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day17
import day17.MoveDirection.*
import util.readInput
import util.repeatingIterator
import util.shouldBe
import kotlin.math.max
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 3068
testInput.part2() shouldBe 1514285714288L
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private data class Point(val x: Int, val y: Long) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
companion object {
val down = Point(0, -1)
}
}
private class Shape(
val points: Set<Point>,
val width: Int = points.maxOf { it.x },
) {
constructor(vararg points: Point) : this(points.toSet())
fun withOffset(offset: Point) = Shape(points.mapTo(mutableSetOf()) { it + offset }, width)
}
private val allShapes = listOf(
Shape(
Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0),
),
Shape(
/* */ Point(1, 2), /* */
Point(0, 1), Point(1, 1), Point(2, 1),
/* */ Point(1, 0), /* */
),
Shape(
/* */ /* */ Point(2, 2),
/* */ /* */ Point(2, 1),
Point(0, 0), Point(1, 0), Point(2, 0),
),
Shape(
Point(0, 3),
Point(0, 2),
Point(0, 1),
Point(0, 0),
),
Shape(
Point(0, 1), Point(1, 1),
Point(0, 0), Point(1, 0),
),
)
private class Board {
val width = 7
val points = mutableSetOf<Point>()
var height = 0L
private set
var stones = 0L
private set
infix fun intersects(shape: Shape) = shape.points.any { it.y <= 0 || it.x < 0 || it.x >= width || it in points }
operator fun plusAssign(shape: Shape) {
points += shape.points
height = max(height, shape.points.maxOf { it.y })
stones++
}
}
private enum class MoveDirection(val dx: Int) { Left(-1), Right(1) }
private class Input(
val directions: List<MoveDirection>,
)
private fun List<String>.parseInput(): Input {
val directions = first().map { if (it == '<') Left else Right }
return Input(directions)
}
private fun Board.tryMove(shape: Shape, offset: Point): Shape? {
return shape.withOffset(offset).takeUnless { this intersects it }
}
private fun simulate(
board: Board,
rockCount: Int,
directions: Iterator<MoveDirection>,
rocks: Iterator<Shape>,
): Int {
var pushCount = 0
repeat(rockCount) {
var currRock = rocks.next().withOffset(Point(2, board.height + 4))
while (true) {
pushCount++
val dx = directions.next().dx
val afterMove = board.tryMove(currRock, Point(dx, 0))
if (afterMove != null) currRock = afterMove
val afterFall = board.tryMove(currRock, Point.down)
if (afterFall != null) {
currRock = afterFall
} else {
board += currRock
break
}
}
}
return pushCount
}
private fun Input.part1(): Long {
val directions = directions.repeatingIterator()
val rocks = allShapes.repeatingIterator()
val board = Board()
simulate(board, 2022, directions, rocks)
return board.height
}
private fun Input.part2(): Long {
val directions = directions.repeatingIterator()
val rocks = allShapes.repeatingIterator()
val board = Board()
val maxPeriods = 1_000_000_000_000L / 5
var periodsSimulated = 0L
var lastRun = emptyList<Log>()
while (true) {
val currRun = mutableListOf<Log>()
val seenMoveIndices = mutableSetOf(directions.nextIndex())
do {
val h1 = board.height
simulate(board, 5, directions, rocks)
periodsSimulated++
val h2 = board.height
val i2 = directions.nextIndex()
val cycleEnded = i2 in seenMoveIndices
seenMoveIndices += i2
currRun += Log(i2, (h2 - h1).toInt())
} while (!cycleEnded)
if (currRun deepEquals lastRun) break
lastRun = currRun
}
val cycleHeight = lastRun.sumOf { it.dy }
val cycleSize = lastRun.size
val periodsToGo = maxPeriods - periodsSimulated
val completeCyclesHeight = periodsToGo / cycleSize * cycleHeight
val lastPartialCycleHeight = lastRun.take((periodsToGo % cycleSize).toInt()).sumOf { it.dy }
return board.height + completeCyclesHeight + lastPartialCycleHeight
}
private data class Log(val i: Int, val dy: Int)
private infix fun List<Log>.deepEquals(other: List<Log>): Boolean {
if (size != other.size) return false
for ((a, b) in asSequence().zip(other.asSequence())) {
if (a != b) return false
}
return true
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 4,894 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/tonnoz/adventofcode23/day6/Six.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day6
import com.tonnoz.adventofcode23.utils.readInput
import com.tonnoz.adventofcode23.utils.transpose
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.sqrt
object Six {
@JvmStatic
fun main(args: Array<String>) {
val input = "inputSix.txt".readInput()
problemOne(input.parseRaces())
problemTwo(input.parseRaces2())
}
private fun problemTwo(input: List<Long>){
val time = System.currentTimeMillis()
waysToWinConstantTime(input[0], input[1])
.also { println(it) }
println("Time p2: ${System.currentTimeMillis() - time} ms")
}
private fun problemOne(input: List<List<Long>>){
val time = System.currentTimeMillis()
input
.map { findAllBestHoldTimes(it[0], it[1]) }
.fold(1) { acc, curr -> acc * curr }
.also { println(it) }
println("Time p1: ${System.currentTimeMillis() - time} ms")
}
private fun List<String>.parseRaces() = this.map{"\\d+".toRegex().findAll(it).map { it.value.toLong() }.toList()}.transpose()
private fun List<String>.parseRaces2() = this.map{"\\d+".toRegex().findAll(it).map { it.value}.joinToString(separator = "").toLong()}
private fun findAllBestHoldTimes(raceTime: Long, recordTime: Long): Int {
val possibleHoldTimes = mutableListOf<Long>()
for (holdTime in 0..raceTime) {
val distance = holdTime * (raceTime - holdTime)
if (distance > recordTime) {
possibleHoldTimes.add(holdTime)
}
}
return possibleHoldTimes.size
}
private fun waysToWinConstantTime(time: Long, minDistance: Long): Long { //by <NAME>: https://github.com/timstokman
val sqrt = sqrt(time * time - 4 * minDistance.toDouble())
var minPressed = floor(0.5 * (time - sqrt)).toLong()
minPressed += if ((time - minPressed) * minPressed > minDistance) 0 else 1
var maxPressed = floor(0.5 * (sqrt + time)).toLong()
maxPressed += if ((time - maxPressed) * maxPressed > minDistance) 1 else 0
return max(0, maxPressed - minPressed)
}
private fun Int.bestHoldTimeForRace(): Int { // formula parabola
val optimalHoldTime = (this / 2.0).toInt()
return optimalHoldTime * (this - optimalHoldTime)
}
} | 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 2,201 | adventofcode23 | MIT License |
src/Day03.kt | jorander | 571,715,475 | false | {"Kotlin": 28471} | fun main() {
val day = "Day03"
fun List<String>.findCommonChar() =
this.drop(1).fold(this.first().toSet()) { acc, s -> s.toSet().intersect(acc) }.first()
fun calculatePriority(badge: Char) =
if (badge.isLowerCase()) {
badge - 'a' + 1
} else {
badge - 'A' + 27
}
fun part1(input: List<String>): Int {
return input.map { rucksack ->
rucksack.chunked(rucksack.length / 2)
.findCommonChar()
}.map(::calculatePriority).sum()
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map(List<String>::findCommonChar)
.map(::calculatePriority).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
val input = readInput(day)
check(part1(testInput) == 157)
val result1 = part1(input)
println(result1)
check(result1 == 7997)
check(part2(testInput) == 70)
val result2 = part2(input)
println(result2)
check(result2 == 2545)
}
| 0 | Kotlin | 0 | 0 | 1681218293cce611b2c0467924e4c0207f47e00c | 1,099 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2020/d10/Day10.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2020.d10
import com.groundsfam.advent.DATAPATH
import kotlin.io.path.div
import kotlin.io.path.useLines
private fun joltDifferences(adapters: List<Int>): Map<Int, Int> =
mutableMapOf<Int, Int>().apply {
adapters.forEachIndexed { i, num ->
if (i == 0) {
this[num] = 1
} else {
val diff = num - adapters[i - 1]
this[diff] = getOrDefault(diff, 0) + 1
}
}
this[3] = getOrDefault(3, 0) + 1
}
private fun countArrangements(adapters: List<Int>): Long {
val arrangementCounts = mutableMapOf(0 to 1L)
adapters.forEachIndexed { i, adapter ->
val arrangements = arrangementCounts[adapter]!!
repeat(3) { n ->
if (i + n + 1 < adapters.size) {
val nextAdapter = adapters[i + n + 1]
if (nextAdapter - adapter <= 3) {
arrangementCounts[nextAdapter] = arrangementCounts.getOrDefault(nextAdapter, 0) + arrangements
}
}
}
}
return arrangementCounts[adapters.last()]!!
}
fun main() {
val adapters = (DATAPATH / "2020/day10.txt").useLines { lines ->
lines.map { it.toInt() }.toList()
}.sorted()
joltDifferences(adapters).let {
it.getOrDefault(1, 0) * it.getOrDefault(3, 0)
}.also { println("Part one: $it") }
mutableListOf(0).apply {
addAll(adapters)
add(adapters.last() + 3)
}.let(::countArrangements)
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,571 | advent-of-code | MIT License |
src/Day07.kt | Ramo-11 | 573,610,722 | false | {"Kotlin": 21264} | // Source: https://github.com/DDihanov/Advent-Of-Code-2022-Kotlin/blob/master/src/main/kotlin/day07/Day7.kt
package day07
import java.io.File
sealed class Directory(
open val name: String,
open val files: MutableList<DirFile>,
open val directories: MutableList<Directory>
) {
data class Root(
override val name: String,
override val files: MutableList<DirFile> = mutableListOf(),
override val directories: MutableList<Directory> = mutableListOf()
) : Directory(name, files, directories) {
override fun toString(): String = "$name, ${calcSize()}"
}
data class Sub(
override val name: String,
override val files: MutableList<DirFile> = mutableListOf(),
override val directories: MutableList<Directory> = mutableListOf(),
val parent: Directory
) : Directory(name, files, directories) {
override fun toString(): String = "$name, ${calcSize()}"
}
}
data class DirFile(val size: Int, val name: String)
fun fileTreeParser(input: () -> List<String>): Directory.Root {
val root = Directory.Root("/")
var current: Directory = root
fun cd(command: String) {
current = when (command) {
"/" -> root
".." -> (current as Directory.Sub).parent
else -> current.findInCurrent(command)
}
}
fun ls(ls: String) {
val args = ls.split(' ')
when {
args.component1() == "dir" -> {
val toAddName = args.component2()
current.directories.add(Directory.Sub(name = toAddName, parent = current))
}
// is number
args.component1().toIntOrNull() != null -> {
val fileSize = args.component1()
val fileName = args.component2()
current.files.add(DirFile(fileSize.toInt(), fileName))
}
// theoretically not possible but still
else -> error("No such command $ls")
}
}
fun processInput(iterator: ListIterator<String>) {
val next = iterator.next()
val split = next.split(' ')
when (split.component1()) {
"$" -> when (split.component2()) {
"ls" -> {
iterator.asSequence()
.forEach {
if (it.startsWith("$")) {
// reset the marker to the previous iteration
// as the startsWith check has advanced one line ahead to check,
// so we need to revert or one line will be skipped
iterator.previous()
return
}
ls(it)
}
}
"cd" -> cd(split.component3())
}
}
}
fun processCommands(commands: List<String>) {
val iterator = commands.listIterator()
while (iterator.hasNext()) {
processInput(iterator)
}
}
processCommands(input())
return root
}
val root = fileTreeParser { File("src/Day07.txt").readLines() }
fun day71() = root
.accumulateDirs().map { it.calcSize() }
.filter { it < 100_000 }
.sortedDescending()
.sum()
const val TOTAL_SIZE = 70_000_000
const val NEEDED_SIZE = 30_000_000
fun day72(): Int {
val neededSpace = NEEDED_SIZE - (TOTAL_SIZE - root.calcSize())
return root.accumulateDirs()
.map { it.name to it.calcSize() }
.filter { it.second >= neededSpace }
.minByOrNull { it.second }!!
.second
}
fun main() {
println(day71())
println(day72())
}
fun Directory.accumulateDirs(): List<Directory> = this.directories.flatMap {
it.accumulateDirs()
} + this.directories
fun Directory.calcSize(): Int = this.files.sumOf { it.size } + this.directories.sumOf { it.calcSize() }
fun Directory.findInCurrent(name: String) = this.directories.first { it.name == name } | 0 | Kotlin | 0 | 0 | a122cca3423c9849ceea5a4b69b4d96fdeeadd01 | 4,044 | advent-of-code-kotlin | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions03.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
fun test3() {
val array1 = intArrayOf(2, 3, 1, 0, 2, 5, 3)
println("数组 1 重复的数字是:${array1.findRepeat1()}")
val array2 = intArrayOf(2, 3, 5, 4, 3, 2, 6, 7)
println("数组 2 重复的数字是:${array2.findRepeat2()}")
}
/**
* 题目一:寻找数组中重复的数字,数组长度 n,数字都在 0 ~ n-1 的范围内
*/
fun IntArray.findRepeat1(): Int {
forEachIndexed { index, i ->
if (index != i)
if (i == this[i]) return i else exchange(index, i)
}
throw IllegalArgumentException("该数组没有重复数字")
}
/**
* 题目二:同题目一,但不能修改数组,且数组长度 n + 1,数字在 1 ~ n 范围内;
* find2 函数使用二分查找,时间复杂度 O(nlogn),空间复杂度 O(1),
* 也可以使用辅助数组,时间复杂度 O(n),空间复杂度 O(n),这个解法比较简单,这里不给出。
*/
fun IntArray.findRepeat2(): Int = findRepeat2(1, size / 2, size - 1)
private tailrec fun IntArray.findRepeat2(start: Int, mid: Int, end: Int): Int {
require(start <= end) { "该数组没有重复数字" }
val count = countArrayInRange(start..mid)
return when {
start == end -> if (count > 1) start else throw IllegalArgumentException("该数组没有重复数字")
count > mid - start + 1 -> findRepeat2(start, (mid - start) / 2 + start, mid)
else -> {
val newStart = mid + 1
findRepeat2(newStart, (end - newStart) / 2 + newStart, end)
}
}
}
private fun IntArray.countArrayInRange(range: IntRange): Int =
countArrayInRange(range, 0, 0)
private tailrec fun IntArray.countArrayInRange(range: IntRange, index: Int, count: Int): Int =
if (index in indices)
countArrayInRange(range, index + 1,
if (this[index] in range) count + 1 else count)
else count | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,917 | Algorithm | Apache License 2.0 |
app/src/main/kotlin/solution/Solution952.kt | likexx | 559,794,763 | false | {"Kotlin": 136661} | package solution
import solution.annotation.Leetcode
class Solution952 {
@Leetcode(952)
class Solution {
fun largestComponentSize(nums: IntArray): Int {
// use prime factor decomposition
var maxN = -1
nums.forEach { maxN = kotlin.math.max(it, maxN) }
var parents = IntArray(maxN+1) {-1}
var sizes = IntArray(maxN+1) {1}
fun findParent(i:Int): Int {
if (parents[i]==-1) {
return i
}
parents[i]=findParent(parents[i])
return parents[i]
}
fun union(i: Int, j: Int) {
val p1 = findParent(i)
val p2 = findParent(j)
if (p1 == p2) {
return
}
val s1 = sizes[p1]
val s2 = sizes[p2]
if (s1>=s2) {
parents[p2] = p1
sizes[p1] += sizes[p2]
} else {
parents[p1] = p2
sizes[p2] += sizes[p1]
}
}
fun getPrimeFactors(n: Int): List<Int> {
val factors = mutableListOf<Int>()
var factor = 2
var num = n
while (num >= factor*factor) {
if (num%factor==0) {
factors.add(factor)
num /= factor
} else {
factor += 1
}
}
factors.add(num)
return factors
}
val numberGroups = hashMapOf<Int, Int>()
nums.forEach {
var factors = getPrimeFactors(it)
numberGroups[it] = factors[0]
for (i in 0..factors.size-2) {
union(factors[i], factors[i+1])
}
}
val count = hashMapOf<Int, Int>()
var maxSize=0
nums.forEach {
val k = findParent(numberGroups[it]!!)
count[k] = count.getOrDefault(k, 0) + 1
maxSize = kotlin.math.max(count[k]!!, maxSize)
}
return maxSize
}
fun largestComponentSizeByFactors(nums: IntArray): Int {
var maxN = -1
nums.forEach { maxN = kotlin.math.max(it, maxN) }
var parents = IntArray(maxN+1) {-1}
var sizes = IntArray(maxN+1) {1}
fun findParent(i:Int): Int {
if (parents[i]==-1) {
return i
}
parents[i]=findParent(parents[i])
return parents[i]
}
fun union(i: Int, j: Int) {
val p1 = findParent(i)
val p2 = findParent(j)
if (p1 == p2) {
return
}
val s1 = sizes[p1]
val s2 = sizes[p2]
if (s1>=s2) {
parents[p2] = p1
sizes[p1] += sizes[p2]
} else {
parents[p1] = p2
sizes[p2] += sizes[p1]
}
}
nums.forEach {
val n = it
for (i in 2..kotlin.math.sqrt(n.toDouble()).toInt()) {
if (n % i == 0) {
union(n, i)
union(n, n / i)
}
}
}
val count = hashMapOf<Int, Int>()
var maxSize=0
nums.forEach {
val k = findParent(it)
count[k] = count.getOrDefault(k, 0) + 1
maxSize = kotlin.math.max(count[k]!!, maxSize)
}
return maxSize
}
}
} | 0 | Kotlin | 0 | 0 | 376352562faf8131172e7630ab4e6501fabb3002 | 3,886 | leetcode-kotlin | MIT License |
baparker/16/main.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File
val VERSION_TYPEID_LENGTH = 3
val BIT_GROUP_SIZE = 4
val LITERAL_GROUP_SIZE = 5
val LENGTH_TYPE_ZERO_SIZE = 15
val LENGTH_TYPE_ONE_SIZE = 11
fun binFromHex(hex: String): String {
return String.format(
"%" + BIT_GROUP_SIZE + "s",
Integer.toBinaryString(Integer.parseUnsignedInt(hex, 16))
)
.replace(" ".toRegex(), "0")
}
// Current spot in the binary string
var pointer = 0
var binString = ""
var versionSum = 0
fun literalValue(): Long {
var literalString = ""
var groupFlag = true
var totalGroupSize = 0
while (groupFlag) {
val group = binString.substring(pointer, pointer + LITERAL_GROUP_SIZE)
if (group.startsWith("0")) {
groupFlag = false
}
literalString += group.substring(1)
pointer += LITERAL_GROUP_SIZE
totalGroupSize += LITERAL_GROUP_SIZE
}
return literalString.toLong(radix = 2)
}
fun versionAndTypeId(): Int {
val value =
Integer.parseUnsignedInt(
binString.substring(pointer, pointer + VERSION_TYPEID_LENGTH),
2
)
pointer += VERSION_TYPEID_LENGTH
return value
}
fun traversePackets(): Long {
val version = versionAndTypeId()
versionSum += version
val typeId = versionAndTypeId()
if (typeId == 4) {
return literalValue()
} else {
val lengthTypeId = binString.substring(pointer, pointer + 1)
pointer++
val valueList: MutableList<Long> = mutableListOf()
if (lengthTypeId == "0") {
var targetPointer =
Integer.parseUnsignedInt(
binString.substring(pointer, pointer + LENGTH_TYPE_ZERO_SIZE),
2
)
pointer += LENGTH_TYPE_ZERO_SIZE
targetPointer += pointer
while (pointer < targetPointer) {
valueList.add(traversePackets())
}
} else {
val numPackets =
Integer.parseUnsignedInt(
binString.substring(pointer, pointer + LENGTH_TYPE_ONE_SIZE),
2
)
pointer += LENGTH_TYPE_ONE_SIZE
for (i in 0 until numPackets) {
valueList.add(traversePackets())
}
}
var result: Long = 0
when (typeId) {
0 -> result = valueList.sum()
1 -> result = valueList.fold(1) { prod, value -> value * prod }
2 -> result = valueList.minOrNull() ?: 0
3 -> result = valueList.maxOrNull() ?: 0
5 -> result = if (valueList.get(0).toInt().compareTo(valueList.get(1)) == 1) 1 else 0
6 -> result = if (valueList.get(1).toInt().compareTo(valueList.get(0)) == 1) 1 else 0
7 -> result = if (valueList.get(0).toInt().compareTo(valueList.get(1)) == 0) 1 else 0
}
if (binString.substring(pointer).length < VERSION_TYPEID_LENGTH * 2) {
pointer += binString.substring(pointer).length
}
return result
}
}
fun main() {
File("input.txt").forEachLine { it.forEach { binString += binFromHex(it.toString()) } }
println("Expression Result: " + traversePackets())
println("Version Sum: " + versionSum)
}
| 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 3,384 | advent-of-code-2021 | MIT License |
src/Day23.kt | kipwoker | 572,884,607 | false | null | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class Day23 {
fun parse(input: List<String>): Set<Point> {
return input.flatMapIndexed { y, line ->
line.mapIndexed { x, c ->
if (c == '#') {
Point(x, y)
} else {
null
}
}
}.filterNotNull().toSet()
}
private val directions = arrayOf(Direction.Up, Direction.Down, Direction.Left, Direction.Right)
fun getNext(direction: Direction): Direction {
val index = (directions.indexOf(direction) + 1 + directions.size) % directions.size
return directions[index]
}
fun getNeighbors(point: Point): List<Point> {
return (-1..1)
.flatMap { x ->
(-1..1)
.map { y -> Point(point.x + x, point.y + y) }
}
.filter { p -> p != point }
}
fun canMove(point: Point, neighbors: List<Point>, direction: Direction): Point? {
return when (direction) {
Direction.Up -> if (neighbors.none { p -> p.y == point.y - 1 }) Point(point.x, point.y - 1) else null
Direction.Down -> if (neighbors.none { p -> p.y == point.y + 1 }) Point(point.x, point.y + 1) else null
Direction.Left -> if (neighbors.none { p -> p.x == point.x - 1 }) Point(point.x - 1, point.y) else null
Direction.Right -> if (neighbors.none { p -> p.x == point.x + 1 }) Point(point.x + 1, point.y) else null
}
}
fun move(points: Set<Point>, direction: Direction): Set<Point> {
val proposals = mutableMapOf<Point, Point>()
for (point in points) {
val neighbors = getNeighbors(point).filter { it in points }
if (neighbors.isEmpty()) {
continue
}
var cursor = direction
while (true) {
val target = canMove(point, neighbors, cursor)
if (target != null) {
proposals[point] = target
break
}
cursor = getNext(cursor)
if (cursor == direction) {
break
}
}
}
val reverseMap = proposals.asIterable().groupBy({ pair -> pair.value }, { pair -> pair.key })
val moves = reverseMap.filter { it.value.size == 1 }.map { it.value[0] to it.key }.toMap()
return points
.filter { p -> !moves.containsKey(p) }
.union(moves.values)
.toSet()
}
fun play1(points: Set<Point>): Set<Point> {
var direction = Direction.Up
var cursor = points
for (i in 1..10) {
cursor = move(cursor, direction)
direction = getNext(direction)
}
return cursor
}
fun play2(points: Set<Point>): Int {
var direction = Direction.Up
var cursor = points
var i = 0
do {
val newCursor = move(cursor, direction)
direction = getNext(direction)
val same = newCursor == cursor
cursor = newCursor
++i
} while (!same)
return i
}
fun print(points: Set<Point>) {
val maxX = points.maxOf { p -> p.x }
val maxY = points.maxOf { p -> p.y }
val minX = points.minOf { p -> p.x }
val minY = points.minOf { p -> p.y }
for (y in (minY - 1)..(maxY + 1)) {
for (x in (minX - 1)..(maxX + 1)) {
if (Point(x, y) in points) {
print('#')
} else {
print('.')
}
}
println()
}
println()
}
fun part1(input: List<String>): String {
val points = parse(input)
val result = play1(points)
return calc(result)
}
private fun calc(result: Set<Point>): String {
val maxX = result.maxOf { p -> p.x }
val maxY = result.maxOf { p -> p.y }
val minX = result.minOf { p -> p.x }
val minY = result.minOf { p -> p.y }
val dx = maxX - minX + 1
val dy = maxY - minY + 1
println("dx $dx dy $dy size ${result.size}")
val answer = dx * dy - result.size
return answer.toString()
}
fun part2(input: List<String>): String {
val points = parse(input)
val result = play2(points)
return result.toString()
}
}
@OptIn(ExperimentalTime::class)
@Suppress("DuplicatedCode")
fun main() {
val solution = Day23()
val name = solution.javaClass.name
val execution = setOf(
ExecutionMode.Test1,
ExecutionMode.Test2,
ExecutionMode.Exec1,
ExecutionMode.Exec2
)
fun test() {
val expected1 = "110"
val expected2 = "20"
val testInput = readInput("${name}_test")
if (execution.contains(ExecutionMode.Test1)) {
println("Test part 1")
assert(solution.part1(testInput), expected1)
println("> Passed")
}
if (execution.contains(ExecutionMode.Test2)) {
println("Test part 2")
assert(solution.part2(testInput), expected2)
println("> Passed")
println()
}
println("=================================")
println()
}
fun run() {
val input = readInput(name)
if (execution.contains(ExecutionMode.Exec1)) {
val elapsed1 = measureTime {
println("Part 1: " + solution.part1(input))
}
println("Elapsed: $elapsed1")
println()
}
if (execution.contains(ExecutionMode.Exec2)) {
val elapsed2 = measureTime {
println("Part 2: " + solution.part2(input))
}
println("Elapsed: $elapsed2")
println()
}
}
test()
run()
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 5,964 | aoc2022 | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[53]最大子序和.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import kotlin.math.max
//给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
//
// 示例:
//
// 输入: [-2,1,-3,4,-1,2,1,-5,4]
//输出: 6
//解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
//
//
// 进阶:
//
// 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
// Related Topics 数组 分治算法 动态规划
// 👍 2807 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun maxSubArray(nums: IntArray): Int {
//动态规划
//dp[i] 代表当前计算中的最大和
//动态规划方程
//dp[i] = Max(dp[i-1]+nums[i],nums[i])
var dp = IntArray(nums.size)
dp[0] = nums[0]
var maxres = dp[0]
for (i in 1 until nums.size){
dp[i] = Math.max(dp[i-1]+nums[i],nums[i])
//更新最大值
maxres = Math.max(dp[i],maxres)
}
return maxres
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,133 | MyLeetCode | Apache License 2.0 |
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/algo/DamerauLevenshtein.kt | pkleimann | 91,075,858 | true | {"Kotlin": 309171, "Java": 50176, "HTML": 1293} | package org.livingdoc.engine.algo
import java.lang.Math.min
/**
* Calculates the Damerau-Levenshtein distance, a string similarity metric used e.g. by spell checkers.
*
* By default, the algorithm calculates the minimum number of four different editing operations
* required to turn one string into another. The four operations are
* <ul>
* <li><emph>insertion:</emph> a character is inserted</li>
* <li><emph>deletion:</emph> a character is deleted</li>
* <li><emph>substitution:</emph> a character is exchanged with another</li>
* <li><emph>transposition:</emph> two adjacent characters are swapped</li>
* </ul>
*
* It is possible to specify a weight for each of these operations to tune the metric.
*
* The implementation is linear in space, but O(n²) in time. To avoid expensive comparisons of long
* strings, you can specify a cutoff distance, beyond which the algorithm will abort.
*
* @param cutoffDistance maximum distance at which the algorithm aborts (default: no cutoff)
* @param weightInsertion weight of an insert operation (default: 1)
* @param weightDeletion weight of a deletion operation (default: 1)
* @param weightSubstitution weight of a substitution operation (default: 1)
* @param weightTransposition weight of a transposition operation (default: 1)
*/
class DamerauLevenshtein(
val cutoffDistance: Int = 0,
val weightInsertion: Int = 1,
val weightDeletion: Int = 1,
val weightSubstitution: Int = 1,
val weightTransposition: Int = 1
) {
/*
* This dynamic programming algorithm calculates a m*n matrix of distance values. The
* final result is the distance between the two given strings a and b. The values in between
* are locally minimal distances for the respective substrings of a and b.
*
* L i v i n g D o c - b
* 0 1 2 3 4 5 6 7 8 9
* L 1 0 2 3 4 5 6 7 8 9
* o 2 1 1 2 3 4 5 6 7 8
* v 3 2 2 1 2 3 4 5 6 7
* i 4 3 2 2 1 2 3 4 5 6
* g 5 4 3 3 2 2 3 4 5 6
* n 6 5 4 4 3 2 2 3 4 5
* D 7 6 5 5 4 3 3 2 3 4
* e 8 7 6 6 5 4 4 3 3 4
* a 9 8 7 7 6 5 5 4 4 4
* d 10 9 8 8 7 6 6 5 5 5 <-- distance result
* |
* a
*
* As only the last three rows are needed to calculate the next distance value, only those are kept
* in memory.
*/
/**
* Calculates the editing distance between the given strings.
*/
@Suppress("ComplexCondition")
fun distance(a: String, b: String): Int {
var secondToLastRow = IntArray(b.length + 1)
var lastRow = IntArray(b.length + 1)
var currentRow = IntArray(b.length + 1)
for (j in 0..b.length) {
lastRow[j] = j * weightInsertion
}
for (i in 0 until a.length) {
var currentDistance = Int.MAX_VALUE
currentRow[0] = (i + 1) * weightDeletion
for (j in 0 until b.length) {
currentRow[j + 1] = currentRow[j] + weightInsertion
currentRow[j + 1] = min(currentRow[j + 1], lastRow[j + 1] + weightDeletion)
currentRow[j + 1] = min(currentRow[j + 1], lastRow[j] + if (a[i] != b[j]) weightSubstitution else 0)
if (i > 0 && j > 0 && a[i - 1] == b[j] && a[i] == b[j - 1]) {
currentRow[j + 1] = min(currentRow[j + 1], secondToLastRow[j - 1] + weightTransposition)
}
currentDistance = min(currentDistance, currentRow[j + 1])
}
// check cutoff
if (cutoffDistance in 1..currentDistance) {
return currentDistance
}
// rotate rows
val tempRow = secondToLastRow
secondToLastRow = lastRow
lastRow = currentRow
currentRow = tempRow
}
return lastRow[b.length]
}
}
| 0 | Kotlin | 0 | 0 | b81fe455a24ea8cd4b46083d443178039fffb2e3 | 3,854 | livingdoc2 | Apache License 2.0 |
p07/src/main/kotlin/SumOfItsParts.kt | jcavanagh | 159,918,838 | false | null | package p07
import common.file.readLines
import java.util.*
import kotlin.NoSuchElementException
class Node<T : Comparable<T>>(var value: T, val cost: Int) : Comparable<Node<T>> {
//Paths to other nodes
var edges = sortedSetOf<Node<T>>()
//Paths from other nodes
var refs = sortedSetOf<Node<T>>()
//A node is a root if nothing leads to it
fun isRoot(): Boolean {
return refs.size == 0
}
fun next(): Node<T>? {
try {
return edges.first()
} catch(e: NoSuchElementException) {
return null
}
}
override fun compareTo(other: Node<T>): Int {
return this.value.compareTo(other.value)
}
}
class SleighGraph<T : Comparable<T>>(var nodes: SortedSet<Node<T>> = sortedSetOf()) {
data class Worker<T : Comparable<T>>(val node: Node<T>, val completesAt: Int)
fun add(value: T, depends: T, cost: (T) -> Int) {
//This could probably be indexed
val node = nodes.find { it.value == value } ?: Node(value, cost(value)).also { nodes.add(it) }
val depNode = nodes.find {it.value == depends} ?: Node(depends, cost(depends)).also { nodes.add(it) }
node.refs.add(depNode)
depNode.edges.add(node)
}
fun roots(): List<Node<T>> {
return nodes.filter { it.isRoot() }
}
//Traverse the list in parallel, respecting cost
//If no workers specified, ignore cost
fun traverse(workerCount: Int = 0, baseNodeCost: Int = 0): Pair<List<Node<T>>, Int> {
//Count costs
var tick = 0
//Final list
val ordered = mutableListOf<Node<T>>()
//Current path choices
val possible = sortedSetOf<Node<T>>()
possible.addAll(this.roots())
//Track workers
val workers = mutableListOf<Worker<T>>()
fun valid(): List<Node<T>> {
return possible.filter { it.refs.minus(ordered).isEmpty() }
}
fun nextNode(): Node<T>? {
val validEdges = valid()
if(validEdges.isNotEmpty()) {
return validEdges.first()
}
return null
}
fun startNode(node: Node<T>) {
possible.remove(node)
}
fun finishNode(node: Node<T>) {
ordered.add(node)
possible.addAll(node.edges)
possible.removeAll(ordered)
}
do {
if(workerCount > 0) {
//Check for workers that should be removed
val completed = workers.filter { tick >= it.completesAt }
completed.forEach { finishNode(it.node) }
workers.removeAll(completed)
val validNodes = valid()
if(validNodes.isEmpty()) {
//If we have no next node and no workers running, we are done
if (workers.isEmpty()) {
break
}
}
for(node in valid()) {
//Assign the new node to a worker, or wait for one to become available
if (workers.size < workerCount) {
workers.add(Worker(node, tick + baseNodeCost + node.cost))
startNode(node)
}
}
tick++
} else {
val node = nextNode() ?: break
startNode(node)
finishNode(node)
}
} while(valid().isNotEmpty() || (workerCount > 0 && workers.isNotEmpty()))
return Pair(ordered, tick)
}
}
fun loadSteps(steps: List<String>): SleighGraph<String> {
val graph = SleighGraph<String>()
val pattern = Regex("""^Step (\w).+step (\w).+$""")
fun cost(value: String): Int {
return value[0].minus('A') + 1
}
for(step in steps) {
val matches = pattern.matchEntire(step)
if(matches != null) {
val value = matches.groups[2]?.value!!
val depends = matches.groups[1]?.value!!
graph.add(value, depends) { cost(it) }
} else {
println("Failed to parse: $step")
}
}
return graph
}
fun main() {
val graph = loadSteps(readLines("input.txt"))
val ordered = graph.traverse()
val orderedWithWorkers = graph.traverse(5, 60)
println("Base")
println("Order: ${ordered.first.joinToString("") { it.value }}")
println("Parallelized - 5/60")
println("Order: ${orderedWithWorkers.first.joinToString("") { it.value }}")
println("Duration: ${orderedWithWorkers.second}")
}
| 0 | Kotlin | 0 | 0 | 289511d067492de1ad0ceb7aa91d0ef7b07163c0 | 4,068 | advent2018 | MIT License |
src/main/kotlin/Excercise23.kt | underwindfall | 433,989,850 | false | {"Kotlin": 55774} | import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.HashSet
import kotlin.math.abs
data class Burrow(
val roomSize: Int,
val hallway: Map<Int, Char>,
val rooms: Map<Int, List<Char>>,
)
val roomAssignments = mapOf(2 to 'A', 4 to 'B', 6 to 'C', 8 to 'D')
fun getPossibleMoves(burrow: Burrow): List<Pair<Int, Int>> = buildList {
fun pathExists(i1: Int, i2: Int): Boolean {
val lo = minOf(i1, i2)
val hi = maxOf(i1, i2)
return burrow.hallway.all { (index, value) ->
index !in (lo + 1)..(hi - 1) || value == '.'
}
}
burrow.hallway.forEach { (hindex, hvalue) ->
burrow.rooms.forEach inner@{ (rindex, rvalue) ->
// Both empty
if (hvalue == '.' && rvalue.isEmpty()) {
return@inner
}
// Hallway to room (room compatible)
if (hvalue != '.') {
if (hvalue == roomAssignments[rindex]
&& rvalue.all { it == hvalue }
&& pathExists(hindex, rindex)
) {
add(hindex to rindex)
}
return@inner
}
// Room to hallway (hallway empty)
if (pathExists(rindex, hindex)
&& rvalue.any { it != roomAssignments[rindex] }
) {
add(rindex to hindex)
}
}
}
}
fun execute(burrow: Burrow, move: Pair<Int, Int>): Pair<Burrow, Int> {
fun costFor(amphipod: Char) = when (amphipod) {
'A' -> 1
'B' -> 10
'C' -> 100
'D' -> 1000
else -> error("Invalid amphipod provided")
}
fun roomToHallway(burrow: Burrow, ri: Int, hi: Int): Pair<Burrow, Int> {
val room = burrow.rooms.getValue(ri)
val amphipod = room.first()
val upwards = burrow.roomSize - room.size + 1
val sideways = abs(ri - hi)
val cost = (upwards + sideways) * costFor(amphipod)
val modifiedBurrow = burrow.copy(
rooms = burrow.rooms.plus(ri to room.drop(1)),
hallway = burrow.hallway.plus(hi to amphipod),
)
return Pair(modifiedBurrow, cost)
}
fun hallwayToRoom(burrow: Burrow, hi: Int, ri: Int): Pair<Burrow, Int> {
val room = burrow.rooms.getValue(ri)
val amphipod = burrow.hallway.getValue(hi)
val sideways = abs(ri - hi)
val downwards = burrow.roomSize - room.size
val cost = (sideways + downwards) * costFor(amphipod)
val modifiedBurrow = burrow.copy(
rooms = burrow.rooms.plus(ri to listOf(amphipod) + room),
hallway = burrow.hallway.plus(hi to '.'),
)
return Pair(modifiedBurrow, cost)
}
return if (move.first in roomAssignments.keys) {
roomToHallway(burrow, move.first, move.second)
} else {
hallwayToRoom(burrow, move.first, move.second)
}
}
fun organizeAmphipods(input: List<String>): Int {
val rooms = input.drop(2).dropLast(1).map { line ->
line.filter { char -> char in 'A'..'D' }
}
val a = rooms.map { it[0] }
val b = rooms.map { it[1] }
val c = rooms.map { it[2] }
val d = rooms.map { it[3] }
val initialBurrow = Burrow(
roomSize = a.size,
hallway = mapOf(
0 to '.',
1 to '.',
3 to '.',
5 to '.',
7 to '.',
9 to '.',
10 to '.',
),
rooms = mapOf(
2 to a,
4 to b,
6 to c,
8 to d,
),
)
var bestCost = Int.MAX_VALUE
val seen = mutableMapOf<Burrow, Int>()
fun simulate(prevBurrow: Burrow, move: Pair<Int, Int>, prevCost: Int): Int {
if (prevCost >= bestCost) return Int.MAX_VALUE
val (burrow, cost) = execute(prevBurrow, move)
val totalCost = prevCost + cost
if (burrow in seen) {
if (seen.getValue(burrow) <= totalCost) {
return Int.MAX_VALUE
}
}
seen[burrow] = totalCost
if (roomAssignments.all { (ri, amph) ->
val r = burrow.rooms.getValue(ri)
r.size == burrow.roomSize && r.all { it == amph }
}) {
if (totalCost < bestCost) bestCost = totalCost
return totalCost
}
val moves = getPossibleMoves(burrow)
if (moves.isEmpty()) return Int.MAX_VALUE
return moves.minOf { simulate(burrow, it, totalCost) }
}
return getPossibleMoves(initialBurrow).minOf { simulate(initialBurrow, it, 0) }
}
private fun part1() {
val testInput1 = getInputAsTest("23")
println("part1 ${organizeAmphipods(testInput1)}")
}
private fun part2() {
data class Cfg(val c: Array<CharArray>, val d: Int) {
override fun equals(other: Any?): Boolean = other is Cfg && (0..4).all { i -> c[i].contentEquals(other.c[i]) }
override fun hashCode(): Int = (0..4).fold(0) { a, i-> a * 31 + c[i].contentHashCode() }
fun copy(d1: Int) = Cfg(c.map { it.copyOf() }.toTypedArray(), d1)
override fun toString(): String = buildList {
add("#".repeat(13))
addAll(c.map { it.concatToString() })
add("distance=$d")
}.joinToString("\n")
}
val d = HashMap<Cfg,Int>()
val q = PriorityQueue(compareBy(Cfg::d))
val f = HashSet<Cfg>()
fun enqueue(c: Cfg) {
val d0 = d[c] ?: Int.MAX_VALUE
if (c.d >= d0) return
d[c] = c.d
q += c
}
val input1 = getInputAsTest("23").subList(1, 4)
val input2 = buildList<String> {
add(input1[0])
add(input1[1])
add(" #D#C#B#A# ")
add(" #D#B#A#C# ")
add(input1[2])
}
val start = Cfg(input2.map { it.toCharArray() }.toTypedArray(), 0)
println(start)
enqueue(start)
fun cost(c0: Char): Int = when(c0) {
'A' -> 1
'B' -> 10
'C' -> 100
'D' -> 1000
else -> error("$c0")
}
while (true) {
val c = q.remove()!!
if (c in f) continue
f += c
val d0 = d[c]!!
if (f.size % 10000 == 0) println("d=$d0, qs=${q.size}, fs=${f.size}")
var ok = true
check@for (r in 1..4) for (i in 0..3) if (c.c[r][2 * i + 3] != 'A' + i) {
ok = false
break@check
}
if (ok) {
println(c)
break
}
for (j0 in 1..11) {
val c0 = c.c[0][j0]
if (c0 !in 'A'..'D') continue
val i = (c0 - 'A')
val j1 = 2 * i + 3
if (!(minOf(j0, j1) + 1..maxOf(j0, j1) - 1).all { j -> c.c[0][j] == '.' }) continue
if (!(1..4).all { r -> c.c[r][j1] == '.' || c.c[r][j1] == c0 }) continue
val r1 = (4 downTo 1).first { r -> c.c[r][j1] == '.' }
val c1 = c.copy(d0 + cost(c0) * (abs(j1 - j0) + r1))
c1.c[0][j0] = '.'
c1.c[r1][j1] = c0
enqueue(c1)
}
for (i in 0..3) for (r0 in 1..4) {
val j0 = 2 * i + 3
val c0 = c.c[r0][j0]
if (c0 !in 'A'..'D') continue
if (!(1..r0 - 1).all { r -> c.c[r][j0] == '.' }) continue
for (j1 in 1..11) {
if ((j1 - 3) % 2 == 0 && (j1 - 3) / 2 in 0..3) continue
if (!(minOf(j1, j0)..maxOf(j1, j0)).all { j -> c.c[0][j] == '.' }) continue
val c1 = c.copy(d0 + cost(c0) * (abs(j1 - j0) + r0))
c1.c[r0][j0] = '.'
c1.c[0][j1] = c0
enqueue(c1)
}
}
}
}
fun main() {
part1()
part2()
} | 0 | Kotlin | 0 | 0 | 4fbee48352577f3356e9b9b57d215298cdfca1ed | 7,698 | advent-of-code-2021 | MIT License |
leetcode-75-kotlin/src/main/kotlin/GreatestCommonDivisorOfStrings.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* For two strings s and t,
* we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times).
*
* Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.
*
*
*
* Example 1:
*
* Input: str1 = "ABCABC", str2 = "ABC"
* Output: "ABC"
* Example 2:
*
* Input: str1 = "ABABAB", str2 = "ABAB"
* Output: "AB"
* Example 3:
*
* Input: str1 = "LEET", str2 = "CODE"
* Output: ""
*
*
* Constraints:
*
* 1 <= str1.length, str2.length <= 1000
* str1 and str2 consist of English uppercase letters.
* @see <a href="https://leetcode.com/problems/greatest-common-divisor-of-strings/">LeetCode</a>
*/
fun gcdOfStrings(str1: String, str2: String): String {
if (str1 + str2 != str2 + str1) {
return ""
}
return str1.substring(0, gcd(str1.length, str2.length))
}
private fun gcd(a: Int, b: Int): Int {
return if (b == 0) a else gcd(b, a % b)
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 965 | leetcode-75 | Apache License 2.0 |
src/day09/Day09.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day09
import log
import logln
import logEnabled
import readInput
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.max
private const val DAY_NUMBER = 9
data class Offset(val x: Int, val y: Int)
enum class Direction(val offset: Offset) {
UP(Offset(0, 1)),
DOWN(Offset(0, -1)),
LEFT(Offset(-1, 0)),
RIGHT(Offset(1, 0)),
}
data class KnotPosition(val x: Int, val y: Int) {
fun follow(target: KnotPosition): KnotPosition {
if (this touches target)
return this
var xOffset = target.x - x
var yOffset = target.y - y
// Clamp to [-1, 1] range
xOffset = max(-1, min(xOffset, 1))
yOffset = max(-1, min(yOffset, 1))
return KnotPosition(x + xOffset, y + yOffset)
}
fun move(direction: Direction): KnotPosition = this + direction.offset
operator fun plus(offset: Offset): KnotPosition = KnotPosition(x + offset.x, y + offset.y)
infix fun touches(other: KnotPosition): Boolean =
abs(this.x - other.x) <= 1 && abs(this.y - other.y) <= 1
override fun toString(): String = "($x, $y)"
}
class Simulation(ropeKnots: Int) {
private val rope: Array<KnotPosition> = Array(ropeKnots) { KnotPosition(0, 0) }
private var head: KnotPosition
get() = rope.first()
set(newHead) {
rope[0] = newHead
}
private val tail: KnotPosition get() = rope.last()
private val uniqueTailPositions = HashSet<KnotPosition>()
val uniqueTailPositionsCount: Int
get() = uniqueTailPositions.size
init {
uniqueTailPositions.add(tail)
}
fun run(movements: List<Pair<Direction, Int>>) {
for (move in movements)
moveRope(move.first, move.second)
}
private fun moveRope(direction: Direction, steps: Int) {
for (step in 0 until steps) {
log("Moving from $head to ")
head = head.move(direction)
log(head)
log(" tail is at $tail")
for (knotId in 1..rope.lastIndex) {
rope[knotId] = rope[knotId].follow(rope[knotId - 1])
}
logln(" and moved to $tail")
uniqueTailPositions.add(tail)
}
}
}
private fun String.toDirection(): Direction {
return when (this) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> throw IllegalArgumentException("Invalid input direction: '$this'")
}
}
fun main() {
fun toMovementList(rawInput: List<String>) = rawInput.map {
Pair(it.substringBefore(' ').toDirection(), it.substringAfter(' ').toInt())
}
fun part1(rawInput: List<String>): Int {
val movements = toMovementList(rawInput)
val simulation = Simulation(2)
simulation.run(movements)
return simulation.uniqueTailPositionsCount
}
fun part2(rawInput: List<String>): Int {
val movements = toMovementList(rawInput)
val simulation = Simulation(10)
simulation.run(movements)
return simulation.uniqueTailPositionsCount
}
val sampleInput = readInput("sample_data", DAY_NUMBER)
val mainInput = readInput("main_data", DAY_NUMBER)
logEnabled = false
val part1SampleResult = part1(sampleInput)
println(part1SampleResult)
check(part1SampleResult == 13)
val part1MainResult = part1(mainInput)
println(part1MainResult)
check(part1MainResult == 6503)
val part2SampleResult = part2(sampleInput)
println(part2SampleResult)
check(part2SampleResult == 1)
val part2MainResult = part2(mainInput)
println(part2MainResult)
check(part2MainResult == 2724)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 3,727 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day8.kt | bfrengley | 318,716,410 | false | null | package aoc2020.day8
import aoc2020.util.loadTextResource
enum class Operation {
NOP, ACC, JMP;
}
data class Instruction(val op: Operation, val arg: Int) {
companion object {
fun parse(instrStr: String) = Instruction(
Operation.valueOf(instrStr.substringBefore(' ').toUpperCase()),
instrStr.substringAfter(' ').toInt()
)
}
}
class Program(private val instrs: List<Instruction>) {
data class State(val acc: Int, val pc: Int) {
fun next(instr: Instruction) = when (instr.op) {
Operation.ACC -> State(acc + instr.arg, pc + 1)
Operation.JMP -> State(acc, pc + instr.arg)
Operation.NOP -> State(acc, pc + 1)
}
}
enum class TerminationState {
LOOP, SUCCESS, OUT_OF_BOUNDS
}
private fun nextState(state: State) = state.next(instrs[state.pc])
fun runToFirstLoop(): Pair<TerminationState, State> {
val seen = mutableSetOf<Int>()
var state = State(0, 0)
while (state.pc !in seen && state.pc in instrs.indices) {
seen.add(state.pc)
state = nextState(state)
}
return when (state.pc) {
in instrs.indices -> Pair(TerminationState.LOOP, state)
instrs.size -> Pair(TerminationState.SUCCESS, state)
else -> Pair(TerminationState.OUT_OF_BOUNDS, state)
}
}
}
fun main(args: Array<String>) {
val instrs = loadTextResource("/day8.txt").lines().map(Instruction::parse)
println("Part 1: ${Program(instrs).runToFirstLoop()}")
println("Part 2: ${solveLoop(instrs.toMutableList())}")
}
fun solveLoop(instrs: MutableList<Instruction>): Program.State {
val flips = instrs.indices.filter { instrs[it].op != Operation.ACC }
for (flipIdx in flips) {
// flip the instruction in-place to its opposite
flip(instrs, flipIdx)
val (term, state) = Program(instrs).runToFirstLoop()
if (term == Program.TerminationState.SUCCESS) {
return state
}
// flip it back
flip(instrs, flipIdx)
}
return Program.State(-1, 0)
}
fun flip(instrs: MutableList<Instruction>, idx: Int) {
val (op, arg) = instrs[idx]
if (op == Operation.JMP) {
instrs[idx] = Instruction(Operation.NOP, arg)
} else if (op == Operation.NOP) {
instrs[idx] = Instruction(Operation.JMP, arg)
}
}
| 0 | Kotlin | 0 | 0 | 088628f585dc3315e51e6a671a7e662d4cb81af6 | 2,411 | aoc2020 | ISC License |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day13/Day13.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day13
import eu.janvdb.aocutil.kotlin.point2d.Point2D
import eu.janvdb.aocutil.kotlin.readGroupedLines
const val FILENAME = "input13.txt"
// < 912
fun main() {
val groupedLines = readGroupedLines(2021, FILENAME)
val sheet = Sheet.create(groupedLines[0])
val instructions = groupedLines[1].map(Instruction::create)
val result1 = instructions[0].apply(sheet)
println(result1.points.size)
var result2 = sheet
instructions.forEach { result2 = it.apply(result2) }
result2.print()
}
data class Sheet(val points: Set<Point2D>) {
fun print() {
val minX = points.minOf { it.x }
val maxX = points.maxOf { it.x }
val minY = points.minOf { it.y }
val maxY = points.maxOf { it.y }
for(y in minY .. maxY) {
for(x in minX..maxX) {
if(points.contains(Point2D(x,y))) {
print("##")
} else {
print (" ")
}
}
println()
}
}
companion object {
fun create(coordinates: List<String>): Sheet {
val points = coordinates.asSequence().map(Point2D.Companion::createCommaSeparated).toSet()
return Sheet(points)
}
}
}
data class Instruction(val axis: Axis, val value: Int) {
fun apply(sheet: Sheet): Sheet {
return when (axis) {
Axis.X -> fold(sheet) { point ->
if (point.x <= value) point else Point2D(2 * value - point.x, point.y)
}
Axis.Y -> fold(sheet) { point ->
if (point.y <= value) point else Point2D(point.x, 2 * value - point.y)
}
}
}
private fun fold(sheet: Sheet, foldFunction: (Point2D) -> Point2D): Sheet {
val newPoints = sheet.points.asSequence().map(foldFunction).toSet()
return Sheet(newPoints)
}
companion object {
private val REGEX = Regex("fold along ([xy])=(\\d+)")
fun create(description: String): Instruction {
val match = REGEX.matchEntire(description)!!
val axis = Axis.valueOf(match.groupValues[1].uppercase())
val value = match.groupValues[2].toInt()
return Instruction(axis, value)
}
}
}
enum class Axis { X, Y } | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 1,967 | advent-of-code | Apache License 2.0 |
2022/main/day_14/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_14_2022
import java.io.File
tailrec fun placeSandPart1(map: HashMap<Pair<Int, Int>, Boolean>, from: Pair<Int, Int>, xBounds: Pair<Int, Int>, yBound: Int): Boolean {
return if ((from.second > yBound) || (from.first !in xBounds.first..xBounds.second)) {
false
} else if (map[from.first to from.second + 1] != true) {
placeSandPart1(map, from.first to from.second + 1, xBounds, yBound)
} else if (map[from.first - 1 to from.second + 1] != true) {
placeSandPart1(map, from.first - 1 to from.second + 1, xBounds, yBound)
} else if (map[from.first + 1 to from.second + 1] != true) {
placeSandPart1(map, from.first + 1 to from.second + 1, xBounds, yBound)
} else {
map[from.first to from.second] = true
true
}
}
fun part1(input: List<String>) {
val cave = hashMapOf<Pair<Int, Int>, Boolean>()
for (line in input) {
val points = line.split(" -> ").map { it.split(",")[0] to it.split(",")[1] }
for ((start, finish) in points.zipWithNext()) {
val (x1, y1) = start
val (x2, y2) = finish
if (x1 == x2) {
for (y in y1.toInt().coerceAtMost(y2.toInt())..y2.toInt().coerceAtLeast(y1.toInt())) {
cave[x1.toInt() to y] = true
}
} else {
for (x in x1.toInt().coerceAtMost(x2.toInt())..x2.toInt().coerceAtLeast(x1.toInt())) {
cave[x to y1.toInt()] = true
}
}
}
}
val xBounds = cave.keys.minOfOrNull { it.first }!! to cave.keys.maxOfOrNull { it.first }!!
val yBound = cave.keys.maxOfOrNull { it.second }!!
val sandSource = 500 to 0
var sand = 0
while (placeSandPart1(cave, sandSource, xBounds, yBound)) {
sand++
}
print("The number of units of sand that rest before sand falls into the abyss is $sand")
}
tailrec fun placeSandPart2(map: HashMap<Pair<Int, Int>, Boolean>, from: Pair<Int, Int>, yBound: Int, startLocation: Pair<Int, Int> = 500 to 0): Boolean {
return if ((from.second == yBound - 1)) {
map[from.first to from.second] = true
true
} else if (map[from.first to from.second + 1] != true) {
placeSandPart2(map, from.first to from.second + 1, yBound, startLocation)
} else if (map[from.first - 1 to from.second + 1] != true) {
placeSandPart2(map, from.first - 1 to from.second + 1, yBound, startLocation)
} else if (map[from.first + 1 to from.second + 1] != true) {
placeSandPart2(map, from.first + 1 to from.second + 1, yBound, startLocation)
} else if (map[from.first to from.second] == true) {
false
} else {
map[from.first to from.second] = true
true
}
}
fun part2(input: List<String>) {
val cave = hashMapOf<Pair<Int, Int>, Boolean>()
for (line in input) {
val points = line.split(" -> ").map { it.split(",")[0] to it.split(",")[1] }
for ((start, finish) in points.zipWithNext()) {
val (x1, y1) = start
val (x2, y2) = finish
if (x1 == x2) {
for (y in y1.toInt().coerceAtMost(y2.toInt())..y2.toInt().coerceAtLeast(y1.toInt())) {
cave[x1.toInt() to y] = true
}
} else {
for (x in x1.toInt().coerceAtMost(x2.toInt())..x2.toInt().coerceAtLeast(x1.toInt())) {
cave[x to y1.toInt()] = true
}
}
}
}
val yBound = cave.keys.maxOfOrNull { it.second }!! + 2
val sandSource = 500 to 0
var sand = 0
while (placeSandPart2(cave, sandSource, yBound, 500 to 0)) {
sand++
}
print("The number of units of sand that rest before sand can't leave the source is $sand")
}
fun main(){
val inputFile = File("2022/inputs/Day_14.txt")
print("\n----- Part 1 -----\n")
part1(inputFile.readLines())
print("\n----- Part 2 -----\n")
part2(inputFile.readLines())
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 3,994 | AdventofCode | MIT License |
src/day05/Day05.kt | devEyosiyas | 576,863,541 | false | null | package day05
import println
import readInput
import kotlin.collections.ArrayDeque
fun main() {
fun generateInput(
input: List<String>,
stack: Int,
): Pair<List<String>, MutableList<ArrayDeque<String>>> {
val split = input.joinToString("\n").split("\n\n")
val stacksList = split[0].split("\n").map { it.replace(Regex("\\[|\\]"), "") }.dropLast(1)
val instructions = split[1].split("\n")
val stacks = mutableListOf<ArrayDeque<String>>()
for (i in 0 until stack) {
stacks.add(ArrayDeque())
}
for (element in stacksList) {
val crates = element.replace(" ", "").split(" ")
for (i in crates.indices) {
if (crates[i].isNotEmpty()) stacks[i].add(crates[i])
}
}
return Pair(instructions, stacks)
}
fun partOne(input: List<String>, stack: Int = 3): String {
val (instructions, stacks) = generateInput(input, stack)
instructions.forEach {
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
val match = regex.find(it)
if (match != null) {
val (move, from, to) = match.destructured
for (j in 0 until move.toInt()) {
val tmp = stacks[from.toInt() - 1].first()
stacks[from.toInt() - 1].remove(tmp)
stacks[to.toInt() - 1].addFirst(tmp)
}
}
}
return stacks.joinToString("") { it.first() }
}
fun partTwo(input: List<String>, stack: Int = 3): String {
val (instructions, stacks) = generateInput(input, stack)
instructions.forEach {
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
val match = regex.find(it)
if (match != null) {
val (move, from, to) = match.destructured
val tempList = ArrayDeque<String>()
for (i in 0 until move.toInt()) {
val temp = stacks[from.toInt() - 1].first()
tempList.add(temp)
stacks[from.toInt() - 1].remove(temp)
}
stacks[to.toInt() - 1].addAll(0, tempList)
}
}
return stacks.joinToString("") { it.first() }
}
val testInput = readInput("day05", true)
val input = readInput("day05")
// part one
partOne(testInput).println()
partOne(input, 9).println()
// part two
partTwo(testInput).println()
partTwo(input, 9).println()
} | 0 | Kotlin | 0 | 0 | 91d94b50153bdab1a4d972f57108d6c0ea712b0e | 2,574 | advent_of_code_2022 | Apache License 2.0 |
src/org/aoc2021/Day4.kt | jsgroth | 439,763,933 | false | {"Kotlin": 86732} | package org.aoc2021
import java.nio.file.Files
import java.nio.file.Path
class Board(boardLines: List<String>) {
companion object {
const val boardSize = 5
}
private val board: List<List<Int>>
private val chosenNumbers: Array<Array<Boolean>> = Array(boardSize) { Array(boardSize) { false } }
private val numberToPosition: Map<Int, Pair<Int, Int>>
init {
board = boardLines.drop(1).map { line ->
line.split(Regex(" +")).filter(String::isNotBlank).map(String::toInt)
}
numberToPosition = board.flatMapIndexed { i, row ->
row.mapIndexed { j, number -> number to (i to j) }
}.toMap()
}
fun processNumber(number: Int) {
numberToPosition[number]?.let { (i, j) ->
chosenNumbers[i][j] = true
}
}
private fun checkRows(): Boolean {
return chosenNumbers.any { row ->
row.all { it }
}
}
private fun checkColumns(): Boolean {
return (0 until boardSize).any { j ->
(0 until boardSize).all { i ->
chosenNumbers[i][j]
}
}
}
fun checkWin() = checkRows() || checkColumns()
fun sumUnmarkedNumbers(): Int {
return board.mapIndexed { i, row ->
row.filterIndexed { j, _ -> !chosenNumbers[i][j] }.sum()
}.sum()
}
}
object Day4 {
private fun solvePart1(filename: String): Int {
val lines = Files.readAllLines(Path.of(filename), Charsets.UTF_8)
val chosenNumbers = lines[0].split(",").map(String::toInt)
val boards = parseBoards(lines)
chosenNumbers.forEach { chosenNumber ->
boards.forEach { board ->
board.processNumber(chosenNumber)
if (board.checkWin()) {
return chosenNumber * board.sumUnmarkedNumbers()
}
}
}
throw IllegalArgumentException("no winning boards found")
}
private fun solvePart2(filename: String): Int {
val lines = Files.readAllLines(Path.of(filename), Charsets.UTF_8)
val chosenNumbers = lines[0].split(",").map(String::toInt)
val boards = parseBoards(lines)
return findSolution(chosenNumbers, boards)
}
private fun parseBoards(lines: List<String>): List<Board> {
return lines.drop(1).chunked(Board.boardSize + 1, ::Board)
}
private tailrec fun findSolution(chosenNumbers: List<Int>, boards: List<Board>): Int {
val chosenNumber = chosenNumbers[0]
boards.forEach { board ->
board.processNumber(chosenNumber)
}
if (boards.size == 1 && boards[0].checkWin()) {
return chosenNumber * boards[0].sumUnmarkedNumbers()
}
val remainingBoards = boards.filterNot(Board::checkWin)
return findSolution(chosenNumbers.drop(1), remainingBoards)
}
@JvmStatic
fun main(args: Array<String>) {
val filename = "input4.txt"
val solution1 = solvePart1(filename)
println(solution1)
val solution2 = solvePart2(filename)
println(solution2)
}
} | 0 | Kotlin | 0 | 0 | ba81fadf2a8106fae3e16ed825cc25bbb7a95409 | 3,148 | advent-of-code-2021 | The Unlicense |
project/src/problems/PrefixSums.kt | informramiz | 173,284,942 | false | null | package problems
import extensions.toInt
import kotlin.math.max
import kotlin.math.min
object PrefixSums {
//https://codility.com/media/train/3-PrefixSums.pdf
/**
* There is a simple yet powerful technique that allows for the fast calculation of sums of
* elements in given slice (contiguous segments of array). Its main idea uses prefix sums which
* are defined as the consecutive totals of the first 0, 1, 2, . . . , n elements of an array.
* Given An = [a0, a1, a2 ..., an-1]
* prefix sums are
* p0 = 0, p1 = a0, p2 = a0 + a1, p3 = a0 + a1 + a2, . . ., pn = a0 + a1 + . . . + an−1
*/
private fun calculatePrefixSums(A: Array<Int>): Array<Int> {
val P = Array(A.size + 1) { 0 }
for (i in 1 until P.size) {
//Px = Px-1 + Ax-1
//i.e., P1 = P0 + a0 where P0 = 0
P[i] = P[i - 1] + A[i - 1]
}
return P
}
/**
* Calculate Slice [x ... y] sum such that 0 <= x <= y < n,
* where the total is the sum ax + ax+1 + . . . + ay−1 + ay
* P(y+1) = a0 + a1 + ... + ax-1 + ax + ax+1 + ... + ay-1 + ay
* we know that Px = a0 + a1 + ... + ax-1 so
* Py+1 = Px + ax + ax+1 + ... + ay-1 + ay
* -> ax + ... + ay = Py+1 - Px
* -> sum[x ... y] = Py+1 - Px
*/
private fun calculateSliceSum(P: Array<Int>, x: Int, y: Int): Int {
//as explained above
//sum[x ... y] = Py+1 - Px
return P[y + 1] - P[x]
}
/*
You are given a non-empty, zero-indexed array A of n (1 ¬ n ¬ 100 000) integers
a0, a1, . . . , an−1 (0 ¬ ai ¬ 1 000). This array represents number of mushrooms growing on the
consecutive spots along a road. You are also given integers k and m (0 ¬ k, m < n).
A mushroom picker is at spot number k on the road and should perform m moves. In
one move she moves to an adjacent spot. She collects all the mushrooms growing on spots
she visits. The goal is to calculate the maximum number of mushrooms that the mushroom
picker can collect in m moves.
For example, consider array A such that:
2 3 7 5 1 3 9
The mushroom picker starts at spot (array index) k = 4 and should perform m = 6 moves. She might
move to spots 3, 2, 3, 4, 5, 6 and thereby collect 1 + 5 + 7 + 3 + 9 = 25 mushrooms. This is the
maximal number of mushrooms she can collect.
*/
fun pickMaximumMushroomsInGivenMoves(A: Array<Int>, k: Int, m: Int): Int {
val prefixSums = calculatePrefixSums(A)
/**
* If we make p moves in one direction, we can calculate the maximal opposite location of the mushroom picker. The mushroom
* picker collects all mushrooms between these extremes. We can calculate the total number of
* collected mushrooms in constant time by using prefix sums.
*/
//first start moving left first, then right
//i.e. p step left, take p step go get back to k spot, now take remaining steps (m - 2p) right
val leftFirstMax = moveMushroomPickerLeftFirst(A, prefixSums, k, m)
//now start moving right first then left
val rightFirstMax = moveMushroomPickerRightFirst(A, prefixSums, k, m)
return max(leftFirstMax, rightFirstMax)
}
/**
* If we make p moves in one direction, we can calculate the maximal opposite location of the mushroom picker. The mushroom
* picker collects all mushrooms between these extremes. We can calculate the total number of
* collected mushrooms in constant time by using prefix sums.
*/
private fun moveMushroomPickerLeftFirst(A: Array<Int>, prefixSums: Array<Int>, k: Int, m: Int): Int {
//first try moving left first
var max = 0
val leftSliceLength = k // k - 0 = k
//we can't exceed left slice length neither can we exceed maximum allowed moves
//so we can only move left as long as there are moves left and we don't exceed slice length (to avoid index out of bound)
val maxLeftMovesPossible = min(leftSliceLength, m)
for (p in 0..maxLeftMovesPossible) {
//move left by p steps
val leftPosition = k - p
//as we have moved left by p steps so remaining moves are
// = m - 2p
// why 2? Because to go to right we have to go through the steps
//that we took to go left first. So we went by p steps to left
//then to go to right we first went back by p steps (back at k now)
//and now we can go to right
//also to go right
val rightStepsPossible = (m - 2 * p)
var proposedRightPosition = k + rightStepsPossible
//it is possible that we took all allowed m moves to left so in this
//case p = m, so (m - 2p) => (m - 2m) => -m
// right position can't be negative so in this case no right steps
//can be take so we will be k on right side
//you can validate it as
//proposedRightPosition = max(proposedRightPosition, k)
//or
if (proposedRightPosition < k) {
proposedRightPosition = k
}
//we don't want to overshoot array length.
val finalRightPosition = min(proposedRightPosition, A.size - 1)
val sliceSum = calculateSliceSum(prefixSums, leftPosition, finalRightPosition)
max = max(max, sliceSum)
}
return max
}
/**
* If we make p moves in one direction, we can calculate the maximal opposite location of the mushroom picker. The mushroom
* picker collects all mushrooms between these extremes. We can calculate the total number of
* collected mushrooms in constant time by using prefix sums.
*/
private fun moveMushroomPickerRightFirst(A: Array<Int>, prefixSums: Array<Int>, k: Int, m: Int): Int {
//same logic as move left first method but in opposite meanings
var max = 0
val lengthOfRightSlice = A.size - k - 1
val maxPossibleRightMoves = min(lengthOfRightSlice, m)
for (p in 0..maxPossibleRightMoves) {
val rightPosition = k + p
val leftSteps = k - (m - 2 * p)
var proposedLeftPosition = k - leftSteps
//it is possible that we took all allowed m moves to right so in this case no left steps
//can be take so we will be k on left side.
//so in this
//case p = m, so k -(m - 2p) => k -(m - 2m) => k - (-m) => k + m => k+m > k so array will overshoot
// left position can't overshoot array. You can validate it as
//proposedLeftPosition = min(proposedLeftPosition, k)
//or
if (proposedLeftPosition > k) {
proposedLeftPosition = k
}
//just to avoid array overshoot
val finalLeftPosition = max(proposedLeftPosition, 0)
val sliceSum = calculateSliceSum(prefixSums, finalLeftPosition, rightPosition)
max = max(sliceSum, max)
}
return max
}
/**
*A non-empty array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.
*
*Array A contains only 0s and/or 1s:
*
*0 represents a car traveling east,
*1 represents a car traveling west.
*The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.
*
*For example, consider array A such that:
*
* A[0] = 0
* A[1] = 1
* A[2] = 0
* A[3] = 1
* A[4] = 1
*We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
*
*Write a function:
*
*class Solution { public int solution(int[] A); }
*
*that, given a non-empty array A of N integers, returns the number of pairs of passing cars.
*
*The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.
*
*For example, given:
*
* A[0] = 0
* A[1] = 1
* A[2] = 0
* A[3] = 1
* A[4] = 1
*the function should return 5, as explained above.
*
*Write an efficient algorithm for the following assumptions:
*
*N is an integer within the range [1..100,000];
*each element of array A is an integer that can have one of the following values: 0, 1.
*/
fun findTotalCarPairs(A: Array<Int>): Int {
val maxPairsCountAllowed = 1_000_000_000
val prefixSums = calculatePrefixSums(A)
var pairsCount = 0
A.forEachIndexed { index, value ->
if (value == 0) {
pairsCount += calculateSliceSum(prefixSums, index, A.size - 1)
}
if (pairsCount > maxPairsCountAllowed) {
return -1
}
}
return pairsCount
}
/**
* A DNA sequence can be represented as a string consisting of the letters A, C, G and T,
* which correspond to the types of successive nucleotides in the sequence.
* Each nucleotide has an impact factor, which is an integer.
* Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively.
* You are going to answer several queries of the form:
* What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence?
*
* The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive).
* For example, consider string S = CAGCCTA and arrays P, Q such that:
*
* P[0] = 2 Q[0] = 4
* P[1] = 5 Q[1] = 5
* P[2] = 0 Q[2] = 6
*
* The answers to these M = 3 queries are as follows:
*
* The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2.
* The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4.
* The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1.
*
* Write a function:
*
* class Solution { public int[] solution(String S, int[] P, int[] Q); }
*
* that, given a non-empty string S consisting of N characters and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries.
* Result array should be returned as an array of integers.
*
* For example, given the string S = CAGCCTA and arrays P, Q such that:
*
* P[0] = 2 Q[0] = 4
* P[1] = 5 Q[1] = 5
* P[2] = 0 Q[2] = 6
*
* the function should return the values [2, 4, 1], as explained above.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [1..100,000];
* M is an integer within the range [1..50,000];
* each element of arrays P, Q is an integer within the range [0..N − 1];
* P[K] ≤ Q[K], where 0 ≤ K < M;
* string S consists only of upper-case English letters A, C, G, T.
*/
fun findMinimalImpactFactorForDNASequence(S: String, P: Array<Int>, Q: Array<Int>): Array<Int> {
val nucleotidesMap = mapOf('A' to 1, 'C' to 2, 'G' to 3, 'T' to 4) //for A, C, G, T respectively
//calculate prefix sum for occurrence of each nucleotide in string S
val nucleotidesPrefixSumsMap = prefixSumOfNucleotides(S, nucleotidesMap.keys)
val answer = Array(P.size) {0}
for (i in 0 until P.size) {
val p = P[i]
val q = Q[i]
//for each nucleotide, check if it is present in range [p, q]
//and set the first encountered nucleotide's impact factor
//why first encounter? because we are searching in order [A, C, G, T]
//which is also the order in which impact factors are sorted and if A is in range [P, Q]
//then that is the minimum
for ( (nucleotide, impactFactor) in nucleotidesMap) {
val prefixSumsForNucleotide = nucleotidesPrefixSumsMap.getValue(nucleotide)
if (calculateSliceSum(prefixSumsForNucleotide, p, q) > 0) {
answer[i] = impactFactor
break
}
}
}
return answer
}
/**
* We will only calculate prefixSum for how many times a nucleotide occurs in given range
* so P3 = 2 for nucleotide 'A' means that 'A' occurred 2 times till range [0, 2]
*/
private fun prefixSumOfNucleotides(S: String, nucleotides: Set<Char>): Map<Char, Array<Int>> {
val nucleotidesPrefixSumsMap = HashMap<Char, Array<Int>>(nucleotides.size)
//initialise sums array for each nucleotide
val prefixSumSize = S.length + 1
nucleotides.forEach { nucleotide ->
nucleotidesPrefixSumsMap[nucleotide] = Array(prefixSumSize) {0}
}
//prefixSums for each nucleotide
for (i in 1 until prefixSumSize) {
val currentNucleotide = S[i-1]
nucleotides.forEach { nucleotide ->
//for nucleotide == currentNucleotide
// Pi = Pi-1 + 1
//for all others
//Pi = Pi-1 + 0
val prefixSumsForNucleotide = nucleotidesPrefixSumsMap[nucleotide]!!
prefixSumsForNucleotide[i] = prefixSumsForNucleotide[i-1] + (currentNucleotide == nucleotide).toInt()
}
}
return nucleotidesPrefixSumsMap
}
/**
* MinAvgTwoSlice
*
* Find the minimal average of any slice containing at least two elements.
* Programming language:
* A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).
*
* For example, array A such that:
*
* A[0] = 4
* A[1] = 2
* A[2] = 2
* A[3] = 5
* A[4] = 1
* A[5] = 5
* A[6] = 8
* contains the following example slices:
*
* slice (1, 2), whose average is (2 + 2) / 2 = 2;
* slice (3, 4), whose average is (5 + 1) / 2 = 3;
* slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.
* The goal is to find the starting position of a slice whose average is minimal.
*
* Write a function:
*
* class Solution { public int solution(int[] A); }
*
* that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.
*
* For example, given array A such that:
*
* A[0] = 4
* A[1] = 2
* A[2] = 2
* A[3] = 5
* A[4] = 1
* A[5] = 5
* A[6] = 8
* the function should return 1, as explained above.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [2..100,000];
* each element of array A is an integer within the range [−10,000..10,000].
*/
fun findMinAvgSlice(A: Array<Int>): Int {
/*
For solution check:
https://www.martinkysel.com/codility-minavgtwoslice-solution/
https://codesays.com/2014/solution-to-min-avg-two-slice-by-codility/
For general math proof:
https://github.com/daotranminh/playground/blob/master/src/codibility/MinAvgTwoSlice/proof.pdf
General idea:
1. A slice needs to have at least 2 elements. A slice of size 4 can be divided into
2 slices of size 2 each. A slice of size 5 can be divided into 2 slices of size 2 and 3 respectively.
so all bigger slices are made up of either 2 or 3 (to handle odd size of bigger slice) sub-slices.
For a bigger
2 If we say that a bigger slice (size > 3) has minimal avg that means that either its sub-slices have
same avg because otherwise the bigger slice can not have minimal avg (because at least one subslice will have
less avg than bigger slice). Using this argument we can divide the bigger sub-slice into smaller slices and keep
dividing (again using the same argument) until we reach 2 or 3 size sub-slices (a slice can't be smaller than this).
So instead of finding a bigger slice with min avg we can just check 2 or 3 size sub-slices and pick the one with
min avg (because bigger slice can only be optimal if smaller sub-slices are optimal)
*/
var minAvgSliceIndex = 0
var minAvg = 10_000.0 //max possible value of Ai
for (i in 0 until A.size - 2) {
//check the 2 size sub-slice
val twoSizeSliceAvg = (A[i] + A[i+1]) / 2.0
if (twoSizeSliceAvg < minAvg) {
minAvg = twoSizeSliceAvg
minAvgSliceIndex = i
}
val threeSizeSliceAvg = (A[i] + A[i + 1] + A[i + 2]) / 3.0
if (threeSizeSliceAvg < minAvg) {
minAvg = threeSizeSliceAvg
minAvgSliceIndex = i
}
}
//check the last 2 size slice
val lastTwoSizeSliceAvg = (A[A.size - 1] + A[A.size - 2]) / 2.0
if (lastTwoSizeSliceAvg < minAvg) {
minAvgSliceIndex = A.size - 2
}
return minAvgSliceIndex
}
private fun calculateSliceSumAvg(P: Array<Int>, x: Int, y: Int): Double {
val elementsCount = y - x + 1.0
//slice needs to have at least 2 elements to be called sliced
if (elementsCount < 2) {
return 10_0000.0
}
return calculateSliceSum(P, x, y) / elementsCount
}
//https://app.codility.com/programmers/lessons/5-prefix_sums/count_div/
fun countDiv(A: Int, B: Int, K: Int): Int {
//NOTE: each divisible number has to be in range [A, B] and we can not exceed this range
//find the first divisible (by k) number after A (greater than A but less than B to stay in range)
var newA = A
while (newA % K != 0 && newA < B)
newA++
//find the first divisible (by k) number before B (less than B but greater than A to stay in range)
var newB = B
while (newB % K != 0 && newB > newA)
newB--
//now that we have final new range ([newA, newB]), verify that both newA and newB are not equal
//because in that case there can be only number (newA or newB as both are equal) and we can just check
//if that number is divisible or not
if (newA == newB) {
return (newA % K == 0).toInt()
}
//Now that both newA and newB are divisible by K (a complete arithmetic sequence)
//we can calculate total divisions by using arithmetic sequence with following params
//a1 = newA, an = newB, d = K
// we know that n-th term (an) can also be calculated using following formula
//an = a1 + (n - 1)d
//n (total terms in sequence with distance d=K) is what we are interested in finding, put all values
//newB = newA + (n - 1)K
//re-arrange -> n = (newB - newA + K) / K
//Note: convert calculation to Long to avoid integer overflow otherwise result will be incorrect
val result = ((newB - newA + K.toLong()) / K.toDouble()).toInt()
return result
}
} | 0 | Kotlin | 0 | 0 | a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4 | 20,143 | codility-challenges-practice | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumRounds.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
/**
* 2244. Minimum Rounds to Complete All Tasks
* @see <a href="https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/">Source</a>
*/
fun interface MinimumRounds {
operator fun invoke(tasks: IntArray): Int
}
class MinimumRoundsSumUp : MinimumRounds {
override operator fun invoke(tasks: IntArray): Int {
val count = HashMap<Int, Int>()
for (a in tasks) {
count[a] = count.getOrDefault(a, 0) + 1
}
return count.values.takeUnless {
it.contains(1)
}?.sumOf {
(it + 2) / 3
} ?: -1
}
}
class MinimumRoundsGreedy : MinimumRounds {
override operator fun invoke(tasks: IntArray): Int {
return tasks.groupBy {
it
}.map {
if (it.value.size < 2) {
return -1
} else if (it.value.size == 2) {
1
} else {
var totalNumberOfThrees = it.value.size / 3
var numberLeft = it.value.size % 3
while (numberLeft % 2 != 0 && totalNumberOfThrees > 0) {
totalNumberOfThrees--
numberLeft += 3
}
if (totalNumberOfThrees == 0 && numberLeft % 2 != 0) {
return -1
} else {
totalNumberOfThrees + numberLeft / 2
}
}
}.sum()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,067 | kotlab | Apache License 2.0 |
src/main/kotlin/Day25.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package aoc
import kotlin.math.abs
import kotlin.math.pow
//2-=102--02--=1-12=22
fun solve25A(input: List<String>) = input.sumOf { it.fromSNAFU() }.toSNAFU()
fun String.fromSNAFU() = this.reversed().mapIndexed { index, c ->
val fiveSquared = 5.0.pow(index)
when (c) {
'2' -> fiveSquared * 2
'1' -> fiveSquared
'0' -> 0.0
'-' -> fiveSquared * -1
'=' -> fiveSquared * -2
else -> throw Exception("$c could not be parsed.")
}
}.sum().toLong()
fun Long.toSNAFU(): String {
var exponent = 0
while (5.0.pow(exponent).toLong() < this && 5.0.pow(exponent).toLong() * 2 < this) {
exponent++
}
return this.toSNAFU(exponent)
}
fun Long.toSNAFU(exp: Int): String {
if (exp == -1) return ""
if (this == 0L) return "0" + 0L.toSNAFU(exp - 1)
val fiveSquared = 5.0.pow(exp).toLong()
val isNegative = this < 0
val first = if (isNegative) fiveSquared * -1 else fiveSquared
val second = if (isNegative) fiveSquared * -2 else fiveSquared * 2
val currentRemainder = abs(this)
val firstRemainder = abs(this - first)
val secondRemainder = abs(this - second)
if (firstRemainder > currentRemainder && secondRemainder > currentRemainder) return "0" + this.toSNAFU(exp - 1)
return if (firstRemainder < secondRemainder) {
val remainder = this - first
val result = if (isNegative) "-" else "1"
result + remainder.toSNAFU(exp - 1)
} else {
val remainder = this - second
val result = if (isNegative) "=" else "2"
result + remainder.toSNAFU(exp - 1)
}
}
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 1,621 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | colund | 573,040,201 | false | {"Kotlin": 10244} | enum class RPS(val value: Int) { Rock(1), Paper(2), Scissors(3) }
fun main() {
data class RockPaperScissors(val rock: Char, val paper: Char, val scissors: Char) {
fun toRPS(char: Char) = when (char) {
rock -> RPS.Rock
paper -> RPS.Paper
scissors -> RPS.Scissors
else -> null
}
}
fun roundScore(me: RPS, they: RPS): Int {
var score = 0
if (me == they) {
score += 3 // draw
} else if ((me == RPS.Rock && they == RPS.Scissors) ||
(me == RPS.Paper && they == RPS.Rock) ||
(me == RPS.Scissors && they == RPS.Paper)
) {
score += 6 // win
}
return score + me.value
}
val me = RockPaperScissors('X', 'Y', 'Z')
val they = RockPaperScissors('A', 'B', 'C')
val testInput = readInput("Day02")
/////////////////////////////////
// Part 2
/////////////////////////////////
var score = 0
testInput.forEach {
val myChar = it[2]
val roundScore = roundScore(me.toRPS(myChar) ?: return@forEach, they.toRPS(it[0]) ?: return@forEach)
score += roundScore
}
println("Part 1 $score")
/////////////////////////////////
// Part 2
/////////////////////////////////
val second = testInput.mapNotNull {
val theirChoice = they.toRPS(it[0])
val myChoice = when (it[2]) {
'X' -> { // Need to lose
when (theirChoice) {
RPS.Rock -> RPS.Scissors
RPS.Paper -> RPS.Rock
RPS.Scissors -> RPS.Paper
null -> null
}
}
'Y' -> { // Need to draw
theirChoice
}
'Z' -> { // Need to win
when (theirChoice) {
RPS.Rock -> RPS.Paper
RPS.Paper -> RPS.Scissors
RPS.Scissors -> RPS.Rock
null -> null
}
}
else -> null
}
if (myChoice != null && theirChoice != null)
roundScore(myChoice, theirChoice)
else null
}.sum()
println("Round two $second")
}
| 0 | Kotlin | 0 | 0 | 49dcd2fccad0e54ee7b1a9cb99df2acdec146759 | 2,249 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day20.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2022
import AoCDay
import kotlin.math.abs
// https://adventofcode.com/2022/day/20
object Day20 : AoCDay<Long>(
title = "Grove Positioning System",
part1ExampleAnswer = 3,
part1Answer = 19559,
part2ExampleAnswer = 1623178306,
part2Answer = 912226207972,
) {
private fun parseNumbers(file: String) = file.lines().map(String::toLong)
private class NumbersList(numbers: List<Long>) {
private class Node(val number: Long) {
lateinit var left: Node
lateinit var right: Node
}
// all nodes in original order
private val nodes = numbers.map(::Node)
private val size get() = nodes.size
init {
for ((i, node) in nodes.withIndex()) {
node.left = nodes[(i - 1).mod(size)]
node.right = nodes[(i + 1).mod(size)]
}
}
fun mix() {
for (node in nodes) {
// node does not count when moving -> % (size - 1)
val move = (node.number % (size - 1)).toInt()
if (move == 0) continue
// remove node from list
node.left.right = node.right
node.right.left = node.left
// insert node again at correct position
var target = node
if (move < 0) {
repeat(abs(move)) {
target = target.left
}
node.right = target
target.left.right = node
node.left = target.left
target.left = node
} else {
repeat(move) {
target = target.right
}
node.left = target
target.right.left = node
node.right = target.right
target.right = node
}
}
}
fun sumOfGroveCoordinates(): Long {
val groveCoordinateIndices = listOf(1000, 2000, 3000).map { it % size }
var sum = 0L
var node = nodes.first { it.number == 0L }
for (i in 1..groveCoordinateIndices.max()) {
node = node.right
// in case, more than one index point to the same node
repeat(groveCoordinateIndices.count { it == i }) {
sum += node.number
}
}
return sum
}
}
override fun part1(input: String): Long {
val list = NumbersList(parseNumbers(input))
list.mix()
return list.sumOfGroveCoordinates()
}
override fun part2(input: String): Long {
val list = NumbersList(parseNumbers(input).map { it * 811589153 })
repeat(10) {
list.mix()
}
return list.sumOfGroveCoordinates()
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 2,918 | advent-of-code-kotlin | MIT License |
src/main/kotlin/fr/o80/aoc/kit/knapsack/Knapsack.kt | olivierperez | 310,899,127 | false | {"Kotlin": 104427} | package fr.o80.aoc.kit.knapsack
import fr.o80.aoc.kit.table.Table
/**
// Example
```
val packets: List<Packet> = input
.filterIndexed { index, _ -> index != 0 }
.map(::toPacket)
.sortedBy { -it.volume }
.toList()
val truckSize = packets.sumBy { it.volume } / 2
val knapsack = Knapsack<Packet>(
items = packets,
capacity = truckSize,
interestOf = { it.volume },
costOf = { it.volume }
)
val result: Knapsack.Info<Packet> = knapsack.compute()
val firstTruck = result.items
val secondTruck = packets - firstTruck
```
*/
class Knapsack<T>(
private val items: List<T>,
private val capacity: Int,
private val interestOf: (T) -> Int,
private val costOf: (T) -> Int
) {
private val table = Table<KnapsackInfo<T>>(capacity + 1, items.size + 1)
fun compute(): KnapsackInfo<T> {
for (i in 0..items.size) {
for (c in 0..capacity) {
when {
i == 0 -> table[c, 0] = KnapsackInfo(0, emptyList())
c == 0 -> table[0, i] = KnapsackInfo(0, emptyList())
else -> {
table[c,i] = fillKnapsack(
item = items[i - 1],
c = c,
i = i
)
}
}
}
}
return table[capacity, items.size]!!
}
fun debug() {
table.debug()
}
private fun fillKnapsack(item: T, c: Int, i: Int): KnapsackInfo<T> {
if (i == 0) {
return KnapsackInfo(0, emptyList())
}
val wi = costOf(item)
val pi = interestOf(item)
return if (c >= pi) {
val sameInfoForLessCapacity = table[c, i - 1]!!
val otherCell = table[c - pi, i - 1]!!
val firstValue = sameInfoForLessCapacity.value
val secondValue = otherCell.value + wi
if (firstValue >= secondValue) {
sameInfoForLessCapacity
} else {
KnapsackInfo(secondValue, otherCell.items + item)
}
} else {
table[c, i - 1]!!
}
}
}
| 0 | Kotlin | 1 | 2 | c92001b5d4651e67e17c20eb8ddc2ac62b14f2c2 | 2,256 | AdventOfCode-KotlinStarterKit | Apache License 2.0 |
src/Day09.kt | casslabath | 573,177,204 | false | {"Kotlin": 27085} | import kotlin.math.abs
fun main() {
fun MutableList<MutableList<Int>>.head(): MutableList<Int> {
return this[0]
}
fun MutableList<MutableList<Int>>.tail(): MutableList<Int> {
return this[9]
}
fun updatedCoords(dir: String): Pair<Int, Int> {
return when (dir) {
"U"-> {
0 to 1
}"D" -> {
0 to -1
} "L" -> {
-1 to 0
} "R" -> {
1 to 0
} else -> {
throw Exception("input is invalid")
}
}
}
fun part1(input: List<String>): Int {
val visitedCoords = mutableSetOf<Pair<Int, Int>>()
var hX = 0
var hY = 0
var tX = 0
var tY = 0
visitedCoords.add(0 to 0)
input.map {
val (dir, distStr) = it.split(" ")
val dist = distStr.toInt()
for(i in 0 until dist) {
val currX = hX
val currY = hY
// Update the head know
val updatedCoords = updatedCoords(dir)
hX += updatedCoords.first // updatedCoords x value
hY += updatedCoords.second // updatedCoords y value
// T replaces where H was if H gets more than one move away (up, down, left, right or diagonal)
if(abs(hX-tX) + abs(hY-tY) == 3 || abs(hX-tX) == 2 || abs(hY-tY) == 2 ) {
tX = currX
tY = currY
}
visitedCoords.add(tX to tY)
}
}
return visitedCoords.size
}
fun part2(input: List<String>): Int {
val visitedCoords = mutableSetOf<Pair<Int, Int>>()
val coords = mutableListOf<MutableList<Int>>()
visitedCoords.add(0 to 0)
for(i in 0..9) {
coords.add(mutableListOf(0,0))
}
input.map {
val (dir, distStr) = it.split(" ")
val dist = distStr.toInt()
for(distNum in 0 until dist) {
// Update the Head Knot
val updatedCoords = updatedCoords(dir)
coords.head()[0] += updatedCoords.first // updatedCoords x value
coords.head()[1] += updatedCoords.second // updatedCoords y value
for(i in 1..9) {
// distance between current knot and the last knot after it is updated
val xDist = coords[i-1][0] - coords[i][0]
val yDist = coords[i-1][1] - coords[i][1]
fun updateX() {
if (xDist < 0) {
coords[i][0]--
} else {
coords[i][0]++
}
}
fun updateY() {
if (yDist < 0) {
coords[i][1]--
} else {
coords[i][1]++
}
}
// The portion of the rope is diagonal + one away
if(abs(xDist) + abs(yDist) == 3) {
updateX()
updateY()
} else {
if (abs(xDist) == 2) {
updateX()
}
if (abs(yDist) == 2) {
updateY()
}
}
}
visitedCoords.add(coords.tail()[0] to coords.tail()[1])
}
}
return visitedCoords.size
}
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5f7305e45f41a6893b6e12c8d92db7607723425e | 3,772 | KotlinAdvent2022 | Apache License 2.0 |
src/main/kotlin/com/leetcode/top100LikedQuestions/easy/mergind_two_binaries_tree/Main.kt | frikit | 254,842,734 | false | null | package com.leetcode.top100LikedQuestions.easy.mergind_two_binaries_tree
/**
* Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.
*/
fun main() {
println("Test case 1:")
//t1
val t1 = TreeNode(1)
run {
val leftFirstLeaf = TreeNode(3)
val rightFirstLeaf = TreeNode(2)
val leftSecondLeaf = TreeNode(5)
val rightSecondLeaf = null
//set nodes
t1.left = leftFirstLeaf
t1.right = rightFirstLeaf
leftFirstLeaf.left = leftSecondLeaf
leftFirstLeaf.right = rightSecondLeaf
}
//t2
val t2 = TreeNode(2)
run {
val leftFirstLeaf = TreeNode(1)
val rightFirstLeaf = TreeNode(3)
val leftSecondLeaf = null
val rightSecondLeaf = TreeNode(4)
val leftSecondLeaf2 = null
val rightSecondLeaf2 = TreeNode(7)
//set nodes
t1.left = leftFirstLeaf
t1.right = rightFirstLeaf
leftFirstLeaf.left = leftSecondLeaf
leftFirstLeaf.right = rightSecondLeaf
rightFirstLeaf.left = leftSecondLeaf2
rightFirstLeaf.right = rightSecondLeaf2
}
println(Solution().mergeTrees(t1, t2))
println()
}
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun mergeTrees(t1: TreeNode?, t2: TreeNode?): TreeNode? {
if (t1 == null) return t2
if (t2 == null) return t1
t1.`val` += t2.`val`
t1.left = mergeTrees(t1.left, t2.left)
t1.right = mergeTrees(t1.right, t2.right)
return t1
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| 0 | Kotlin | 0 | 0 | dda68313ba468163386239ab07f4d993f80783c7 | 2,466 | leet-code-problems | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day12/Day12.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day12
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 12](https://adventofcode.com/2021/day/12)
*/
object Day12 : DayOf2021(12) {
override fun first(): Any? {
val edges = lines
.map { it.split("-") }
.flatMap { listOf(it.first() to it.last(), it.last() to it.first()) }
.groupBy(
keySelector = { it.first },
valueTransform = { it.second },
)
.mapValues { it.value.sorted() }
val visited = mutableSetOf<List<String>>()
val finish = mutableSetOf<List<String>>()
val queue = ArrayDeque(listOf(listOf("start")))
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
if (curr !in visited) {
visited += curr
val tail = curr.last()
if (tail == "end") {
finish += curr
} else {
queue += edges[tail].orEmpty()
.filter { it.uppercase() == it || it !in curr }
.map { curr + it }
.filter { it !in visited }
}
}
}
return finish.size
}
override fun second(): Any? {
val edges = lines
.map { it.split("-") }
.flatMap { listOf(it.first() to it.last(), it.last() to it.first()) }
.groupBy(
keySelector = { it.first },
valueTransform = { it.second },
)
.mapValues { it.value.sorted() }
val visited = mutableSetOf<List<String>>()
val finish = mutableSetOf<List<String>>()
val queue = ArrayDeque(listOf(listOf("start") to false))
while (queue.isNotEmpty()) {
val (curr, twice) = queue.removeFirst()
if (curr !in visited) {
visited += curr
val tail = curr.last()
val nexts = edges[tail].orEmpty()
if ("end" in nexts) {
finish += curr + "end"
}
queue += nexts
.asSequence()
.filter { it !in setOf("start", "end") }
.filter { it.uppercase() == it || it !in curr }
.map { curr + it }
.filter { it !in visited }
.map { it to twice }
if (!twice) {
queue += nexts
.asSequence()
.filter { it !in setOf("start", "end") }
.filter { it.lowercase() == it && it in curr }
.map { curr + it }
.filter { it !in visited }
.map { it to true }
}
}
}
return finish.size
}
}
fun main() = SomeDay.mainify(Day12)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,479 | adventofcode | MIT License |
kotlin-stlc/app/src/main/kotlin/stlc/Constraints.kt | graeme-lockley | 540,723,061 | false | {"Kotlin": 57141, "TypeScript": 41966, "C": 36472, "Shell": 8245, "Makefile": 679, "Dockerfile": 574} | package stlc
typealias Constraint = Pair<Type, Type>
data class Constraints(private val constraints: MutableList<Constraint> = mutableListOf()) {
fun add(t1: Type, t2: Type) {
constraints.add(Pair(t1, t2))
}
fun solve(): Subst =
solver(constraints)
override fun toString(): String = constraints.joinToString(", ") { "${it.first} ~ ${it.second}" }
fun clone(): Constraints = Constraints(constraints.toMutableList())
}
private data class Unifier(val subst: Subst, val constraints: List<Constraint>)
private val emptyUnifier = Unifier(nullSubst, emptyList())
private fun bind(name: Var, type: Type): Unifier =
Unifier(Subst(mapOf(Pair(name, type))), emptyList())
private fun unifies(t1: Type, t2: Type): Unifier =
when {
t1 == t2 -> emptyUnifier
t1 is TVar -> bind(t1.name, t2)
t2 is TVar -> bind(t2.name, t1)
t1 is TArr && t2 is TArr -> unifyMany(listOf(t1.domain, t1.range), listOf(t2.domain, t2.range))
t1 is TTuple && t2 is TTuple -> unifyMany(t1.types, t2.types)
else -> throw UnificationMismatch(t1, t2)
}
private fun applyTypes(s: Subst, ts: List<Type>): List<Type> =
ts.map { it.apply(s) }
private fun unifyMany(ta: List<Type>, tb: List<Type>): Unifier =
if (ta.isEmpty() && tb.isEmpty()) emptyUnifier
else if (ta.isEmpty() || tb.isEmpty()) throw UnificationManyMismatch(ta, tb)
else {
val t1 = ta[0]
val ts1 = ta.drop(1)
val t2 = tb[0]
val ts2 = tb.drop(1)
val (su1, cs1) = unifies(t1, t2)
val (su2, cs2) = unifyMany(applyTypes(su1, ts1), applyTypes(su1, ts2))
Unifier(su2 compose su1, cs1 + cs2)
}
private fun solver(constraints: List<Constraint>): Subst {
var su = nullSubst
var cs = constraints.toList()
while (cs.isNotEmpty()) {
val (t1, t2) = cs[0]
val cs0 = cs.drop(1)
val (su1, cs1) = unifies(t1, t2)
su = su1 compose su
cs = cs1 + cs0.map { Pair(it.first.apply(su1), it.second.apply(su1)) }
}
return su
}
data class UnificationMismatch(val t1: Type, val t2: Type) : Exception()
data class UnificationManyMismatch(val t1: List<Type>, val t2: List<Type>) : Exception()
| 0 | Kotlin | 0 | 0 | bb29888a15584b9539ba6ae04e112022779b974d | 2,233 | little-languages | MIT License |
shark/shark/src/main/java/shark/ReferenceMatcher.kt | square | 34,824,499 | false | {"Kotlin": 1430657, "Java": 4762, "Shell": 531, "AIDL": 203} | package shark
/**
* Used to pattern match known patterns of references in the heap, either to ignore them
* ([IgnoredReferenceMatcher]) or to mark them as library leaks ([LibraryLeakReferenceMatcher]).
*/
sealed class ReferenceMatcher {
/** The pattern that references will be matched against. */
abstract val pattern: ReferencePattern
}
/**
* [LibraryLeakReferenceMatcher] should be used to match references in library code that are
* known to create leaks and are beyond your control. The shortest path finder will only go
* through matching references after it has exhausted references that don't match, prioritizing
* finding an application leak over a known library leak. Library leaks will be reported as
* [LibraryLeak] instead of [ApplicationLeak].
*/
data class LibraryLeakReferenceMatcher(
override val pattern: ReferencePattern,
/**
* A description that conveys what we know about this library leak.
*/
val description: String = "",
/**
* Whether the identified leak may exist in the provided [HeapGraph]. Defaults to true. If
* the heap dump comes from a VM that runs a different version of the library that doesn't
* have the leak, then this should return false.
*/
val patternApplies: (HeapGraph) -> Boolean = { true }
) : ReferenceMatcher() {
override fun toString() = "library leak: $pattern"
}
/**
* [IgnoredReferenceMatcher] should be used to match references that cannot ever create leaks. The
* shortest path finder will never go through matching references.
*/
class IgnoredReferenceMatcher(override val pattern: ReferencePattern) : ReferenceMatcher() {
override fun toString() = "ignored ref: $pattern"
}
internal fun Iterable<ReferenceMatcher>.filterFor(graph: HeapGraph): List<ReferenceMatcher> {
return filter { matcher ->
(matcher is IgnoredReferenceMatcher ||
(matcher is LibraryLeakReferenceMatcher && matcher.patternApplies(graph)))
}
}
| 91 | Kotlin | 4,013 | 29,004 | b3d151194b8501ea85f96d236f7ab2bb7a3e8762 | 1,933 | leakcanary | Apache License 2.0 |
src/Day04.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | class Day04 {
fun part1(input: List<String>): Int{
return input.map {
val pair = it.split(",")
val a = pair[0].split("-").map { it.toInt() }
val b = pair[1].split("-").map { it.toInt() }
if (((b[0] >= a[0]).and(b[1] <= a[1])) or ((a[0] >= b[0]).and(a[1] <= b[1])))
1
else
0
}.sum()
}
fun part2(input: List<String>): Int{
return input.map {
val pair = it.split(",")
val a = pair[0].split("-").map { it.toInt() }
val b = pair[1].split("-").map { it.toInt() }
if (a[0].coerceAtLeast(b[0]) <= a[1].coerceAtMost(b[1]))
1
else
0
}.sum()
}
}
fun main() {
val testInput = readInput("Day04_test")
check(Day04().part1(testInput) == 2)
measureTimeMillisPrint {
val input = readInput("Day04")
println(Day04().part1(input))
println(Day04().part2(input))
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 1,019 | aoc-22-kotlin | Apache License 2.0 |
src/Day09.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
infix fun Point.follow(head: Point) {
val dx = head.x - x
val dy = head.y - y
if (abs(dx) > 1 || abs(dy) > 1) {
this += Point(dx.sign, dy.sign)
}
}
fun part1(input: List<String>): Int {
val head = Point(0, 0)
val tail = Point(0, 0)
val visited = mutableSetOf<Point>()
input.map {
it.split(" ")
}.forEach { (direction, amount) ->
val dirVector = when (direction) {
"U" -> Point(0, +1)
"D" -> Point(0, -1)
"L" -> Point(-1, 0)
"R" -> Point(+1, 0)
else -> error("wrong direction $direction")
}
for (i in 0 until amount.toInt()) {
head += dirVector
tail.follow(head)
visited.add(tail.copy())
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val knots = MutableList(10) { Point(0, 0) }
val visited = mutableSetOf<Point>()
input.map {
it.split(" ")
}.forEach { (direction, amount) ->
val dirVector = when (direction) {
"U" -> Point(0, +1)
"D" -> Point(0, -1)
"L" -> Point(-1, 0)
"R" -> Point(+1, 0)
else -> error("wrong direction $direction")
}
for (i in 0 until amount.toInt()) {
knots.forEachIndexed { index, knot ->
if (index == 0) {
knot += dirVector
} else {
knot follow knots[index-1]
}
if (index == 9) {
visited.add(knot.copy())
}
}
}
}
return visited.size
}
val input = readInput("inputs/Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 2,047 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | Ajimi | 572,961,710 | false | {"Kotlin": 11228} | fun main() {
fun Char.score() = if (isLowerCase()) {
this - 'a' + 1
} else {
this - 'A' + 27
}
fun part1(input: List<String>): Int = input
.map { it.chunked(it.length / 2) }
.fold(listOf<Int>()) { acc, (first, second) ->
first.forEach { character ->
if (second.contains(character)) {
return@fold acc + character.score()
}
}
acc
}.sum()
fun part2(input: List<String>) = input
.chunked(3)
.fold(listOf<Int>()) { acc, (first, second, third) ->
first.forEach { character ->
if (second.contains(character) && third.contains(character)) {
return@fold acc + character.score()
}
}
acc
}.sum()
// 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 | 8c2211694111ee622ebb48f52f36547fe247be42 | 1,090 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/day4.kt | sviams | 726,160,356 | false | {"Kotlin": 9233} | object day4 {
data class Card(val id: Int, val winning: List<Int>, val mine: List<Int>) {
val matches by lazy { mine.intersect(winning) }
val value by lazy {
if (matches.isEmpty()) 0 else
( 0 until matches.size-1).fold(1) { acc, i -> acc * 2 }
}
val copies by lazy { matches.indices.fold(emptyList<Int>()) { acc, i -> acc.plus(id+i+1) } }
}
fun parseInput(input: List<String>): List<Card> = input.fold(emptyList<Card>()) { acc, line ->
val (id) = Regex("""Card\s+(\d+):""").find(line)!!.destructured
val parts = line.split(':').last().split('|')
val winning = parts[0].split(' ').filterNot { it.isEmpty() }.map { it.toInt() }
val mine = parts[1].split(' ').filterNot { it.isEmpty() }.map { it.toInt() }
acc + Card(id.toInt(), winning, mine)
}
fun pt1(input: List<String>): Int = parseInput(input).sumOf { it.value }
fun pt2(input: List<String>): Int = parseInput(input)
.reversed()
.fold(emptyMap<Int, Int>()) { res, card -> res + (card.id to (1 + card.copies.sumOf { res[it]!! }))}.values.sum()
} | 0 | Kotlin | 0 | 0 | 4914a54b21e8aac77ce7bbea3abc88ac04037d50 | 1,141 | aoc23 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1383/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1383
import java.util.*
/**
* LeetCode page: [1383. Maximum Performance of a Team](https://leetcode.com/problems/maximum-performance-of-a-team/);
*/
class Solution {
/* Complexity:
* Time O(NLogN) and Space O(N) where N equals n;
*/
fun maxPerformance(n: Int, speed: IntArray, efficiency: IntArray, k: Int): Int {
val sortedEngineers = getEngineersSortedByEfficiency(speed, efficiency)
var maxPerformance = 0L
val teamSpeedMinPq = PriorityQueue<Int>()
var sumOfTeamSpeed = 0L
for (index in sortedEngineers.indices.reversed()) {
val currSpeed = sortedEngineers[index].speed
val currEfficiency = sortedEngineers[index].efficiency
teamSpeedMinPq.offer(currSpeed)
sumOfTeamSpeed += currSpeed
val teamSizeExceeded = teamSpeedMinPq.size > k
if (teamSizeExceeded) sumOfTeamSpeed -= teamSpeedMinPq.poll()
val leastMaxPerformance = sumOfTeamSpeed * currEfficiency
maxPerformance = maxOf(maxPerformance, leastMaxPerformance)
}
return maxPerformance.toOutputFormat()
}
private fun getEngineersSortedByEfficiency(speed: IntArray, efficiency: IntArray): List<Engineer> {
return speed
.asSequence()
.zip(efficiency.asSequence()) { spd, eff -> Engineer(spd, eff) }
.sortedBy { engineer -> engineer.efficiency }
.toList()
}
private data class Engineer(val speed: Int, val efficiency: Int)
private fun Long.toOutputFormat(): Int {
val requiredModulo = 1_000_000_007
return (this % requiredModulo).toInt()
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,706 | hj-leetcode-kotlin | Apache License 2.0 |
src/day7/Day7.kt | blundell | 572,916,256 | false | {"Kotlin": 38491} | package day7
import readInput
data class FileDetails(
val name: String,
val size: Long,
)
data class Directory(
val name: String,
val parent: Directory?,
val directories: MutableList<Directory> = mutableListOf(),
val files: MutableList<FileDetails> = mutableListOf(),
) {
val size: Long by lazy {
var size = 0L
for (directory in directories) {
size += directory.size
}
for (file in files) {
size += file.size
}
size
}
/**
* Return any directory we contiain that is under 100,000 total size, including ourselves
*/
fun smallsOrEmpty(output: MutableList<Directory>) {
if (size <= 100_000) {
output.add(this)
}
for (directory in directories) {
directory.smallsOrEmpty(output)
}
}
fun hasDir(directory: Directory): Boolean = this.directories.find {
it.name == directory.name && it.parent == directory.parent
} != null
fun addFile(name: String, size: Long) {
this.files.add(FileDetails(name, size))
}
fun findOver(sizeMin: Long, output: MutableList<Directory>) {
if (this.size >= sizeMin) {
output.add(this)
}
for (directory in directories) {
directory.findOver(sizeMin, output)
}
}
}
fun main() {
fun readFileSystem(input: List<String>): Directory {
var fileSystem: Directory? = null
var currentDirectory: Directory? = null
for (line in input) {
if (line.startsWith("$")) {
// Found an instruction
if (line.startsWith("$ cd")) {
// Found a directory
val directoryName = line.substring(5)
val directory: Directory
if (directoryName == "..") {
directory = currentDirectory!!.parent!!
} else {
directory = Directory(name = directoryName, parent = currentDirectory)
if (currentDirectory == null) {
fileSystem = directory
} else {
if (!currentDirectory.hasDir(directory)) {
currentDirectory.directories.add(directory)
}
}
}
currentDirectory = directory
} else if (line.startsWith("$ ls")) {
// listing files & directories next
}
} else if (line.matches("^[0-9].*".toRegex())) {
// Description of a file
val size = line.substringBefore(' ').toLong()
val name = line.substringAfter(' ')
currentDirectory!!.addFile(name, size)
} else if (line.startsWith("dir")) {
// Description of a folder
// We don't record this; it has no size, so it is not interesting
} else {
throw IllegalStateException("Unhandled line [$line]")
}
}
return fileSystem!!
}
fun part1(input: List<String>): Int {
val fileSystem: Directory = readFileSystem(input)
val smalls = mutableListOf<Directory>()
fileSystem.smallsOrEmpty(smalls)
return smalls.sumOf { it.size }.toInt()
}
fun part2(input: List<String>): Int {
val fileSystem: Directory = readFileSystem(input)
val unusedSpace = 70_000_000 - fileSystem.size
val neededSpace = 30_000_000 - unusedSpace
val output = mutableListOf<Directory>()
fileSystem.findOver(neededSpace, output)
var smallest: Directory? = null
for (directory in output) {
if (smallest == null || directory.size < smallest.size) {
smallest = directory
}
}
return smallest!!.size.toInt()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day7/Day7_test")
val part1Result = part1(testInput)
check(part1Result == 95437) { "Expecting 95437 but got [$part1Result]." }
val part2Result = part2(testInput)
check(part2Result == 24933642) { "Expecting 24933642 but got [$part2Result]." }
val input = readInput("day7/Day7")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f41982912e3eb10b270061db1f7fe3dcc1931902 | 4,458 | kotlin-advent-of-code-2022 | Apache License 2.0 |
year2023/src/cz/veleto/aoc/year2023/Day08.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2023
import cz.veleto.aoc.core.AocDay
import cz.veleto.aoc.core.allSame
import cz.veleto.aoc.core.leastCommonMultiple
class Day08(config: Config) : AocDay(config) {
private val nodeRegex = Regex("""^(\w{3}) = \((\w{3}), (\w{3})\)$""")
override fun part1(): String {
val (instructions, nodes) = cachedInput.parse()
val startState = State(
currentNode = nodes["AAA"]!!,
stepsTaken = 0,
)
return instructions
.runningFold(startState) { state, instruction ->
State(
currentNode = state.currentNode.navigateToNextNode(nodes, instruction),
stepsTaken = state.stepsTaken + 1,
)
}
.first { it.isEndState(allZs = true) }
.stepsTaken
.toString()
}
override fun part2(): String {
val (instructions, nodes) = cachedInput.parse()
val startNodes = nodes.values.filter { it.name.endsWith('A') }.also { check(it.isNotEmpty()) }
val cycleLengths = startNodes
.map { startNode ->
val startState = State(
currentNode = startNode,
stepsTaken = 0,
)
val endStates = instructions
.runningFold(startState) { state, instruction ->
State(
currentNode = state.currentNode.navigateToNextNode(nodes, instruction),
stepsTaken = state.stepsTaken + 1,
)
}
.filter { it.isEndState(allZs = false) }
.take(10) // could be just 1 it seems, but let's check that re-visit happens every N steps
.toList()
check(endStates.map { it.currentNode }.allSame())
val firstStepsToEnd = endStates[0].stepsTaken
val cycleLengths = endStates.windowed(2, 1) { (a, b) -> b.stepsTaken - a.stepsTaken }
check(cycleLengths.all { it == firstStepsToEnd })
firstStepsToEnd
}
return leastCommonMultiple(cycleLengths).toString()
}
private fun State.isEndState(allZs: Boolean): Boolean =
if (allZs) currentNode.name == "ZZZ" else currentNode.name.endsWith('Z')
private fun Node.navigateToNextNode(nodes: Map<String, Node>, instruction: IndexedValue<Char>): Node {
val newNode = when (instruction.value) {
'L' -> left
'R' -> right
else -> error("undefined instruction $instruction")
}
return nodes[newNode]!!
}
private fun List<String>.parse(): Pair<Sequence<IndexedValue<Char>>, Map<String, Node>> {
val instructions = this[0].toList().withIndex()
val repeatingInstructions = sequence {
while (true) yieldAll(instructions)
}
val nodes = drop(2).map { it.parseNode() }.associateBy(Node::name)
return repeatingInstructions to nodes
}
private fun String.parseNode(): Node {
val (name, left, right) = nodeRegex.matchEntire(this)!!.destructured
return Node(name, left, right)
}
data class Node(
val name: String,
val left: String,
val right: String,
)
data class State(
val currentNode: Node,
val stepsTaken: Long,
)
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 3,446 | advent-of-pavel | Apache License 2.0 |
src/main/kotlin/Algorithms/MaxSubarraySum/DivideAndConquer.kt | walkmansit | 383,766,158 | false | null | package Algorithms.MaxSubarraySum
class DivideAndConquer {
companion object {
fun findMaxSubarraySum(array: IntArray): Int {
return findMaxSubarrayDiapason(array, 0, array.size - 1).third
}
private fun findMaxSubarrayDiapason(
array: IntArray,
low: Int,
high: Int
): Triple<Int, Int, Int> { //left,right,sun
if (low == high)
return Triple(low, high, array[low])
val mid = (low + high) / 2
val leftValues = findMaxSubarrayDiapason(array, low, mid)
val rightValues = findMaxSubarrayDiapason(array, mid + 1, high)
val middleValues = findMaxSubarrayCrosslines(array, low, mid, high)
return if (leftValues.third >= rightValues.third && leftValues.third >= middleValues.third)
leftValues
else if (rightValues.third >= leftValues.third && rightValues.third >= middleValues.third)
rightValues
else middleValues
}
private fun findMaxSubarrayCrosslines(
array: IntArray,
low: Int,
mid: Int,
high: Int
): Triple<Int, Int, Int> { //left,right,sun
var leftSum = Int.MIN_VALUE
var rightSum = Int.MIN_VALUE
var leftIdx = mid
var rightIdx = mid + 1
if (low == high)
return Triple(low, high, array[low])
var sum = 0
for (i in mid downTo low) {
sum += array[i]
if (sum > leftSum) {
leftIdx = i
leftSum = sum
}
}
sum = 0
for (i in mid + 1..high) {
sum += array[i]
if (sum > rightSum) {
rightIdx = i
rightSum = sum
}
}
return Triple(leftIdx, rightIdx, leftSum + rightSum)
}
}
}
| 0 | Kotlin | 0 | 1 | 2497fccef5ee2eeac08c4e7b79c9faa761736535 | 2,021 | AlgoHub | Apache License 2.0 |
src/test/kotlin/be/brammeerten/y2023/Day3Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2023
import be.brammeerten.Co
import be.brammeerten.readFile
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class Day3Test {
@Test
fun `part 1`() {
val inputLines = readFile("2023/day3/exampleInput.txt")
val lines = inputLines
.map { line ->
val numbers = mutableListOf<Pair<Int, String>>()
for (i in line.indices) {
if (line[i].isDigit()) {
if (numbers.isNotEmpty() && (numbers.last().first + numbers.last().second.length) == i) {
numbers[numbers.size-1] = numbers.last().first to numbers.last().second + line[i]
} else {
numbers.add(i to line[i] + "")
}
}
}
numbers
}
var sum = 0
for (y in lines.indices) {
for (number in lines[y]) {
var found = false
for (i in 0 until number.second.length) {
if (isSurrounded(inputLines, y, number.first+i)) {
found = true
}
}
if (found) sum += Integer.parseInt(number.second)
}
}
assertThat(sum).isEqualTo(4361);
// assertThat(sum).isEqualTo(539590);
}
@Test
fun `part 2`() {
val inputLines = readFile("2023/day3/exampleInput.txt")
val lines = inputLines
.map { line ->
val numbers = mutableListOf<Pair<Int, String>>()
for (i in line.indices) {
if (line[i].isDigit()) {
if (numbers.isNotEmpty() && (numbers.last().first + numbers.last().second.length) == i) {
numbers[numbers.size-1] = numbers.last().first to numbers.last().second + line[i]
} else {
numbers.add(i to line[i] + "")
}
}
}
numbers
}
var sum = 0
for (y in inputLines.indices) {
for (x in 0 until inputLines[y].length) {
if (inputLines[y][x] == '*') {
val nums = getNumbersSurrounding(y, x, lines)
if (nums.size == 2) {
sum += (nums[0] * nums[1])
}
}
}
}
assertThat(sum).isEqualTo(467835);
// assertThat(sum).isEqualTo(80703636);
}
private fun getNumbersSurrounding(y: Int, x: Int, lines: List<List<Pair<Int, String>>>): List<Int> {
val sum = mutableListOf<Int>()
if (y-1 >= 0) sum.addAll(getNumbersOnLineSurroundingPositionX(x, lines[y - 1]))
sum.addAll(getNumbersOnLineSurroundingPositionX(x, lines[y]))
if (y+1 < lines.size) sum.addAll(getNumbersOnLineSurroundingPositionX(x, lines[y + 1]))
return sum
}
private fun getNumbersOnLineSurroundingPositionX(x: Int, line: List<Pair<Int, String>>): List<Int> {
return line.filter {
val start = it.first
val end = it.first + it.second.length - 1
val result = (x in start..end || (x - 1) in start..end || (x + 1) in start..end)
result
}.map { Integer.parseInt(it.second) }
}
private fun isSurrounded(lines: List<String>, row: Int, col: Int): Boolean {
val cos: List<Co> = listOf(Co(-1, -1), Co.UP, Co(-1, 1), Co.LEFT, Co(0, 0), Co.RIGHT, Co(1, -1), Co.DOWN, Co(1, 1))
for (co in cos) {
val y = co.row + row
val x = co.col + col
if (y >= 0 && y < lines.size) {
if (x >= 0 && x < lines[y].length) {
val char = lines[y][x]
if (!char.isDigit() && char != '.') {
return true
}
}
}
}
return false;
}
} | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 4,080 | Advent-of-Code | MIT License |
src/day11/a/day11a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day11.a
import readInputLines
import shouldBe
fun main() {
val monkeys = readInput()
fun doMonkey(m: Monkey) {
val it = m.items.iterator()
while(it.hasNext()) {
val item = it.next(); it.remove()
m.activity++
item.level = m.operation(item.level)
item.level = item.level/3
if (item.level % m.divTest == 0) {
monkeys[m.ifTrue].items.add(item)
} else {
monkeys[m.ifFalse].items.add(item)
}
}
}
for (round in 1..20) monkeys.forEach { doMonkey(it) }
val r = monkeys.map { it.activity }.sorted().reversed()
val wl = r[0]*r[1]
shouldBe(55458, wl)
}
data class Item(
var level: Int
)
data class Monkey(
val items : ArrayList<Item>,
val operation : (Int) -> Int,
val divTest : Int,
val ifTrue : Int,
val ifFalse : Int,
) {
var activity: Int = 0
}
fun readInput(): ArrayList<Monkey> {
val r = ArrayList<Monkey>()
val it = readInputLines(11).iterator()
while (it.hasNext()) {
it.next() // skip Monkey
var s = it.next()
val items = ArrayList(s.substring(18).split(", ").map { i -> Item(i.toInt()) })
s = it.next()
val op = s.substring(23, 24)
val w = s.substring(25)
val oper: (Int, Int)->Int = when(op) {
"*" -> { a,b -> a*b }
"+" -> { a,b -> a+b }
else -> throw RuntimeException()
}
val oper2: (Int)->Int = if (w == "old")
{{old:Int->oper(old, old) }}
else
{{old:Int->oper(old, w.toInt())}}
s = it.next()
val divTest = s.substring(21).toInt()
s = it.next()
val ifTrue = s.substring(29).toInt()
s = it.next()
val ifFalse = s.substring(30).toInt()
if (it.hasNext()) it.next() // empty line
val m = Monkey(items, oper2, divTest, ifTrue, ifFalse)
r.add(m)
}
return r
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 2,004 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | fun main() {
fun part1(input: List<String>): Int {
val solution = Solution(input) { c -> c == 'S' }
return solution.getPathLength()
}
fun part2(input: List<String>): Int {
val solution = Solution(input) { c -> c == 'S' || c == 'a' }
return solution.getPathLength()
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private class Solution(
val input: List<String>,
val exitCondition: (Char) -> Boolean
) {
var result: Int = input.size * input[0].length + 1
val maxRow = input.lastIndex
val maxColumn = input[0].lastIndex
val minPathArray = Array(maxRow + 1) {
Array(maxColumn + 1) { result }
}
private fun addNextCell(coords: Coords, path: Set<Coords>) {
if (path.size > result)
return
if (minPathArray[coords.y][coords.x] <= path.size)
return
else
minPathArray[coords.y][coords.x] = path.size
var pointValue = input[coords.y][coords.x]
if (exitCondition.invoke(pointValue)) {
if (result > path.size)
result = path.size
return
}
if (pointValue == 'E')
pointValue = 'z'
NEXT_MOVE_LIST.forEach {
val newCoords = getNewCoords(coords, it)
if (newCoords.x in 0 .. maxColumn && newCoords.y in 0 .. maxRow
&& !path.contains(newCoords)
) {
var newValue = input[newCoords.y][newCoords.x]
if (newValue == 'S')
newValue = 'a'
if (pointValue <= newValue + 1)
addNextCell(newCoords, path.plus(newCoords))
}
}
}
private fun getEndCoords(): Coords {
input.forEachIndexed { index, s ->
if (s.contains("E"))
return Coords(s.indexOf('E'), index)
}
return Coords(0, 0)
}
fun getPathLength(): Int {
val startCoords = getEndCoords()
addNextCell(startCoords, setOf(startCoords))
return result - 1
}
} | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 2,237 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/nl/kelpin/fleur/advent2018/Day23.kt | fdlk | 159,925,533 | false | null | package nl.kelpin.fleur.advent2018
import arrow.syntax.function.memoize
import java.util.*
class Day23(input: List<String>) {
companion object {
val origin = Point3D(0, 0, 0)
}
data class Sphere(val pos: Point3D, val r: Int) {
companion object {
private val regex = Regex("""pos=<(-?\d+),(-?\d+),(-?\d+)>, r=(\d+)""")
fun of(input: String): Sphere {
val (x, y, z, r) = regex.matchEntire(input)!!.destructured
return Sphere(Point3D(x.toInt(), y.toInt(), z.toInt()), r.toInt())
}
}
fun contains(point: Point3D) = pos.distanceTo(point) <= r
}
private val spheres: List<Sphere> = input.map(Sphere.Companion::of)
fun part1(): Int {
val largest = spheres.maxBy { it.r }!!
return spheres.count { largest.contains(it.pos) }
}
data class Box(val xs: IntRange, val ys: IntRange, val zs: IntRange) {
fun distanceFrom(point: Point3D): Int = with(point) { xs.distance(x) + ys.distance(y) + zs.distance(z) }
fun contains(point: Point3D): Boolean = distanceFrom(point) == 0
fun overlaps(sphere: Sphere): Boolean = distanceFrom(sphere.pos) <= sphere.r
fun dimension(): Point3D = Point3D(xs.length(), ys.length(), zs.length())
fun split(): Set<Box> = xs.split().flatMap { newXs ->
ys.split().flatMap { newYs ->
zs.split().map { newZs -> Box(newXs, newYs, newZs) }
}
}.toSet()
}
val overlappingSpheres = { box: Box -> spheres.count(box::overlaps) }.memoize()
val initialBox = Box(spheres.map { it.pos.x }.range(),
spheres.map { it.pos.y }.range(),
spheres.map { it.pos.z }.range())
fun part2(): Int? {
val queue: PriorityQueue<Box> = PriorityQueue(
compareByDescending(overlappingSpheres).then(compareBy { it.distanceFrom(origin) }))
queue.add(initialBox)
while (!queue.isEmpty()) {
val box = queue.poll()
println("overlaps = ${overlappingSpheres(box)}, size = ${box.dimension()}")
if (box.dimension() == Point3D(1, 1, 1)) {
return box.distanceFrom(origin)
}
queue.addAll(box.split())
}
return null
}
} | 0 | Kotlin | 0 | 3 | a089dbae93ee520bf7a8861c9f90731eabd6eba3 | 2,310 | advent-2018 | MIT License |
src/chapter5/section3/ex20.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter5.section3
import chapter5.section1.Alphabet
import java.math.BigInteger
import java.util.*
import kotlin.collections.HashSet
/**
* 如何修改Rabin-Karp算法才能够判定k个模式(假设它们的长度全部相同)中的任意子集出现在文本之中?
* 解答:计算所有k个模式字符串的散列值并将散列值保存在一个StringSET(请见练习5.2.6)对象中。
*
* 解:散列值是Int或Long,不能保存在StringSET中,应该保存到普通SET中
* 遍历txt时,判断txt的hash值是否包含在SET中
*/
class RabinKarpSearchList(val pats: Array<String>, val alphabet: Alphabet = Alphabet.EXTENDED_ASCII) {
private val Q = longRandomPrime()
private var RM = 1L
private val hashSet = HashSet<Long>()
private val M: Int
init {
require(pats.isNotEmpty())
M = pats[0].length
pats.forEach {
check(it.length == M)
hashSet.add(hash(it, M))
}
repeat(pats[0].length - 1) {
RM = (RM * alphabet.R()) % Q
}
}
fun search(txt: String): Int {
val N = txt.length
if (M > N) return N
var txtHash = hash(txt, M)
if (hashSet.contains(txtHash) && check(txt, 0)) return 0
for (i in 0 until N - M) {
// 先计算旧hash值排除第一个元素后的hash值
txtHash = (txtHash + Q - RM * alphabet.toIndex(txt[i]) % Q) % Q
// 再添加新元素重新计算hash值
txtHash = (txtHash * alphabet.R() + alphabet.toIndex(txt[i + M])) % Q
if (hashSet.contains(txtHash) && check(txt, i + 1)) {
return i + 1
}
}
return N
}
private fun check(txt: String, i: Int): Boolean {
return true
}
/**
* 计算key[0..M-1]的散列值
*/
private fun hash(key: String, M: Int): Long {
require(key.length >= M)
var hash = 0L
repeat(M) {
hash = (hash * alphabet.R() + alphabet.toIndex(key[it])) % Q
}
return hash
}
private fun longRandomPrime(): Long {
return BigInteger.probablePrime(31, Random()).longValueExact()
}
}
fun main() {
val array = arrayOf("ABABAB", "AAAAAA", "BBBBBB")
val search = RabinKarpSearchList(array)
check(search.search("ABABABABABAB") == 0)
check(search.search("AAAAAA") == 0)
check(search.search("AAAAAAAAAAAA") == 0)
check(search.search("BBBBBBCD") == 0)
check(search.search("AAAABABABABBBBBB") == 3)
check(search.search("AAABBBAAABBB") == 12)
check(search.search("ABABBBBBBABABAB") == 3)
check(search.search("") == 0)
println("check succeed.")
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,713 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/main/kotlin/algorithms/ArrayAlgorithms.kt | AgentKnopf | 240,955,745 | false | null | package algorithms
/**
* Sliding window problem: Two buckets, each can only hold one type of fruit, what's the most fruits we can collect.
* https://levelup.gitconnected.com/an-introduction-to-sliding-window-algorithms-5533c4fe1cc7
*/
internal fun totalFruit(tree: Array<Int>): Int {
//Find the longest contiguous sequence, note that each basket can only contain one type of fruit
//Special cases or easy cases we don't need to compute due to number of baskets/trees
val treeCount = tree.size
if (treeCount == 0) {
return 0
} else if (treeCount == 1) {
return 1
} else if (treeCount == 2) {
return 2
}
//Here we start the actual algorithm that operates on any number of trees
//We keep track of the fruit types we already collected
val maxIndex = tree.size - 1
var bucketOne = -1
var bucketTwo = -1
var maxSequenceCount = 0
var rightPointer: Int
for (leftPointer in 0..maxIndex) {
//Update the right pointer
rightPointer = leftPointer
//Check if we're done
if (maxIndex - leftPointer < maxSequenceCount) {
//We can't do better anymore, so just stop
return maxSequenceCount
}
while (rightPointer <= maxIndex) {
val fruit = tree[rightPointer]
if (canFitInBucket(fruit, bucketOne, bucketTwo)) {
//Put the fruit in either bucket
if (bucketOne == -1 || bucketOne == fruit) {
bucketOne = fruit
} else if (bucketTwo == -1 || bucketTwo == fruit) {
bucketTwo = fruit
}
} else {
//Buckets are full and we're done, clear the buckets
bucketOne = -1
bucketTwo = -1
break
}
val currentSequenceCount = rightPointer - leftPointer + 1
//Check if we have improved our sequence
if (currentSequenceCount > maxSequenceCount) {
maxSequenceCount = currentSequenceCount
}
rightPointer++
}
}
return maxSequenceCount
}
/**
* @return true if we can add this fruit type to either of our buckets; false otherwise.
* also return true, if the fruit type is already in either bucket.
*/
private fun canFitInBucket(fruit: Int, bucketOne: Int, bucketTwo: Int): Boolean {
val isInBucket = fruit == bucketOne || fruit == bucketTwo
val areBucketsFull = bucketOne != -1 && bucketTwo != -1
return isInBucket || !areBucketsFull
} | 0 | Kotlin | 1 | 0 | 5367ce67e54633e53b2b951c2534bf7b2315c2d8 | 2,575 | technical-interview | MIT License |
src/Day05.kt | allisonjoycarter | 574,207,005 | false | {"Kotlin": 22303} | import java.util.*
import kotlin.collections.ArrayList
fun main() {
fun part1(input: List<String>): String {
val stacks = input.count { it.contains("[") }
val crates = input.take(stacks)
val columns = input[stacks]
val amountOfColumns = columns.trim().split(" ").last().toInt()
val crateLists = ArrayList<Stack<String>>(amountOfColumns)
val windowSize = 4
crates.forEach { line ->
for ((column, i) in (0..line.length step windowSize).withIndex()) {
val windowEnd = if ((i + windowSize) > line.length) line.length else i + windowSize
val crate = line.substring(i, windowEnd).trim()
if (crateLists.size <= column) {
crateLists.add(Stack())
}
if (crate.isNotEmpty()) {
crateLists[column].push(crate)
}
}
}
crateLists.forEach { it.reverse() }
val instructions = input.filter { it.contains("move") }
instructions.forEach { instr ->
//move 1 from 2 to 1
val pieces = instr.split(" ")
val amount = pieces[1].toInt()
val startingCol = pieces[3].toInt() - 1
val endingCol = pieces[5].toInt() - 1
for (i in 0 until amount) {
val crate = crateLists[startingCol].pop()
crateLists[endingCol].push(crate)
}
}
var result = ""
for (i in 0 until amountOfColumns) {
result += crateLists[i].pop().replace("[", "").replace("]", "").trim()
}
return result
}
fun part2(input: List<String>): String {
val stacks = input.count { it.contains("[") }
val crates = input.take(stacks)
val columns = input[stacks]
val amountOfColumns = columns.trim().split(" ").last().toInt()
val crateLists = ArrayList<Stack<String>>(amountOfColumns)
val windowSize = 4
crates.forEach { line ->
for ((column, i) in (0..line.length step windowSize).withIndex()) {
val windowEnd = if ((i + windowSize) > line.length) line.length else i + windowSize
val crate = line.substring(i, windowEnd).trim()
if (crateLists.size <= column) {
crateLists.add(Stack())
}
if (crate.isNotEmpty()) {
crateLists[column].push(crate)
}
}
}
crateLists.forEach { it.reverse() }
val instructions = input.filter { it.contains("move") }
instructions.forEach { instr ->
//move 1 from 2 to 1
val pieces = instr.split(" ")
val amount = pieces[1].toInt()
val startingCol = pieces[3].toInt() - 1
val endingCol = pieces[5].toInt() - 1
val cratesToMove = ArrayList<String>()
for (i in 0 until amount) {
val crate = crateLists[startingCol].pop()
cratesToMove.add(crate)
}
cratesToMove.reversed().forEach { crateLists[endingCol].push(it) }
}
var result = ""
for (i in 0 until amountOfColumns) {
result += crateLists[i].pop().replace("[", "").replace("]", "").trim()
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println("Part 1:")
println(part1(input))
println("Part 2:")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 86306ee6f4e90c1cab7c2743eb437fa86d4238e5 | 3,719 | adventofcode2022 | Apache License 2.0 |
src/day11/Parser.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day11
import readInput
import java.math.BigInteger
import java.util.regex.Pattern
private val REGEX = """
^Monkey (\d+):\s+Starting items: ([0-9, ]+)\s+Operation: new = old\s([+*])\s([\w\d]+)\s+Test: divisible by (\d+)\s+If true: throw to monkey (\d+)\s+If false: throw to monkey (\d+)${'$'}
""".trimIndent()
data class Monkeys (
val monkeys: List<Monkey>
) {
val clamp = monkeys.fold (1) { acc, i -> acc * i.test.toInt () }
var round: Int = 0
private set
fun playRound (monkey: Monkey, worry: (BigInteger) -> BigInteger) {
while (monkey.items.isNotEmpty()) {
val (throwTo, bored) = monkey.inspect (worry)
monkeys[throwTo].items.add (bored.mod (clamp.toBigInteger()))
}
return
}
fun playRound (worry: (BigInteger) -> BigInteger) {
monkeys.forEach {
playRound (it, worry)
}
round ++
return
}
fun dump () {
println ("after round $round")
monkeys.forEach {
println ("m${it.index} (${it.inspections}): ${it.items}:")
}
}
companion object {
fun parse (str: String): Monkeys {
val parts = str.split ("\n\n")
val monkeys = parts.map { Monkey.parse (it) }
return Monkeys (monkeys)
}
}
}
data class Monkey (
val index: Int,
val items: MutableList<BigInteger>,
val operation: Pair<String, String>,
val test: BigInteger,
val ifTrue: Int,
val ifFalse: Int
) {
var inspections: Int = 0
fun evaluate (item: BigInteger): BigInteger {
val (op, rexpr) = operation
val rval = if (rexpr == "old") item else rexpr.toBigInteger()
return when (op) {
"+" -> item + rval
"*" -> item * rval
else -> throw Exception ("Invalid op: $op")
}
}
fun inspect (worry: (BigInteger) -> BigInteger): Pair<Int, BigInteger> {
val item = items.removeAt(0)
val inspect = evaluate (item)
val bored = worry (inspect)
val throwTo = if (bored.mod (test) == 0.toBigInteger()) ifTrue else ifFalse
inspections ++
return Pair<Int, BigInteger> (throwTo, bored)
}
companion object {
private val pattern by lazy {
Pattern.compile (REGEX)
}
fun parse (str: String): Monkey {
val match = pattern.matcher (str)
if (! match.matches()) {
throw IllegalArgumentException ("No match: $str")
}
var i = 1
val monkey = match.group (i++).toInt ()
val items = match.group (i++).split (",").map { it.trim ().toBigInteger() }.toMutableList()
val op = Pair<String, String> (match.group (i++), match.group (i++))
val test = match.group (i++).toBigInteger ()
val ifTrue = match.group (i++).toInt ()
val ifFalse = match.group (i++).toInt ()
return Monkey (monkey, items, op, test, ifTrue, ifFalse)
}
}
}
fun getMonkeys (example: Boolean): Monkeys {
val input = readInput (11, example)
return Monkeys.parse (input)
}
/**
* Test out the parser.
*/
fun main (args: Array<String>) {
Boolean.values ().forEach {
val monkeys = getMonkeys (it)
monkeys.monkeys.forEach {
println (it)
}
}
return
}
private fun Boolean.Companion.values () = listOf (true, false)
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 3,463 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/_2022/Day20.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
import java.util.*
fun main() {
fun part1(input: List<String>): Long {
val intInput = input.map { it.toLong() }
.mapIndexed { index, value ->
SortNode(index, value)
}
val arrayToSort = LinkedList<SortNode>()
arrayToSort.addAll(intInput)
for (i in intInput) {
val indexOf = arrayToSort.indexOf(i)
val newPosition = (indexOf + i.value).mod(arrayToSort.size - 1)
arrayToSort.removeAt(indexOf)
if (newPosition == 0) {
arrayToSort.add(i)
} else {
arrayToSort.add(newPosition, i)
}
}
val start = arrayToSort.indexOfFirst { it.value == 0L }
val first = (1000 + start).mod(arrayToSort.size)
val second = (2000 + start).mod(arrayToSort.size)
val third = (3000 + start).mod(arrayToSort.size)
return arrayToSort[first].value + arrayToSort[second].value + arrayToSort[third].value
}
fun part2(input: List<String>): Long {
val intInput = input.map { it.toLong() * 811589153 }
.mapIndexed { index, value ->
SortNode(index, value)
}
val arrayToSort = LinkedList<SortNode>()
arrayToSort.addAll(intInput)
repeat(10) {
for (i in intInput) {
val indexOf = arrayToSort.indexOf(i)
val newPosition = (indexOf + i.value).mod(arrayToSort.size - 1)
arrayToSort.removeAt(indexOf)
if (newPosition == 0) {
arrayToSort.add(i)
} else {
arrayToSort.add(newPosition, i)
}
}
}
val start = arrayToSort.indexOfFirst { it.value == 0L }
val first = (1000 + start).mod(arrayToSort.size)
val second = (2000 + start).mod(arrayToSort.size)
val third = (3000 + start).mod(arrayToSort.size)
return arrayToSort[first].value + arrayToSort[second].value + arrayToSort[third].value
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
data class SortNode(val id: Int, val value: Long) | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 2,411 | advent-of-code | Apache License 2.0 |
src/day2/Day02.kt | dean95 | 571,923,107 | false | {"Kotlin": 21240} | package day2
import day2.Choice.*
import readInput
private fun main() {
val myPlayCodes = mutableMapOf(
"X" to ROCK,
"Y" to PAPER,
"Z" to SCISSORS
)
val opponentPlayCodes = mutableMapOf(
"A" to ROCK,
"B" to PAPER,
"C" to SCISSORS
)
val choiceToDefeat = mutableMapOf(
ROCK to SCISSORS,
SCISSORS to PAPER,
PAPER to ROCK
)
fun part1(input: List<String>): Int {
var totalScore = 0
input.forEach {
val (opponentPlayCode, myPlayCode) = it.split(" ")
val opponentPlay = opponentPlayCodes.getValue(opponentPlayCode)
val myPlay = myPlayCodes.getValue(myPlayCode)
totalScore += myPlay.score
if (myPlay == opponentPlay) {
totalScore += 3
} else if (choiceToDefeat.getValue(myPlay) == opponentPlay) {
totalScore += 6
}
}
return totalScore
}
fun part2(input: List<String>): Int {
val defeatToChoice = mutableMapOf(
SCISSORS to ROCK,
PAPER to SCISSORS,
ROCK to PAPER
)
var totalScore = 0
input.forEach {
val (opponentPlayCode, myPlayCode) = it.split(" ")
val opponentPlay = opponentPlayCodes.getValue(opponentPlayCode)
val myPlay = when (myPlayCode) {
"X" -> choiceToDefeat.getValue(opponentPlay)
"Y" -> {
totalScore += 3
opponentPlay
}
"Z" -> {
totalScore += 6
defeatToChoice.getValue(opponentPlay)
}
else -> throw IllegalStateException()
}
totalScore += myPlay.score
}
return totalScore
}
val testInput = readInput("day2/Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("day2/Day02")
println(part1(input))
println(part2(input))
}
enum class Choice(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3)
} | 0 | Kotlin | 0 | 0 | 0ddf1bdaf9bcbb45116c70d7328b606c2a75e5a5 | 2,153 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day15.kt | cbrentharris | 712,962,396 | false | {"Kotlin": 171464} | import kotlin.String
import kotlin.collections.List
object Day15 {
fun part1(input: List<String>): String {
val steps = input[0].split(",").map { it.trim() }
return steps.sumOf { hash(it) }.toString()
}
private fun hash(it: String): Int {
return it.toCharArray().fold(0) { acc, c -> ((acc + c.code) * 17) % 256 }
}
fun part2(input: List<String>): String {
val steps = input[0].split(",").map { it.trim() }
val boxes = mutableMapOf<Int, LinkedHashMap<String, Int>>()
steps.forEach {
if (it.contains("-")) {
val label = it.substring(0, it.length - 1)
val box = hash(label)
boxes.getOrPut(box) { linkedMapOf() }.remove(label)
} else {
val (label, focusLength) = it.split("=")
val box = hash(label)
boxes.getOrPut(box) { linkedMapOf() }[label] = focusLength.toInt()
}
}
return boxes.toList().sumOf { (boxNumber, lenses) ->
lenses.values.withIndex().sumOf { (idx, value) ->
(idx + 1) * value * (boxNumber + 1)
}
}.toString()
}
}
| 0 | Kotlin | 0 | 1 | f689f8bbbf1a63fecf66e5e03b382becac5d0025 | 1,196 | kotlin-kringle | Apache License 2.0 |
src/UsefulStuff.kt | lucsrathbun | 574,590,457 | false | null | fun main() {
val input = readInput("sentences")
//println("Sum: ${sumAllNums(input)}")
//println("Min: ${findMin(input)}")
println("Count: ${countHWords(input)}")
}
fun sumAllNums(input: List<String>) : Int {
var total = 0
for(num in input) {
total += num.toInt()
}
return total
}
fun findMin(input: List<String>): Int {
return input.map { it.toInt() }.min()
}
fun findTwoSmallest(input: List<String>): Int {
val sorted=input.map {it.toInt()}.sorted()
println(sorted.take(2))
return sorted[0] + sorted[1]
}
fun countWords(input: List<String>): Int{
var count = 0
for (line in input) {
val words = line.split(" ")
count += words.size
}
return count
}
fun countHWords(input: List<String>): Int {
var count = 0
for (line in input) {
val words = line.split(" ")
for (i in words.indices) {
if(words[i].lowercase().startsWith("h")) {
count++
}
}
}
return count
} | 0 | Kotlin | 0 | 0 | 3b0ec8488f54ee219bd3de8b1b2aa4f4187f03b0 | 1,028 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day10.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2021
import se.saidaspen.aoc.util.*
fun main() = Day10.run()
object Day10 : Day(2021, 10) {
private var chunkDelims = mapOf('(' to ')', '{' to '}', '[' to ']', '<' to '>')
private var scoreErrorChar = mapOf(')' to 3, '}' to 1197, ']' to 57, '>' to 25137)
private var scoreClosings = mapOf(')' to 1, '}' to 3, ']' to 2, '>' to 4)
override fun part1() = input.lines().map { check(it) }.sumOf { scoreErrorChar.getOrDefault(it.first, 0) }
override fun part2(): Any {
val sortedScores = input.lines()
.map { check(it) }
.filter { it.first == null }
.map { scoreOfEnding(it.second) }
.sortedDescending()
return sortedScores[sortedScores.size/2]
}
private fun check(s: String): P<Char?, List<Char>> {
val chunkOrder = mutableListOf<Char>()
for (c in s.toCharArray().toList()) {
if (chunkDelims.keys.contains(c)) {
chunkOrder.add(c)
} else {
val lastChunkOpen = chunkOrder.removeLast()
if (c != chunkDelims[lastChunkOpen]) {
return P(c, chunkOrder.map { chunkDelims[it]!! }.reversed())
}
}
}
return P(null, chunkOrder.map { chunkDelims[it]!! }.reversed())
}
private fun scoreOfEnding(delims: List<Char>) = delims.fold(0L) { acc, e -> acc * 5 + scoreClosings.getOrDefault(e, 0) }
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,474 | adventofkotlin | MIT License |
year2022/src/cz/veleto/aoc/year2022/Day25.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2022
import cz.veleto.aoc.core.AocDay
import kotlin.math.abs
class Day25(config: Config) : AocDay(config) {
private val snafus = listOf(-2, -1, 0, 1, 2)
private val maxSnafuOrder = 27 // so 2*5^maxSnafuOrder < Long.MAX_VALUE
private val snafuPowers: List<Long> = (0..maxSnafuOrder).map { 5.pow(it) }
private val snafuPowerSums: List<Long> = snafuPowers
.runningFold(0L) { acc, power -> acc + power * 2 }
.drop(1)
override fun part1(): String = input
.map(::snafuToDec)
.sum()
.let(::decToSnafu)
override fun part2(): String = ""
private fun snafuToDec(snafu: String): Long = snafu.toList().asReversed()
.map { c ->
when (c) {
'=' -> -2
'-' -> -1
else -> c.digitToInt().also { check(it in 0..2) }
}
}
.mapIndexed { index, snafuDigit -> snafuPowers[index] * snafuDigit }
.sum()
private fun decToSnafu(dec: Long): String = buildString {
val maxOrder = snafuPowerSums.indexOfFirst { dec in -it..it }
var remainingDec = dec
for (order in maxOrder downTo 0) {
val (snafuDigit, newRemainingDec) = snafus
.map { it to remainingDec - snafuPowers[order] * it }
.minBy { (_, newRemainingDec) -> abs(newRemainingDec) }
val snafuChar = when (snafuDigit) {
-2 -> '='
-1 -> '-'
else -> snafuDigit.digitToChar()
}
append(snafuChar)
remainingDec = newRemainingDec
}
}
private fun Int.pow(exp: Int): Long = (0 until exp)
.also { check(exp in 0..maxSnafuOrder) }
.fold(1L) { acc, _ -> acc * this }
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 1,787 | advent-of-pavel | Apache License 2.0 |
src/Day04.kt | Vlisie | 572,110,977 | false | {"Kotlin": 31465} | import java.io.File
fun main() {
fun intRangeFromDashString(s: String): IntRange {
return IntRange(s.split("-".toRegex())[0].toInt(), s.split("-".toRegex())[1].toInt())
}
fun compareCompleteOverlapRanges(s: String, s1: String): Int {
val range1 = intRangeFromDashString(s)
val range2 = intRangeFromDashString(s1)
if (range1.first >= range2.first && range1.last <= range2.last) {
return 1
}
if (range2.first >= range1.first && range2.last <= range1.last) {
return 1
}
return 0
}
fun compareOverlapRanges(s: String, s1: String): Int {
val range1 = intRangeFromDashString(s)
val range2 = intRangeFromDashString(s1)
for (nummer in range1) {
if (range2.contains(nummer)) {
return 1
}
}
return 0
}
fun part1(file: File): Int = file
.readText()
.trimEnd()
.split("\n".toRegex())
.map {
it.split(",".toRegex()).toTypedArray()
}
.map {
compareCompleteOverlapRanges(it[0], it[1])
}
.sum()
fun part2(file: File): Int = file
.readText()
.trimEnd()
.split("\n".toRegex())
.map {
it.split(",".toRegex()).toTypedArray()
}
.map {
compareOverlapRanges(it[0], it[1])
}
.sum()
// test if implementation meets criteria from the description, like:
val testInput = File("src/input", "testInput.txt")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = File("src/input", "input4.txt")
println(part1(input))
println("Part 2 -----------")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b5de21ed7ab063067703e4adebac9c98920dd51e | 1,774 | AoC2022 | Apache License 2.0 |
day3/src/main/kotlin/com/lillicoder/adventofcode2023/day3/Day3.kt | lillicoder | 731,776,788 | false | {"Kotlin": 98872} | package com.lillicoder.adventofcode2023.day3
import com.lillicoder.adventofcode2023.grids.Grid
import com.lillicoder.adventofcode2023.grids.GridParser
import com.lillicoder.adventofcode2023.grids.Node
fun main() {
val day3 = Day3()
val schematic = EngineSchematicParser().parse("input.txt")
println("The sum of all part numbers in the schematic is ${day3.part1(schematic)}.")
println("The sum of all gear ratios in the schematic is ${day3.part2(schematic)}.")
}
class Day3 {
/**
* Sums the valid part numbers from the given [Schematic].
* @param schematic Schematic to evaluate.
* @return Sum of valid part numbers.
*/
fun part1(schematic: Schematic) =
schematic.numbers.sumOf { number ->
when (schematic.isAnyNodeNeighborToNonPeriodNonNumericSymbol(number)) {
true -> {
number.toInt()
}
false -> 0
}
}
fun part2(schematic: Schematic) = GearRatiosCalculator().sum(schematic)
}
/**
* Represents a gear in an engine [Schematic].
* @param node Gear [Node].
* @param neighbors Part numbers neighboring this gear in a schematic.
* @param ratio Gear ratio.
*/
data class Gear(
val node: Node<String>,
val neighbors: List<Int>,
val ratio: Int = neighbors.reduce { accumulator, element -> accumulator * element },
)
/**
* Represents an engine schematic.
* @param grid Grid of all [Node] in this schematic.
* @param numbers List of all number node sets in this schematic.
*/
data class Schematic(
val grid: Grid<String>,
val numbers: List<List<Node<String>>>,
) {
/**
* Determines if any [Node] neighboring one or more of the given nodes is a non-period,
* non-numeric symbol.
* @param nodes Nodes to check.
* @return True if any of the given nodes is neighbor to a non-period, non-numeric symbol, false otherwise.
*/
fun isAnyNodeNeighborToNonPeriodNonNumericSymbol(nodes: List<Node<String>>): Boolean {
nodes.forEach { node ->
val neighbors = grid.neighbors(node)
if (
neighbors.any {
it.value != "." && it.value.toIntOrNull() == null
}
) {
return true
}
}
return false
}
}
/**
* Converts this list of [Node] into a single number whose digits consist of each node's value.
* @return Node values as a single number.
*/
fun List<Node<String>>.toInt() = joinToString("") { it.value }.toInt()
/**
* Parses a raw engine schematic into a [Schematic].
*/
class EngineSchematicParser(
private val gridParser: GridParser = GridParser(),
) {
/**
* Parses the file with the given filename and returns a [Schematic].
* @param filename Name of the file to parse.
* @return Engine schematic.
*/
fun parse(filename: String) = parse(javaClass.classLoader.getResourceAsStream(filename)!!.reader().readLines())
/**
* Parses the given raw schematic to an equivalent [Schematic].
* @params raw Raw input.
* @return Engine schematic.
*/
fun parse(raw: List<String>): Schematic {
val grid = gridParser.parseGrid(raw.joinToString(System.lineSeparator()))
val numbers = mutableListOf<List<Node<String>>>()
val numberBuffer = mutableListOf<Node<String>>()
grid.forEach { node ->
when (node.value.toIntOrNull() != null) {
true -> numberBuffer.add(node) // Found a number, accumulate
false -> {
if (numberBuffer.isNotEmpty()) {
// No longer on a number, flush accumulator
numbers.add(numberBuffer.toList())
numberBuffer.clear()
}
}
}
}
return Schematic(grid, numbers)
}
}
/**
* Calculator that sums the gear ratios of all gears from a [Schematic].
*/
class GearRatiosCalculator {
/**
* Sums the gear ratios of all gears in the given [Schematic].
* @param schematic Schematic to evaluate.
* @return Sum of gear ratios.
*/
fun sum(schematic: Schematic) = findGears(schematic).sumOf { it.ratio }
/**
* Finds the list of [Gear] in the given [Schematic].
* @param schematic Schematic to evaluate.
* @return Gears.
*/
private fun findGears(schematic: Schematic): List<Gear> {
// Since gears depend on all neighbor nodes, I can't preprocess this in the parser unless I do
// a second loop through all the nodes; since there's no gain efficiency-wise, and I'm not reusing this
// code for another purpose, I'm just going to walk the data structure here
val ratios = mutableListOf<Gear>()
schematic.grid.forEach { node ->
if (node.value == "*") {
// Potential gear, check conditions:
// * At least two neighbors are numeric
// * Neighbors belong to exactly two distinct part numbers
val neighbors = schematic.grid.neighbors(node).filter { it.value.toIntOrNull() != null }
if (neighbors.size > 1) {
val partNumbers =
neighbors.mapNotNull { neighbor ->
schematic.numbers.find { it.contains(neighbor) }?.toInt()
}.toSet()
if (partNumbers.size == 2) {
ratios.add(Gear(node, partNumbers.toList()))
}
}
}
}
return ratios
}
}
| 0 | Kotlin | 0 | 0 | 390f804a3da7e9d2e5747ef29299a6ad42c8d877 | 5,654 | advent-of-code-2023 | Apache License 2.0 |
2020/src/year2020/day04/Day04.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2020.day04
import util.readAllLines
import java.util.regex.Pattern
private data class Passport(
val byr: String?,
val iyr: String?,
val eyr: String?,
val hgt: String?,
val hcl: String?,
val ecl: String?,
val pid: String?,
val cid: String?) {
constructor(map: Map<String, String>) :
this(
map["byr"],
map["iyr"],
map["eyr"],
map["hgt"],
map["hcl"],
map["ecl"],
map["pid"],
map["cid"]
)
val isValidFast: Boolean
get() =
!byr.isNullOrBlank()
&& !iyr.isNullOrBlank()
&& !eyr.isNullOrBlank()
&& !hgt.isNullOrBlank()
&& !hcl.isNullOrBlank()
&& !ecl.isNullOrBlank()
&& !pid.isNullOrBlank()
val isValidHeight = when (hgt) {
null -> false
else -> if (hgt.endsWith("cm")) {
hgt.substringBefore("cm").toIntOrNull()?.let { it in 150..193 } ?: false
} else if (hgt.endsWith("in")) {
hgt.substringBefore("in").toIntOrNull()?.let { it in 59..76 } ?: false
} else {
false
}
}
val pattern: Pattern = Pattern.compile("#[0-9a-f]{6}")
val isValid: Boolean
get() =
isValidFast
&& byr?.toIntOrNull()?.let { it in 1920..2002 } ?: false
&& iyr?.toIntOrNull()?.let { it in 2010..2020 } ?: false
&& eyr?.toIntOrNull()?.let { it in 2020..2030 } ?: false
&& isValidHeight
&& checkNotNull(hcl).let { pattern.matcher(it).matches() }
&& checkNotNull(ecl).let { setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth").contains(it) }
&& checkNotNull(pid).let { it.length == 9 && it.toIntOrNull() != null }
}
private fun findValidPassportsFast(filename: String): Int {
return readPassports(filename).count { it.isValidFast }
}
private fun findValidPassports(filename: String): Int {
return readPassports(filename).count { it.isValid }
}
private fun readPassports(filename: String): MutableList<Passport> {
val input = readAllLines(filename)
val list = mutableListOf<Passport>()
val currentMap = mutableMapOf<String, String>()
input.forEach { line ->
if (line.isBlank()) {
list.add(Passport(currentMap))
currentMap.clear()
} else {
line.split(" ", "\t").forEach { part ->
part.split(":").let {
currentMap[it[0]] = it[1]
}
}
}
}
if (currentMap.isNotEmpty()) {
list.add(Passport(currentMap))
}
return list
}
fun main() {
val validFast = findValidPassportsFast("input.txt")
println(validFast)
val invalid = findValidPassports("test-invalid.txt")
println(invalid)
val validtest = findValidPassports("test-valid.txt")
println(validtest)
val valid = findValidPassports("input.txt")
println(valid)
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 3,081 | adventofcode | MIT License |
src/main/kotlin/day9/Day9.kt | afTrolle | 572,960,379 | false | {"Kotlin": 33530} | package day9
import Day
fun main() {
Day9("Day09").apply {
println(part1(parsedInput))
println(part2(parsedInput))
}
}
data class Point(
var height: Int = 0,
var width: Int = 0
)
class Day9(input: String) : Day<List<Char>>(input) {
override fun parseInput() = inputByLines.map {
val (a, b) = it.split(" ")
a.first() to b.toInt()
}.flatMap { (direction, step) ->
List(step) { direction }
}
fun MutableMap<Pair<Int, Int>, Boolean>.setVisited(point: Point) {
this[point.height to point.width] = true
}
fun Point.isTouching(head: Point): Boolean =
head.height in (height - 1)..(height + 1) && head.width in (width - 1)..(width + 1)
fun Point.updateTail(head: Point) {
if (!isTouching(head)) {
height += (head.height - height).coerceIn(-1..1)
width += (head.width - width).coerceIn(-1..1)
}
}
fun Point.updateHead(input: List<Char>, updateTails: (head: Point) -> Unit) {
input.forEach {
when (it) {
'U' -> height += 1
'D' -> height -= 1
'L' -> width -= 1
'R' -> width += 1
else -> error("invalid dir")
}
updateTails(this)
}
}
override fun part1(input: List<Char>): Any {
val visitedMap: MutableMap<Pair<Int, Int>, Boolean> = mutableMapOf()
val head = Point()
val tail = Point()
visitedMap.setVisited(head)
head.updateHead(input) { currentHead ->
tail.updateTail(currentHead)
visitedMap.setVisited(tail)
}
return visitedMap.count { it.value }
}
override fun part2(input: List<Char>): Any {
val visitedMap: MutableMap<Pair<Int, Int>, Boolean> = mutableMapOf()
val head = Point()
visitedMap.setVisited(head)
val tails = List(9) { Point() }
head.updateHead(input) { currentHead ->
tails.fold(currentHead) { prev, tail ->
tail.updateTail(prev)
tail
}
visitedMap.setVisited(tails.last())
}
return visitedMap.count { it.value }
}
}
| 0 | Kotlin | 0 | 0 | 4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545 | 2,240 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2018/Day15BeverageBandits.kt | n81ur3 | 484,801,748 | false | {"Kotlin": 476844, "Java": 275} | package adventofcode2018
class Day15BeverageBandits
sealed class Token(val sign: Char, var posX: Int, var posY: Int) : Comparable<Token> {
open fun nextEnemy(): Token = NullToken()
override fun toString(): String = sign.toString()
override fun compareTo(other: Token): Int {
return when {
posY < other.posY -> -1
posY > other.posY -> 1
posX < other.posX -> -1
posX > other.posX -> 1
else -> 0
}
}
fun adjacentCoordinates(): List<Pair<Int, Int>> {
return listOf(posX to posY - 1, posX + 1 to posY, posX to posY + 1, posX - 1 to posY)
}
companion object {
fun fromChar(c: Char, posX: Int, posY: Int): Token {
return when (c) {
'#' -> Wall(posX, posY)
'.' -> Cavern(posX, posY)
'G' -> Goblin(posX, posY)
'E' -> Elf(posX, posY)
else -> NullToken()
}
}
}
}
class Wall(posX: Int, posY: Int) : Token('#', posX, posY)
class Cavern(posX: Int, posY: Int) : Token('.', posX, posY)
class Goblin(posX: Int, posY: Int) : Token('G', posX, posY)
class Elf(posX: Int, posY: Int) : Token('E', posX, posY)
class NullToken : Token(' ', -1, -1)
class Cave(input: List<String>) {
val caveMap: List<Token>
val caveWidth = input[0].length
val caveHeight = input.size
val sortedFighters: List<Token>
get() = caveMap.sorted().filter { it is Goblin || it is Elf }
init {
caveMap = input.flatMapIndexed { posY, line ->
line.mapIndexed { posX, token ->
Token.fromChar(token, posX, posY)
}
}
}
fun playRound() {
sortedFighters.forEach { fighter ->
val caverns = getAdjacentCaverns(fighter)
val enemies = findEnemies(fighter)
val targets = findTargets(fighter)
println(caverns)
}
}
private fun getAdjacentCaverns(token: Token): List<Token> {
return caveMap.filter { it is Cavern }.filter { it.posX to it.posY in token.adjacentCoordinates() }
}
private fun findEnemies(token: Token): List<Token> {
return when (token) {
is Goblin -> caveMap.filter { it is Elf }
is Elf -> caveMap.filter{ it is Goblin }
else -> emptyList()
}
}
private fun findTargets(token: Token): List<Token> {
val enemies = findEnemies(token)
return enemies.flatMap { getAdjacentCaverns(it) }
}
fun printCaveMap() {
caveMap.sorted().forEachIndexed { index, token ->
if (index % caveWidth == 0) { println() }
print(token)
}
println()
}
} | 0 | Kotlin | 0 | 0 | fdc59410c717ac4876d53d8688d03b9b044c1b7e | 2,743 | kotlin-coding-challenges | MIT License |
src/main/kotlin/io/dmitrijs/aoc2022/Day13.kt | lakiboy | 578,268,213 | false | {"Kotlin": 76651} | package io.dmitrijs.aoc2022
class Day13(private val input: String) {
fun puzzle1() = input
.split("\n\n")
.map { it.toPairs() }
.foldIndexed(0) { index, acc, (left, right) ->
(if (left < right) (index + 1) else 0) + acc
}
fun puzzle2(): Int {
val dividers: Pair<Packet, Packet>
return "[[2]]\n[[6]]\n\n$input"
.lines()
.filter { it.isNotEmpty() }
.map { Packet.of(it) }
.also { packets -> dividers = packets[0] to packets[1] }
.sorted()
.let { (it.indexOf(dividers.first) + 1) * (it.indexOf(dividers.second) + 1) }
}
private fun String.toPairs() = Pair(
Packet.of(substringBefore("\n").trim()),
Packet.of(substringAfter("\n").trim()),
)
private sealed class Packet : Comparable<Packet> {
companion object {
fun of(line: String) = if ('[' in line) Items.fromString(line) else Number.fromString(line)
}
class Number(private val value: Int) : Packet() {
override operator fun compareTo(other: Packet) = when (other) {
is Number -> value - other.value
is Items -> asItems().compareTo(other)
}
fun asItems() = Items(listOf(this))
companion object {
fun fromString(s: String) = Number(s.toInt())
}
}
class Items(private val items: List<Packet>) : Packet() {
override operator fun compareTo(other: Packet): Int = when (other) {
is Number -> compareTo(other.asItems())
is Items -> items.zip(other.items)
.firstNotNullOfOrNull { (left, right) -> left.compareTo(right).takeUnless { it == 0 } }
?: (items.size - other.items.size)
}
companion object {
fun fromString(s: String): Items {
val stack = ArrayDeque<Char>()
var level = 0
val items = mutableListOf<Packet>()
s.removePrefix("[").removeSuffix("]").forEach { char ->
when (char) {
'[' -> level++
']' -> level--
}
stack.add(char)
if (char == ',' && level == 0) {
stack.removeLast()
items.add(of(stack.joinToString("")))
stack.clear()
}
}
if (stack.isNotEmpty()) {
items.add(of(stack.joinToString("")))
}
return Items(items)
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | bfce0f4cb924834d44b3aae14686d1c834621456 | 2,833 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/OnesAndZeroes.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.extensions.countZeroesOnes
import kotlin.math.max
/**
* Ones and Zeroes
* @see <a href="https://leetcode.com/problems/ones-and-zeroes">Source</a>
*/
fun interface OnesAndZeroes {
fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int
}
/**
* Approach #1 Brute Force [Time Limit Exceeded]
* Time complexity : O(2 ^ l * x). 2^l possible subsets,
* where l is the length of the list strs and x is the average string length.
* Space complexity : O(1). Constant Space required.
*/
class OnesAndZeroesBF : OnesAndZeroes {
override fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
var maxlen = 0
for (i in 0 until (1 shl strs.size)) {
var zeroes = 0
var ones = 0
var len = 0
for (j in strs.indices) {
if (i and (1 shl j) != 0) {
val count: IntArray = strs[j].countZeroesOnes()
zeroes += count[0]
ones += count[1]
len++
}
}
if (zeroes <= m && ones <= n) maxlen = max(maxlen, len)
}
return maxlen
}
}
/**
* Approach #2 Better Brute Force [Time Limit Exceeded]
* Time complexity : O(2 ^ l * x). 2^l possible subsets,
* where l is the length of the list strs and x is the average string length.
* Space complexity : O(1). Constant Space required.
*/
class OnesAndZeroesBetterBF : OnesAndZeroes {
override fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
var maxlen = 0
for (i in 0 until (1 shl strs.size)) {
var zeroes = 0
var ones = 0
var len = 0
for (j in 0 until INT_32_BITS_COUNT) {
if (i and (1 shl j) != 0) {
val count: IntArray = strs[j].countZeroesOnes()
zeroes += count[0]
ones += count[1]
if (zeroes > m || ones > n) break
len++
}
}
if (zeroes <= m && ones <= n) maxlen = max(maxlen, len)
}
return maxlen
}
companion object {
private const val INT_32_BITS_COUNT = 32
}
}
/**
* Approach #3 Using Recursion [Time Limit Exceeded]
* Time complexity : O(2 ^ l * x). 2^l possible subsets,
* where l is the length of the list strs and x is the average string length.
* Space complexity : O(l). Depth of recursion tree grows up to l.
*/
class OnesAndZeroesRecursion : OnesAndZeroes {
override fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
return calculate(strs, 0, m, n)
}
fun calculate(strs: Array<String>, i: Int, zeroes: Int, ones: Int): Int {
if (i == strs.size) return 0
val count: IntArray = strs[i].countZeroesOnes()
var taken = -1
if (zeroes - count[0] >= 0 && ones - count[1] >= 0) {
taken = calculate(strs, i + 1, zeroes - count[0], ones - count[1]) + 1
}
val notTaken = calculate(strs, i + 1, zeroes, ones)
return max(taken, notTaken)
}
}
/**
* Approach #4 Using Memoization
* Time complexity : O(l*m*n). memo array of size l*m*n is filled, where ll is the length of strs,
* mm and nn are the number of zeroes and ones respectively.
* Space complexity : O(l*m*n). 3D array memo is used.
*/
class OnesAndZeroesMemoization : OnesAndZeroes {
override fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
val memo: Array<Array<IntArray>> = Array(strs.size) {
Array(m + 1) {
IntArray(n + 1)
}
}
return calculate(strs, 0, m, n, memo)
}
private fun calculate(strs: Array<String>, i: Int, zeroes: Int, ones: Int, memo: Array<Array<IntArray>>): Int {
if (i == strs.size) {
return 0
}
if (memo[i][zeroes][ones] != 0) {
return memo[i][zeroes][ones]
}
val count: IntArray = strs[i].countZeroesOnes()
var taken = -1
if (zeroes - count[0] >= 0 && ones - count[1] >= 0) {
taken = calculate(strs, i + 1, zeroes - count[0], ones - count[1], memo) + 1
}
val notTaken = calculate(strs, i + 1, zeroes, ones, memo)
memo[i][zeroes][ones] = max(taken, notTaken)
return memo[i][zeroes][ones]
}
}
/**
* Approach #5 Dynamic Programming
* Time complexity : O(l*m*n). Three nested loops are their,
* where ll is the length of strs, m and n are the number of zeroes and ones respectively.
* Space complexity : O(m*n). dp array of size m*n is used.
*/
class OnesAndZeroesDP : OnesAndZeroes {
override fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
val dp = Array(m + 1) { IntArray(n + 1) }
for (s in strs) {
val count: IntArray = s.countZeroesOnes()
for (zeroes in m downTo count[0]) for (ones in n downTo count[1]) dp[zeroes][ones] = max(
1 + dp[zeroes - count[0]][ones - count[1]],
dp[zeroes][ones],
)
}
return dp[m][n]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,758 | kotlab | Apache License 2.0 |
2020/day16/day16.kt | flwyd | 426,866,266 | false | {"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398} | /*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package day16
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
import kotlin.time.measureTimedValue
/* Input: three sections, the first is "field name: #-# or #-#", second starts with "your tickets:"
and is comma-delimited ints, third starts with "nearby tickets:" and is several lines of
comma-delimited ints. Fields are disjoint ranges of valid values. */
class DisjointIntRange(private val ranges: List<IntRange>) {
companion object {
fun parse(ranges: String): DisjointIntRange = DisjointIntRange(
ranges.split(" or ")
.map { it.split("-").let { (lo, hi) -> lo.toInt()..hi.toInt() } }
)
}
operator fun contains(value: Int) = ranges.any { it.contains(value) }
override fun toString(): String = ranges.joinToString(" or ")
}
/* Output: the product of all "nearby tickets" values that don't match any range. */
object Part1 {
fun solve(input: Sequence<String>): String {
val fields = mutableMapOf<String, DisjointIntRange>()
val invalidValues = mutableListOf<Int>()
var section = "fields"
for (line in input.filterNot(String::isBlank)) {
if (line.contains(':')) {
val (prefix, value) = line.split(':')
when (prefix) {
"your ticket" -> section = "your"
"nearby tickets" -> section = "nearby"
else -> fields[prefix] = DisjointIntRange.parse(value.trim())
}
} else when (section) {
"nearby" -> invalidValues.addAll(
line.split(',').map(String::toInt).filter { value -> fields.values.none { value in it } }
)
}
}
return invalidValues.sum().toString()
}
}
/* Throw out all rows with invalid values, then determine the field position for each field.
Output: product of the "your tickets" values for fields that start with "departure". */
object Part2 {
fun solve(input: Sequence<String>): String {
val fields = mutableMapOf<String, DisjointIntRange>()
val possiblePositions = mutableMapOf<String, MutableSet<Int>>()
var yourTicket = listOf<Int>()
var section = "fields"
for (line in input.filterNot(String::isBlank)) {
if (line.contains(':')) {
val (prefix, value) = line.split(':')
when (prefix) {
"your ticket" -> section = "your"
"nearby tickets" -> {
section = "nearby"
fields.keys.forEach { possiblePositions[it] = (0 until fields.size).toHashSet() }
}
else -> fields[prefix] = DisjointIntRange.parse(value.trim())
}
} else when (section) {
"your" -> yourTicket = line.split(',').map(String::toInt).toList()
"nearby" -> {
val values = line.split(',').map(String::toInt).toList()
if (values.any { v -> fields.values.none { r -> v in r } }) {
continue // invalid row
}
for ((i, value) in values.withIndex()) {
for ((field, range) in fields) {
if (value !in range) {
possiblePositions.getValue(field).remove(i)
}
}
}
}
}
}
fields.keys.sortedBy { possiblePositions.getValue(it).size }.forEach { field ->
val possible = possiblePositions.getValue(field)
if (possible.size == 1) {
val theOne = possible.first()
if (yourTicket[theOne] !in fields.getValue(field)) {
error("Impossible value ${yourTicket[theOne]} for $field in $possible")
}
possiblePositions.filterKeys { it != field }.values.forEach { it.remove(theOne) }
} else {
error("Multiple possible values $possible for $field")
}
}
// for actual input, only fields starting with "departure" matter, but example inputs
// don't have any departure fields.
val filtered =
possiblePositions.filterKeys { it.startsWith("departure") }.ifEmpty { possiblePositions }
return filtered
.values.map(Set<Int>::first)
.map(yourTicket::get)
.map(Int::toLong)
.reduce(Long::times).toString()
}
}
@ExperimentalTime
@Suppress("UNUSED_PARAMETER")
fun main(args: Array<String>) {
val lines = generateSequence(::readLine).toList()
print("part1: ")
TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
print("part2: ")
TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
}
| 0 | Julia | 1 | 5 | f2d6dbb67d41f8f2898dbbc6a98477d05473888f | 4,725 | adventofcode | MIT License |
src/main/kotlin/dev/bogwalk/batch7/Problem79.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch7
/**
* Problem 79: Passcode Derivation
*
* https://projecteuler.net/problem=79
*
* Goal: Based on a collection of successful login attempts using 3 characters (ASCII codes [33,
* 126]) in order (but not necessarily consecutive), determine the shortest (& lexicographically
* smallest) original password of unknown length with only unique characters. If a password is
* not possible, return a null string.
*
* Constraints: 1 <= login attempts <= 3000
*
* e.g.:
* attempts = {an0, n/., .#a}
* password = <PASSWORD>
* 1st attempt shows that 'n' must follow 'a'. 2nd attempt shows '.' must follow 'n'. But
* the last attempt has 'a' after '.' which should not be possible.
*/
class PasscodeDerivation {
/**
* Solution stores all connections between each login character & characters that potentially
* precede it in the passcode, using a pseudo-graph.
*
* A stored character will be next in the passcode if it has degree 0 (i.e. no connecting
* edges), with multiple choices being judged based on their lexicographic order (as the
* cache is an array, the smallest will be the first element found that matches the predicate).
*
* Once a character is added to the passcode, its presence in the array is nullified & it is
* removed from all characters that referenced it as an edge.
*
* A passcode is considered invalid/unattainable if at any point there are no degree 0
* characters & a null value is returned.
*
* N.B. A dictionary could be used to cache all character nodes & references & would require
* dictionary keys to be sorted to find the smallest insert for every iteration.
*
* SPEED (BETTER) 3.80ms for 50-login attempts
*/
fun derivePasscodeImproved(logins: List<String>): String? {
// reduce cache size to ASCII characters between 33 and 126 inclusive
val offset = 33
val connections = Array<Set<Int>?>(127 - offset) { null }
for (login in logins) {
// normalise login character ASCII to fit in cache
val codes = login.map { it.code - offset }
for (i in 0..2) {
connections[codes[i]] = if (i == 0) {
// create a new set if a new character, otherwise preceding characters unknown
connections[codes[i]] ?: mutableSetOf()
} else {
connections[codes[i]]?.plus(codes[i-1]) ?: mutableSetOf(codes[i-1])
}
}
}
var passcode = ""
while (connections.any { it != null }) { // break loop if no more edges exist
val smallest = connections.indexOfFirst { it?.isEmpty() == true }
// break loop if no isolated characters exist
if (smallest == -1) return null
passcode += (smallest + offset).toChar()
// remove all existence of the character just added
connections[smallest] = null
for (i in 0..93) {
if (connections[i]?.contains(smallest) == true) {
connections[i] = connections[i]?.minus(smallest)
}
}
}
return passcode
}
/**
* Solution assesses each login string & places each character into a list with minimal
* movement or swapping based on the indices or pre-existing characters, if any.
*
* If characters are swapped or newly placed, the new passcode is matched with all login
* Regex objects encountered so far, until either a match is not found (null value returned) or
* all login attempts are processed (string value returned).
*
* e.g.
* "SMH" = [-1, -1, -1] -> [S, M, H]
* "TON" = [-1, -1, -1] -> [S, M, H, T, O, N]
* "RNG" = [-1, 5, -1] -> [S, M, H, T, O, R, N, G]
* "WRO" = [-1, 5, 4] !! swap required -> [S, M, H, T, R, O, N, G]
* [-1, 4, 5] -> [S, M, H, T, W, R, O, N, G]
* "THG" = [3, 2, 8] !! swap required -> [S, M, T, H, W, R, O, N, G]
* passcode = <PASSWORD>
*
* N.B. This solution uses Regex & solves the Project Euler problem easily along with more
* restricted test samples. However, this solution is not ideal for the more robust HackerRank
* problems, particularly due to the span of characters allowed, which may cause either
* dangling metacharacters or escape characters. It also does not allow for backtracking in
* the event a swap is not enough to satisfy a new login Regex, leading to occasional false
* null results.
*
* SPEED (WORSE) 13.06ms for 50-login attempts
*/
fun derivePasscode(logins: List<String>): String? {
val passcode = mutableListOf<Char>()
val patterns = mutableListOf<Regex>()
for (login in logins) {
patterns.add(createRegex(login))
var indices = login.map { passcode.indexOf(it) }
var alreadySeen = indices.filter { it != -1 }
if (alreadySeen.isEmpty()) { // all new characters added to end of list
passcode.addAll(login.toList())
continue
}
val expected = alreadySeen.sorted()
var swapped = false
if (expected != alreadySeen) { // order does not match new login attempt
if (expected.size == 2) {
val toSwap = mutableListOf<Int>()
for (i in expected.indices) {
if (expected[i] != alreadySeen[i]) toSwap.add(expected[i])
}
val (a, b) = toSwap
passcode[a] = passcode[b].also {
passcode[b] = passcode[a]
}
} else {
when (indices.indexOf(expected.first())) {
0 -> {
passcode.remove(login[1])
passcode.add(indices[2], login[1])
}
1 -> {
passcode.remove(login[0])
passcode.add(indices[1], login[0])
}
2 -> {
passcode.removeAll(login.take(2).toList())
val toAdd = expected.takeLast(2).map { login[it] }
passcode.addAll(indices[2], toAdd)
}
}
}
indices = login.map { passcode.indexOf(it) }
alreadySeen = indices.filter { it != -1 }
swapped = true
}
// login attempt fits well with current passcode
if (alreadySeen.size == 3 && !swapped) continue
if (alreadySeen.size == 2) {
when (indices.indexOf(-1)) {
0 -> passcode.add(indices[1], login[0])
1 -> passcode.add(indices[0] + 1, login[1])
2 -> {
if (indices[1] >= passcode.lastIndex) {
passcode.add(login[2])
} else {
passcode.add(indices[1] + 1, login[2])
}
}
}
}
if (alreadySeen.size == 1) {
when (indices.indexOfFirst { it != -1 }) {
0 -> {
if (indices[0] >= passcode.lastIndex) {
passcode.addAll(login.takeLast(2).toList())
} else {
passcode.addAll(indices[0] + 1, login.takeLast(2).toList())
}
}
1 -> {
if (indices[1] >= passcode.lastIndex) {
passcode.add(login[2])
} else {
passcode.add(indices[1] + 1, login[2])
}
passcode.add(indices[1], login[0])
}
2 -> passcode.addAll(indices[2], login.take(2).toList())
}
}
for (pattern in patterns) {
if (!pattern.containsMatchIn(passcode.joinToString(""))) return null
}
}
return passcode.joinToString("")
}
/**
* Returns a Regex object based on the [login] attempt that ensures metacharacters are
* escaped to allow no dangling during match checks.
*/
private fun createRegex(login: String): Regex {
var pattern = ""
for ((i, ch) in login.withIndex()) {
val next = if (ch in listOf('$', '*', '+', '.', '?', '\\')) """\$ch""" else "$ch"
pattern += if (i < 2) "$next.*" else next
}
return pattern.toRegex()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 8,961 | project-euler-kotlin | MIT License |
algorithms/src/main/kotlin/com/kotlinground/algorithms/arrays/majorityelement/majorityElement.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.algorithms.arrays.majorityelement
/**
* Finds the element that occurs more than n/2 times, where n is the size of the input list.
*
* This first sorts the list in place and finds the element at index n/2, since the majority element will always occupy
* the middle position when the array is sorted.
*
* Complexity:
* - Time Complexity O(n log(n)) since sorting an array of size n takes O(n log(n)) time
* - Space Complexity O(1) since no extra space is required
*
* @param nums [IntArray] array of integers
* @return [Int] element that occurs the most in the array
*/
fun majorityElement(nums: IntArray): Int {
nums.sort()
val n = nums.size
return nums[n / 2]
}
/**
* Finds the element that occurs more than n/2 times, where n is the size of the input list.
*
* This uses a hash map to keep track of how frequent an element occurs in the list.
* The key value pairs will be the element itself, while the value will be the count/occurrences in the hash map.
*
* Complexity:
* - Time Complexity O(n):
* Since iteration is done through the array once to count the occurrences and then iterates through the hash map,
* which has a maximum size of the number of distinct elements in the array.
* - Space Complexity O(n) since a hashmap is used to keep track of frequencies of the elements in the list.
*
* @param nums [IntArray] array of integers
* @return [Int] element that occurs the most in the array
*/
fun majorityElementWithHashMap(nums: IntArray): Int {
val map = hashMapOf<Int, Int>()
// Keep track of the count of each element from the list in the hash map
for (num in nums) {
map[num] = map[num]?.plus(1) ?: 1
}
// Update n to be n/2, where n is the size of the list.
// This is done to check if an element occurs more than n/2 times
val n = nums.size / 2
for ((key, value) in map.entries) {
if (value > n) {
return key
}
}
// If no majority element is found in the hash map, 0 is returned as the default value.
// This will only occur if the input array is empty or does not have a majority element.
return 0
}
/**
* Finds the element that occurs more than n/2 times, where n is the size of the input list.
*
* This uses Moore's Voting Algorithm based on the fact that if there is a majority element in an array, it
* will always remain in the lead, even after encountering other elements.
*
* Reference: https://en.wikipedia.org/wiki/Boyer-Moore_majority_vote_algorithm
*
* 1. The algorithm starts by assuming the first element as the majority candidate and sets the count to 1.
* 2. As it iterates through the array, it compares each element with the candidate:
* - If the current element matches the candidate, it suggests that it reinforces the majority element because it
* appears again.
* Therefore, the count is incremented by 1.
* - If the current element is different from the candidate, it suggests that there might be an equal number of
* occurrences of the majority element and other elements.
* Therefore, the count is decremented by 1.
* Note that decrementing the count doesn't change the fact that the majority element occurs more than n/2
* times.
*
* 3. If the count becomes 0, it means that the current candidate is no longer a potential majority element.
* In this
* case, a new candidate is chosen from the remaining elements.
* 4. The algorithm continues this process until it has traversed the entire array.
* 5. The final value of the candidate variable will hold the majority element.
*
* Explanation of Correctness:
* The algorithm works on the basis of the assumption that the majority element occurs more than n/2 times in the
* array.
* This assumption guarantees that even if the count is reset to 0 by other elements, the majority element will
* eventually regain the lead.
*
* Let's consider two cases:
* 1. If the majority element has more than n/2 occurrences:
* The algorithm will ensure
* that the count remains positive for the majority element throughout the traversal,
* guaranteeing that it will be selected as the final candidate.
*
* 2. If the majority element has exactly n/2 occurrences:
*
* In this case, there will be an equal number of occurrences for the majority element and the remaining elements
* combined.
* However, the majority element will still be selected as the final candidate because it will always
* have a lead over any other element.
*
* In both cases, the algorithm will correctly identify the majority element.
*
* Complexity:
* - Time Complexity O(n):
* Since iteration is done through the array once.
* - Space Complexity O(1):
* No extra space is used to perform the algorithm.
*
* @param nums [IntArray] array of integers
* @return [Int] element that occurs the most in the array
*/
fun majorityElementWithVoting(nums: IntArray): Int {
// Initialize two variables, count and candidate. Set count to 0 and candidate to an arbitrary value.
var count = 0
var candidate = 0
// Iterate through nums
for (num in nums) {
// if the count is 0, assign the current element as the new candidate and increment count by 1
if (count == 0) {
candidate = num
}
// if the current element is the same as the candidate, increment count by 1
if (num == candidate) {
count += 1
} else {
// if the current element is different, decrement count by 1
count -= 1
}
}
// After the iteration, the candidate variable will hold the majority element.
return candidate
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 5,673 | KotlinGround | MIT License |
src/main/kotlin/days/Day13.kt | andilau | 573,139,461 | false | {"Kotlin": 65955} | package days
@AdventOfCodePuzzle(
name = "Distress Signal",
url = "https://adventofcode.com/2022/day/13",
date = Date(day = 13, year = 2022)
)
class Day13(val input: List<String>) : Puzzle {
private val divider: List<String> = listOf("[[2]]", "[[6]]")
private val pairs = input
.asSequence().filter(String::isNotBlank)
.map { Packet.from(it) }
.chunked(2)
.map { it[0] to it[1] }
override fun partOne(): Int =
pairs.mapIndexed { ix, p -> (ix + 1) * if (p.first < p.second) 1 else 0 }
.sum()
override fun partTwo(): Int {
return (input + divider)
.filter(String::isNotBlank)
.map { Packet.from(it) }
.sorted()
.mapIndexed { index, packet ->
if (packet.toString() in divider) index + 1 else 1
}
.reduce { a, b -> a * b }
}
sealed class Packet : Comparable<Packet> {
class PacketNumber(val number: Int) : Packet() {
override fun compareTo(other: Packet): Int = when (other) {
is PacketNumber -> number.compareTo(other.number)
is PacketList -> PacketList(listOf(this)).compareTo(other)
}
override fun toString(): String = "$number"
}
class PacketList(val packets: List<Packet>) : Packet() {
override fun compareTo(other: Packet): Int = when (other) {
is PacketNumber -> this.compareTo(PacketList(listOf(other)))
is PacketList -> packets.zip(other.packets)
.map { (first, second) -> first.compareTo(second) }
.firstOrNull { it != 0 }
?: this.packets.size.compareTo(other.packets.size)
}
override fun toString(): String =
packets.joinToString(",", "[", "]")
}
companion object {
fun from(line: String): Packet =
Regex("""\[|]|\d+""").findAll(line).map { it.value }.toList().let { from(ArrayDeque(it)) }
private fun from(tokens: ArrayDeque<String>): Packet {
val packets = mutableListOf<Packet>()
while (tokens.isNotEmpty()) {
when (val symbol = tokens.removeFirst()) {
"]" -> return PacketList(packets)
"[" -> packets.add(from(tokens))
else -> packets.add(PacketNumber(symbol.toInt()))
}
}
return packets.first()
}
}
}
}
| 0 | Kotlin | 0 | 0 | da824f8c562d72387940844aff306b22f605db40 | 2,603 | advent-of-code-2022 | Creative Commons Zero v1.0 Universal |
src/Day04.kt | PauliusRap | 573,434,850 | false | {"Kotlin": 20299} | fun main() {
fun getAssignmentRange(assignment: String) = with(assignment.split("-")) {
this[0].toInt()..this[1].toInt()
}
fun isAnyAssignmentCovered(input: String): Boolean {
val assignments = input.split(",")
val range1 = getAssignmentRange(assignments[0]).toList()
val range2 = getAssignmentRange(assignments[1]).toList()
return range1.containsAll(range2) || range2.containsAll(range1)
}
fun isAnyAssignmentOverlapped(input: String): Boolean {
val assignments = input.split(",")
val range1 = getAssignmentRange(assignments[0])
val range2 = getAssignmentRange(assignments[1])
return range1.any { range2.contains(it) }
}
fun part1(input: List<String>) = input.count { isAnyAssignmentCovered(it) }
fun part2(input: List<String>) = input.count { isAnyAssignmentOverlapped(it) }
// test if implementation meets criteria from the description:
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 | df510c3afb104c03add6cf2597c433b34b3f7dc7 | 1,156 | advent-of-coding-2022 | Apache License 2.0 |
src/day03/Day03.kt | pientaa | 572,927,825 | false | {"Kotlin": 19922} | package day03
import readLines
fun main() {
fun findPriority(rucksack: String): Char {
val first = rucksack.substring(0, rucksack.length / 2)
val second = rucksack.substring(rucksack.length / 2)
return first.first {
second.contains(it)
}
}
fun Char.toPriority() = if (isLowerCase()) this - 'a' + 1 else this - 'A' + 27
fun part1(input: List<String>): Int =
input.sumOf {
findPriority(it)
.toPriority()
}
fun findBadge(rucksacks: List<String>): Char =
rucksacks.first()
.first { c ->
rucksacks.subList(1, 3)
.all { it.contains(c) }
}
fun part2(input: List<String>): Int =
input.windowed(3, 3)
.sumOf { findBadge(it).toPriority() }
// test if implementation meets criteria from the description, like:
val testInput = readLines("day03/Day03_test")
val input = readLines("day03/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 63094d8d1887d33b78e2dd73f917d46ca1cbaf9c | 1,060 | aoc-2022-in-kotlin | Apache License 2.0 |
kotlin/src/2022/Day24_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} |
fun main() {
val chMap = listOf('<', '^', '>', 'v').withIndex().associate {it.value to (1 shl it.index)}
val input = readInput(24).trim().lines()
val mStart = input.map {
it.map {ch -> chMap.getOrDefault(ch, 0)}
}
val (N, M) = mStart.size to mStart[0].size
// directions for each type of blizzard
val dirs = listOf(0 to -1, -1 to 0, 0 to 1, 1 to 0).withIndex().associate {(1 shl it.index) to it.value}
fun nextMap(m: List<List<Int>>) = run {
val nm = List(N) { MutableList(M) { 0 } }
for (i in m.indices)
for (j in m[0].indices)
for ((k, dir) in dirs.entries) {
// blizzard of direction `k` is not present at pos (i, j)
if (m[i][j] and k == 0) continue
var (y, x) = i + dir.first to j + dir.second
// if the blizzard reached a wall, it wraps at the other end (first and last coords are walls)
if (y == 0) y = N - 2
else if (y == N - 1) y = 1
if (x == 0) x = M - 2
else if (x == M - 1) x = 1
nm[y][x] = nm[y][x] or k
}
nm
}
val start = 0 to input[0].indexOf('.')
val target = N - 1 to input[N-1].indexOf('.')
fun neighbors(i: Int, j: Int) = listOf(i + 1 to j, i - 1 to j, i to j - 1, i to j + 1)
.filter {p ->
p == start || p == target || (p.first > 0 && p.second > 0 && p.first < N - 1 && p.second < M - 1)
}
fun simulate(phases: Int): Int {
var fields = setOf(start)
var m = mStart
var phase = 0
for (t in 1..Int.MAX_VALUE) {
m = nextMap(m)
var s = mutableSetOf<Pair<Int, Int>>()
for ((i, j) in fields) {
if (m[i][j] == 0) s.add(i to j)
for ((y, x) in neighbors(i, j))
if (m[y][x] == 0) s.add(y to x)
}
if (phase % 2 == 0 && target in s) {
s = mutableSetOf(target)
phase += 1
} else if (phase % 2 == 1 && start in s) {
s = mutableSetOf(start)
phase += 1
}
if (phase == phases) return t
fields = s
}
throw IllegalStateException()
}
// part1
println(simulate(1))
// part2
println(simulate(3))
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 2,430 | adventofcode | Apache License 2.0 |
lib/src/main/java/anatoldevelopers/by/functional/Extensions.kt | Nublo | 141,798,429 | false | null | package anatoldevelopers.by.functional
val <T> List<T>.head: T
get() = when (this.isEmpty()) {
true -> throw NoSuchElementException("List is empty.")
false -> this[0]
}
val <T> List<T>.tail: List<T>
get() = drop(1)
val List<Int>.sum: Int
get() = sum(this)
fun sum(xs: List<Int>): Int {
tailrec fun sumInner(xs: List<Int>, acum: Int): Int = when (xs.size) {
0 -> acum
else -> sumInner(xs.tail, xs.head + acum)
}
return sumInner(xs, 0)
}
fun sum2(xs: List<Int>) = reduce(0, xs) { acum, current -> acum + current }
fun <T, R> List<T>.map(f: (T) -> R): List<R> = when (this.size) {
0 -> listOf()
else -> f(head) + tail.map(f)
}
fun <T, R> List<T>.map2(f: (T) -> R): List<R> = reduce(listOf(), this)
{ xs, s -> xs + f(s) }
fun <T> List<T>.filter(f: (T) -> Boolean): List<T> = when (this.size) {
0 -> listOf()
else -> if (f(head)) head + tail.filter(f) else tail.filter(f)
}
fun <T> List<T>.filter2(f: (T) -> Boolean): List<T> = reduce(listOf(), this)
{ ys, s ->
if (f(s))
return@reduce ys + s
else
ys
}
fun <T, R> reduce(s: T, xs: List<R>, f: (T, R) -> T): T = when (xs.size) {
0 -> s
else -> reduce(f(s, xs.head), xs.tail, f)
}
operator fun <T> List<T>.plus(x: T): List<T> = ArrayList(this).also { it.add(x) }
operator fun <T> List<T>.plus(xs: List<T>): List<T> = when (xs.size) {
0 -> ArrayList(this)
else -> (this + xs.head) + xs.tail
}
operator fun <T> T.plus(xs: List<T>): List<T> = listOf(this) + xs
fun <T, R> zip(xs: List<T>, ys: List<R>): List<Pair<T, R>> = when (xs.isEmpty() || ys.isEmpty()) {
true -> listOf()
false -> Pair(xs.head, ys.head) + zip(xs.tail, ys.tail)
}
fun <T, R, C> zipWith(xs: List<T>, ys: List<R>, f: (T, R) -> C): List<C> =
zip(xs, ys).map { f(it.first, it.second) }
fun maxSum(xs: List<Int>) = zipWith(xs, xs.tail) { a, b -> a + b }.max()
fun <T> reverse(xs: List<T>) = reduce(listOf<T>(), xs)
{ ys, s -> s + ys }
fun sumWithEvenIndexes(xs: List<Int>) =
zip(xs, generateSequence(0) { it + 1 }.take(xs.size).toList())
.filter { it.second % 2 == 0 }
.map { it.first }
.sum
fun <T> reduceSame(xs: List<T>) = reduce(listOf<T>(), xs) { list, elem -> list + elem } | 0 | Kotlin | 0 | 0 | ab51d422a886a1b4d9ee35c8cfb2a1b3b82ba17b | 2,294 | KotlinByHaskell | MIT License |
2021/src/main/kotlin/de/skyrising/aoc2021/day13/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day13
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.ints.IntArrayList
import it.unimi.dsi.fastutil.ints.IntList
val test = TestInput("""
6,10
0,14
9,10
0,3
10,4
4,11
6,0
6,12
4,1
0,13
10,12
3,4
3,0
8,4
1,10
2,14
8,10
9,0
fold along y=7
fold along x=5
""")
@PuzzleName("Transparent Origami")
fun PuzzleInput.part1(): Any {
val (points, instructions) = readInput(this)
return fold(points, instructions.getInt(0)).size
}
fun PuzzleInput.part2(): Any {
val (points, instructions) = readInput(this)
var folded = points
for (i in instructions.indices) {
folded = fold(folded, instructions.getInt(i))
}
val max = folded.reduce { acc, pair -> Pair(maxOf(acc.first, pair.first), maxOf(acc.second, pair.second)) }
val result = StringBuilder((max.first + 2) * (max.second + 1) + 9)
val chars = Array(8) { CharArray(24) }
result.append('\n')
for (y in 0 .. max.second) {
if (y > 0) result.append('\n')
for (x in 0 .. max.first) {
val char = if (Pair(x, y) in folded) '█' else ' '
if (x % 5 < 4) {
chars[x / 5][y * 4 + (x % 5)] = char
}
result.append(char)
}
}
log(result)
return parseDisplay(result.toString())
}
private fun readInput(input: PuzzleInput): Pair<Set<Pair<Int, Int>>, IntList> {
val points = mutableSetOf<Pair<Int, Int>>()
val instructions = IntArrayList()
var i = 0
while (i < input.lines.size) {
val line = input.lines[i++]
if (line.isEmpty()) break
val (x, y) = line.split(',')
points.add(x.toInt() to y.toInt())
}
while (i < input.lines.size) {
val line = input.lines[i++]
if (line[11] == 'y') {
instructions.add(-line.substring(13).toInt())
} else {
instructions.add(line.substring(13).toInt())
}
}
return points to instructions
}
private fun fold(points: Set<Pair<Int, Int>>, axis: Int) = if (axis < 0) foldY(points, -axis) else foldX(points, axis)
private fun foldX(points: Set<Pair<Int, Int>>, axis: Int): Set<Pair<Int, Int>> {
val newPoints = HashSet<Pair<Int, Int>>(points.size)
for (p in points) {
if (p.first > axis) {
newPoints.add(2 * axis - p.first to p.second)
} else {
newPoints.add(p)
}
}
return newPoints
}
private fun foldY(points: Set<Pair<Int, Int>>, axis: Int): Set<Pair<Int, Int>> {
val newPoints = HashSet<Pair<Int, Int>>(points.size)
for (p in points) {
if (p.second > axis) {
newPoints.add(p.first to 2 * axis - p.second)
} else {
newPoints.add(p)
}
}
return newPoints
} | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,832 | aoc | MIT License |
src/main/kotlin/day17/Code.kt | fcolasuonno | 317,324,330 | false | null | package day17
import isDebug
import java.io.File
private val Triple<Int, Int, Int>.neighbours: Set<Triple<Int, Int, Int>>
get() = (-1..1).flatMap { d1 ->
(-1..1).flatMap { d2 ->
(-1..1).map { d3 ->
Triple(first + d1, second + d2, third + d3)
}
}
}.filter { it != this }.toSet()
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
fun parse(input: List<String>) = input.flatMapIndexed { y, s ->
s.mapIndexedNotNull { x, c -> c.takeIf { it == '#' }?.let { Triple(x, y, 0) } }
}.toSet()
fun part1(input: Set<Triple<Int, Int, Int>>) {
val res = generateSequence(input) { start ->
mutableSetOf<Triple<Int, Int, Int>>().apply {
start.filterTo(this) { each -> each.neighbours.count { it in start }.let { it == 2 || it == 3 } }
start.flatMapTo(mutableSetOf()) { it.neighbours }
.filterTo(this) { each -> each !in start && each.neighbours.count { it in start } == 3 }
}
}.elementAt(6).size
println("Part 1 = $res")
}
fun part2(input: Set<Triple<Int, Int, Int>>) {
val res = generateSequence(input.mapTo(mutableSetOf()) { Quadruple(it.first, it.second, it.third, 0) }) { start ->
mutableSetOf<Quadruple>().apply {
start.filterTo(this) { each -> each.neighbours.count { it in start }.let { it == 2 || it == 3 } }
start.flatMapTo(mutableSetOf()) { it.neighbours }
.filterTo(this) { each -> each !in start && each.neighbours.count { it in start } == 3 }
}
}.elementAt(6).size
println("Part 2 = $res")
}
data class Quadruple(
val first: Int,
val second: Int,
val third: Int,
val fourth: Int
) {
val neighbours: Set<Quadruple>
get() = (-1..1).flatMap { d1 ->
(-1..1).flatMap { d2 ->
(-1..1).flatMap { d3 ->
(-1..1).map { d4 ->
Quadruple(first + d1, second + d2, third + d3, fourth + d4)
}
}
}
}.filter { it != this }.toSet()
} | 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 2,305 | AOC2020 | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1071/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1071
/**
* LeetCode page: [1071. Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/);
*/
class Solution {
/* Complexity:
* Time O(|str1|+|str2|) and Space O(min(|str1|, |str2|));
*/
fun gcdOfStrings(str1: String, str2: String): String {
val potentialGcd = getPotentialGcd(str1, str2)
val isTrueGcd = str1.isRepeating(potentialGcd) && str2.isRepeating(potentialGcd)
return if (isTrueGcd) potentialGcd else ""
}
private fun getPotentialGcd(str1: String, str2: String): String {
/* If gcd exists, one can prove that the length of gcd is the gcd of str1.length
* and str2.length.
*/
val length = gcd(str1.length, str2.length)
return str1.slice(0 until length)
}
private tailrec fun gcd(a: Int, b: Int): Int {
require(a >= 0 && b >= 0)
val (large, small) = if (a >= b) a to b else b to a
return if (small == 0) large else gcd(small, large % small)
}
private fun String.isRepeating(baseStr: String): Boolean {
if (this.length % baseStr.length != 0) return false
if (this.length == baseStr.length) return this == baseStr
for (i in baseStr.length until this.length step baseStr.length) {
for (j in baseStr.indices) {
if (this[i + j] != this[i + j - baseStr.length]) {
return false
}
}
}
return true
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,542 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day15.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | import java.lang.IllegalStateException
import kotlin.math.abs
private const val i = 4000000
fun main() {
fun beacons(input: List<String>): List<Pair<Pair<Int, Int>, Pair<Int, Int>>> {
val a = input.map {
val m =
Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)").matchEntire(it)!!
val x1 = m.groups[1]!!.value.toInt()
val y1 = m.groups[2]!!.value.toInt()
val x2 = m.groups[3]!!.value.toInt()
val y2 = m.groups[4]!!.value.toInt()
Pair(Pair(x1, y1), Pair(x2, y2))
}
return a
}
fun getDistanceToBeacon(p: Pair<Pair<Int, Int>, Pair<Int, Int>>, x: Int, y: Int) =
abs(p.first.first - x) + abs(p.first.second - y)
fun getDistanceToBeacon(p: Pair<Pair<Int, Int>, Pair<Int, Int>>) =
getDistanceToBeacon(p, p.second.first, p.second.second)
fun part1(input: List<String>): Int {
val a = beacons(input)
val y = 2000000
return (-5000000..5000000).count { c ->
val any = a.any { p ->
val distanceToBeacon = getDistanceToBeacon(p)
val distanceToCandidate = abs(p.first.first - c) + abs(p.first.second - y)
p.first != Pair(c, y) && p.second != Pair(c, y) && distanceToBeacon >= distanceToCandidate
}
any
}
}
fun part2(input: List<String>): Long {
fun res(x: Int, y: Int): Long {
return x.toLong() * 4000000L + y.toLong()
}
val top = 4000000
fun canExistInAllBeacons(
a: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>,
x: Int,
y: Int
) = a.all { p ->
if (!(x in 0 .. top && y in 0 .. top)) false
else {
val distanceToBeacon = getDistanceToBeacon(p)
val distanceToCandidate = abs(p.first.first - x) + abs(p.first.second - y)
p.first != Pair(x, y) && p.second != Pair(x, y) && distanceToBeacon < distanceToCandidate
}
}
val a = beacons(input)
for (pair in a) {
val distanceToBeacon = getDistanceToBeacon(pair)
var y = pair.first.second
for (x in pair.first.first - distanceToBeacon - 1..pair.first.first) {
if (canExistInAllBeacons(a, x, y)) {
return res(x,y)
}
y--
}
for (x in pair.first.first..pair.first.first + distanceToBeacon + 1) {
if (canExistInAllBeacons(a, x, y)) {
return res(x,y)
}
y++
}
for (x in pair.first.first + distanceToBeacon + 1 downTo pair.first.first) {
if (canExistInAllBeacons(a, x, y)) {
return res(x,y)
}
y++
}
for (x in pair.first.first + distanceToBeacon + 1 downTo pair.first.first) {
if (canExistInAllBeacons(a, x, y)) {
return res(x,y)
}
y--
}
}
throw IllegalStateException()
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 3,299 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | kthun | 572,871,866 | false | {"Kotlin": 17958} | fun main() {
fun String.createElfRanges() = split(",")
.map { it.split("-") }
.map { it[0].toInt()..it[1].toInt() }
fun part1(input: List<String>): Int {
return input.count { line ->
val (elf1, elf2) = line.createElfRanges()
elf1 in elf2 || elf2 in elf1
}
}
fun part2(input: List<String>): Int {
return input.count { line ->
val (elf1, elf2) = line.createElfRanges()
elf1.first in elf2 || elf1.last in elf2 || elf2.first in elf1 || elf2.last in elf1
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
operator fun IntRange.contains(other: IntRange) = other.first in this && other.last in this
| 0 | Kotlin | 0 | 0 | 5452702e4e20ef2db3adc8112427c0229ebd1c29 | 868 | aoc-2022 | Apache License 2.0 |
2020/Day2/src/main/kotlin/main.kt | airstandley | 225,475,112 | false | {"Python": 104962, "Kotlin": 59337} | import java.io.File
data class PasswordPolicy(val char: Char, val first: Int = 0, val second: Int = 0)
fun getInput(): List<String> {
return File("Input").readLines()
}
private val linRegex = Regex("(\\d*)-(\\d*) (\\w): (\\w*)")
fun parseInputLine(line: String): Pair<PasswordPolicy, String>? {
// Input is formatted "min-max char: password"
val match = linRegex.find(line)
if (match != null) {
val values: List<String> = match.groupValues
return Pair(
PasswordPolicy(values[3][0], values[1].toInt(), values[2].toInt()),
values[4]
)
}
return null
}
fun countCharOccurrence(password: String, char: Char): Int {
// Count how many times char appears in password
var count = 0
password.forEach { passChar -> if (passChar == char) { count ++ } }
return count
}
fun isPasswordValidFirst(policy: PasswordPolicy, password: String): Boolean {
// Password contains at least first occurrences of char and not more than second
val count = countCharOccurrence(password, policy.char)
return policy.first <= count && count <= policy.second
}
fun isPasswordValidSecond(policy: PasswordPolicy, password: String): Boolean {
// Password contains char at first or second position, but not at both
val first = password[policy.first - 1] == policy.char
val second = password[policy.second - 1] == policy.char
return ((first && !second) || (second && !first))
}
fun countValidPasswords(lines: List<String>, validationMethod: (PasswordPolicy, String) -> Boolean): Int {
var count = 0
for (line in lines) {
val (policy, password) = parseInputLine(line) ?: continue
if (validationMethod(policy, password)) { count++ }
}
return count
}
fun main(args: Array<String>) {
val firstValidationMethod: (PasswordPolicy, String) -> Boolean = {
policy, password -> isPasswordValidFirst(policy, password)
}
println("First Solution: ${countValidPasswords(getInput(), firstValidationMethod)}")
val secondValidationMethod: (PasswordPolicy, String) -> Boolean = {
policy, password -> isPasswordValidSecond(policy, password)
}
println("Second Solution: ${countValidPasswords(getInput(), secondValidationMethod)}")
} | 0 | Python | 0 | 0 | 86b7e289d67ba3ea31a78f4a4005253098f47254 | 2,268 | AdventofCode | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day12.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year21
import com.grappenmaker.aoc.PuzzleSet
fun PuzzleSet.day12() = puzzle(day = 12) {
// Part one
val graph = inputLines.generateGraph()
// Initialize queue for BFS
val queue = ArrayDeque(listOf(Node("start")))
// Initialize counters
var result = 0
var additional = 0
// Perform BFS
while (queue.isNotEmpty()) {
// Pop first element, check if it is the destination (end)
val (name, visitedSmall, twice) = queue.removeFirst()
if (name == "end") {
if (twice == null) result++ else additional++
continue
}
// Go through all connected nodes
// and enqueue them if:
// 1. It is not "start"
// 2. For part one, it should not be small
// 3. For part two, it can be small at most twice
graph[name]?.forEach {
if (it == "start") return@forEach
if (it !in visitedSmall) {
queue.addLast(Node(it, buildSet {
addAll(visitedSmall)
if (it.isLowerCase()) add(it)
}, twice))
} else if (twice == null && it != "end") {
// Part two
// Checking for "end" here, because the node may contain
// "end" when it is not the twice visited cave,
// but it can't be end here, because then it wouldn't be
// visited twice
queue.addLast(Node(it, visitedSmall, it))
}
}
}
// Return the results of the search
partOne = result.s()
partTwo = (result + additional).s()
}
// Utility to check if full string is lowercase
fun String.isLowerCase() = all { it.isLowerCase() }
// Data class to keep track of all visited elements, and the current element
// It's called node because it is a node in the queue (elements in BFS are called nodes)
private data class Node(val name: String, val visitedSmall: Set<String> = setOf(), var visitedSmallTwice: String? = null)
// Generate graph (maths and cs data structure)
fun List<String>.generateGraph(): Map<String, List<String>> {
// 1. Maps everything to a List<Pair<String, String>>,
// which represents a list of key-value and value-key pairs,
// which then represent a vertex
// 2. Groups by key
// 3. Maps to value
// Result: Map of node to possible destination nodes
// or: a map of vertexes
return flatMap {
val split = it.split("-")
listOf(split[0] to split[1], split[1] to split[0])
}.groupBy { it.first }.mapValues { it.value.map { v -> v.second } }
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,636 | advent-of-code | The Unlicense |
src/main/kotlin/sort/HeapSort.kt | TheAlgorithms | 177,334,737 | false | {"Kotlin": 41212} | package sort
/**
* This function implements the Heap Sort.
*
* @param array The array to be sorted
* Sorts the array in increasing order
*
* Worst-case performance O(n*log(n))
* Best-case performance O(n*log(n))
* Average-case performance O(n*log(n))
* Worst-case space complexity O(1) (auxiliary)
*/
fun <T : Comparable<T>> heapSort(array: Array<T>) {
buildMaxHeap(array)
transformMaxHeapToSortedArray(array)
}
/**
* This function changes the element order of the array to represent a max
* binary tree.
*
* @param array The array containing the elements
* @param index Index of the currently largest element
*/
fun <T : Comparable<T>> maxheapify(array: Array<T>, heapSize: Int, index: Int) {
val left = 2 * index + 1
val right = 2 * index + 2
var largest = index
if (left < heapSize && array[left] > array[largest])
largest = left
if (right < heapSize && array[right] > array[largest])
largest = right
if (largest != index) {
swapElements(array, index, largest)
maxheapify(array, heapSize, largest)
}
}
/**
* Arrange the elements of the array to represent a max heap.
*
* @param array The array containing the elements
*/
private fun <T : Comparable<T>> buildMaxHeap(array: Array<T>) {
val n = array.size
for (i in (n / 2 - 1) downTo 0)
maxheapify(array, n, i)
}
/**
* Arrange the elements of the array, which should be in order to represent a
* max heap, into ascending order.
*
* @param array The array containing the elements (max heap representation)
*/
private fun <T : Comparable<T>> transformMaxHeapToSortedArray(array: Array<T>) {
for (i in (array.size - 1) downTo 0) {
swapElements(array, i, 0)
maxheapify(array, i, 0)
}
}
| 62 | Kotlin | 369 | 1,221 | e57a8888dec4454d39414082bbe6a672a9d27ad1 | 1,791 | Kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.